Skip to content

Commit 38379f5

Browse files
author
Shakeel Mohamed
committed
Event, EventWriter, and tests are done; need to elaborate docstrings.
Also added newer test data, and minor tweaks throughout.
1 parent e7b001e commit 38379f5

8 files changed

Lines changed: 75 additions & 81 deletions

File tree

‎splunklib/modularinput/event.py‎

Lines changed: 17 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -12,17 +12,12 @@
1212
# License for the specific language governing permissions and limitations
1313
# under the License.
1414

15-
import sys, time
16-
1715
try:
1816
import xml.etree.cElementTree as ET
1917
except ImportError as ie:
2018
import xml.etree.ElementTree as ET
2119

22-
try:
23-
import cStringIO as StringIO
24-
except ImportError as ie:
25-
import StringIO
20+
#todo: extend the docs. What would you want to know about this class if you were faced with it for the first time and had to use it?
2621

2722
class Event(object):
2823
"""Represents an event or fragment of an event to be written by this modular input to Splunk."""
@@ -50,32 +45,24 @@ def write_to(self, stream):
5045
event.set("stanza", self.stanza)
5146
event.set("unbroken", str(int(self.unbroken)))
5247

53-
if(self.time):
54-
epoch_time = self.time
55-
else:
56-
epoch_time = time.time()
48+
# if a time isn't set, let Splunk guess by not creating a <time> element
49+
if self.time:
50+
ET.SubElement(event, "time").text = str(self.time)
5751

58-
create_subelement(event, "time", str(epoch_time))
59-
create_subelement(event, "source", self.source)
60-
create_subelement(event, "sourceType", self.sourceType)
61-
create_subelement(event, "index", self.index)
62-
create_subelement(event, "host", self.host)
63-
create_subelement(event, "data", self.data)
52+
# add all other subelements to this event
53+
subElements = [
54+
("source", self.source),
55+
("sourceType", self.sourceType),
56+
("index", self.index),
57+
("host", self.host),
58+
("data", self.data)
59+
]
60+
for node, value in subElements:
61+
if value:
62+
ET.SubElement(event, node).text = value
6463

65-
if not self.unbroken and self.done:
64+
if self.done:
6665
done = ET.SubElement(event, "done")
6766

6867
stream.write(ET.tostring(event))
69-
sys.stdout.flush()
70-
71-
def create_subelement(parent, name, text):
72-
"""Create an XML subelement with tag and text specified
73-
74-
:param parent: parent XML element
75-
:param name: name of XML node tag
76-
:param text: text to go inside <name>
77-
"""
78-
if not text:
79-
return
80-
subelement = ET.SubElement(parent, name)
81-
subelement.text = text
68+
stream.flush()

‎splunklib/modularinput/event_writer.py‎

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,16 @@
1212
# License for the specific language governing permissions and limitations
1313
# under the License.
1414

15-
from splunklib.modularinput.event import Event, ET, StringIO
15+
from splunklib.modularinput.event import Event, ET
1616
import sys
1717

18+
try:
19+
from cStringIO import StringIO
20+
except ImportError:
21+
from StringIO import StringIO
22+
23+
#todo: extend the docs. What would you want to know about this class if you were faced with it for the first time and had to use it?
24+
1825
class EventWriter(object):
1926
"""EventWriter writes events and error messages to Splunk from a modular input."""
2027
def __init__(self, output = sys.stdout, error = sys.stderr):
@@ -29,9 +36,10 @@ def __init__(self, output = sys.stdout, error = sys.stderr):
2936
self.ERROR = "ERROR"
3037
self.FATAL = "FATAL"
3138

32-
self.output_writer = output
33-
self.error_writer = error
39+
self._out = output
40+
self._err = error
3441

42+
# has the opening <stream> tag been written yet?
3543
self.header_written = False
3644

3745
def write_event(self, event):
@@ -41,12 +49,10 @@ def write_event(self, event):
4149
"""
4250

4351
if not self.header_written:
44-
self.output_writer.write("<stream>")
52+
self._out.write("<stream>")
4553
self.header_written = True
46-
#try:
47-
event.write_to(self.output_writer)
48-
#except ValueError as ve:
49-
#self.log(self.WARN, ve.message)
54+
55+
event.write_to(self._out)
5056

5157
def log(self, severity, message):
5258
"""Log messages about the state of this modular input to Splunk. These messages will show up in Splunk's
@@ -56,20 +62,17 @@ def log(self, severity, message):
5662
:param message: message to log
5763
"""
5864

59-
self.error_writer.write("%s %s\n" % (severity, message))
60-
self.error_writer.flush()
65+
self._err.write("%s %s\n" % (severity, message))
66+
self._err.flush()
6167

6268
def write_xml_document(self, document):
6369
"""Write an ElementTree to the output stream
6470
6571
:param document: an ElementTree object
6672
"""
67-
stream = StringIO.StringIO()
68-
stream.write(ET.tostring(document, "us-ascii", "xml"))
69-
stream.flush()
70-
self.output_writer.write(stream.getvalue())
71-
self.output_writer.flush()
73+
self._out.write(ET.tostring(document, "utf-8", "xml"))
74+
self._out.flush()
7275

7376
def close(self):
7477
"""Write the closing </stream> tag to make this XML well formed."""
75-
self.output_writer.write("</stream>")
78+
self._out.write("</stream>")

‎splunklib/modularinput/modularinput_testlib.py‎

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -56,33 +56,32 @@ def xml_compare(expected, found):
5656
:param found: an ElementTree object
5757
:return: boolean, equality of expected and found
5858
"""
59-
#TODO: error handling & exception throwing
60-
61-
try:
62-
import xml.etree.cElementTree as ET
63-
except ImportError:
64-
import xml.etree.ElementTree as ET
6559

6660
# if comparing the same ET object
6761
if expected == found:
6862
return True
6963

7064
# compare element attributes, ignoring order
71-
if not set(expected.items()) == set(found.items()):
65+
if set(expected.items()) != set(found.items()):
7266
return False
67+
68+
# check for equal number of children
7369
expectedChildren = list(expected)
7470
foundChildren = list(found)
7571
if len(expectedChildren) != len(foundChildren):
7672
return False
7773

7874
# compare children
79-
for i, child in enumerate(expectedChildren):
80-
if not xml_compare(child, foundChildren[i]):
81-
return False
75+
if not all([xml_compare(a, b) for a, b in zip(expectedChildren, foundChildren)]):
76+
return False
77+
8278
# compare element text if it exists, else elements are equal
8379
if expected.text and expected.text.strip() != "":
8480
if expected.tag == found.tag and expected.text == found.text:
85-
return True
81+
if expected.attrib == found.attrib:
82+
return True
83+
else:
84+
return False
8685
else:
8786
return False
8887
else:

‎tests/modularinput/data/event_maximal.xml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,5 @@
55
<index>main</index>
66
<host>localhost</host>
77
<data>This is a test of the emergency broadcast system.</data>
8+
<done/>
89
</event>
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
<event stanza="fubar" unbroken="1">
22
<time>1372187084.000</time>
33
<data>This is a test of the emergency broadcast system.</data>
4+
<done/>
45
</event>

‎tests/modularinput/data/stream_with_one_event.xml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,6 @@
66
<index>main</index>
77
<host>localhost</host>
88
<data>This is a test of the emergency broadcast system.</data>
9+
<done/>
910
</event>
1011
</stream>

‎tests/modularinput/data/stream_with_two_events.xml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
<index>main</index>
77
<host>localhost</host>
88
<data>This is a test of the emergency broadcast system.</data>
9+
<done/>
910
</event>
1011
<event stanza="fubar" unbroken="1">
1112
<time>1372275124.466</time>
@@ -14,5 +15,6 @@
1415
<index>main</index>
1516
<host>localhost</host>
1617
<data>This is a test of the emergency broadcast system.</data>
18+
<done/>
1719
</event>
1820
</stream>

‎tests/modularinput/test_event.py‎

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -16,26 +16,22 @@
1616

1717
from splunklib.modularinput.modularinput_testlib import unittest, xml_compare
1818
from splunklib.modularinput.event import Event, ET
19-
from splunklib.modularinput.event_writer import EventWriter
20-
21-
try:
22-
import cStringIO as StringIO
23-
except ImportError:
24-
import StringIO
19+
from splunklib.modularinput.event_writer import EventWriter, StringIO
2520

2621
class EventTestCase(unittest.TestCase):
2722
def test_event_without_enough_fields_fails(self):
2823
"""Check that events without data throw an error"""
2924
with self.assertRaises(ValueError):
3025
event = Event()
31-
stream = StringIO.StringIO()
26+
stream = StringIO()
3227
event.write_to(stream)
3328
self.assertTrue(True)
3429

3530
def test_xml_of_event_with_minimal_configuration(self):
36-
"""Generate XML from an event object with a small number of fields, and see if it matches what we expect."""
31+
"""Generate XML from an event object with a small number of fields,
32+
and see if it matches what we expect."""
3733

38-
stream = StringIO.StringIO()
34+
stream = StringIO()
3935
event = Event()
4036
event.time = "%.3f" % 1372187084.000
4137
event.stanza = "fubar"
@@ -48,8 +44,9 @@ def test_xml_of_event_with_minimal_configuration(self):
4844
self.assertTrue(xml_compare(expected, constructed))
4945

5046
def test_xml_of_event_with_more_configuration(self):
51-
"""Generate XML from an even object with all fields set, see if it matches what we expect"""
52-
stream = StringIO.StringIO()
47+
"""Generate XML from an even object with all fields set, see if
48+
it matches what we expect"""
49+
stream = StringIO()
5350

5451
event = Event()
5552
event.stanza = "fubar"
@@ -69,10 +66,10 @@ def test_xml_of_event_with_more_configuration(self):
6966
self.assertTrue(xml_compare(expected, constructed))
7067

7168
def test_writing_events_on_event_writer(self):
72-
"""Write a pair of events with an EventWriter, and ensure that they are
73-
being encoded immediately and correctly onto the output stream"""
74-
out = StringIO.StringIO()
75-
err = StringIO.StringIO()
69+
"""Write a pair of events with an EventWriter, and ensure that they
70+
are being encoded immediately and correctly onto the output stream"""
71+
out = StringIO()
72+
err = StringIO()
7673

7774
ew = EventWriter(out, err)
7875

@@ -103,10 +100,11 @@ def test_writing_events_on_event_writer(self):
103100
self.assertTrue(xml_compare(expected, found))
104101

105102
def test_error_in_event_writer(self):
106-
"""An event which cannot write itself onto an output stream (such as because it doesn't have a data field set)
103+
"""An event which cannot write itself onto an output stream
104+
(such as because it doesn't have a data field set)
107105
should write an error. Check that it does so."""
108-
out = StringIO.StringIO()
109-
err = StringIO.StringIO()
106+
out = StringIO()
107+
err = StringIO()
110108

111109
ew = EventWriter(out, err)
112110
e = Event()
@@ -116,9 +114,10 @@ def test_error_in_event_writer(self):
116114
self.assertTrue(err.getvalue().startswith(ew.WARN))
117115

118116
def test_logging_errors_with_event_writer(self):
119-
"""Check that the log method on EventWriter produces the expected error message."""
120-
out = StringIO.StringIO()
121-
err = StringIO.StringIO()
117+
"""Check that the log method on EventWriter produces the
118+
expected error message."""
119+
out = StringIO()
120+
err = StringIO()
122121

123122
ew = EventWriter(out, err)
124123

@@ -127,9 +126,10 @@ def test_logging_errors_with_event_writer(self):
127126
self.assertEqual("ERROR Something happened!\n", err.getvalue())
128127

129128
def test_write_xml_is_sane(self):
130-
"""Check that EventWriter.writeXmlDocument writes sensible XML to the output stream."""
131-
out = StringIO.StringIO()
132-
err = StringIO.StringIO()
129+
"""Check that EventWriter.writeXmlDocument writes sensible
130+
XML to the output stream."""
131+
out = StringIO()
132+
err = StringIO()
133133

134134
ew = EventWriter(out, err)
135135

0 commit comments

Comments
 (0)