Skip to content

SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.

tests: Update TestSpiderFootPlugin tests

Brendan Coles95fdbf1e8328
diff --git a/sflib.py b/sflib.py
index ada18707..6d31c55a 100644
--- a/sflib.py
+++ b/sflib.py
@@ -2395,71 +2395,108 @@ class SpiderFootPlugin(object):
# Error state of the module
errorState = False
-
- # Not really needed in most cases.
def __init__(self):
+ """Not really needed in most cases."""
pass
- # Hack to override module's use of socket, replacing it with
- # one that uses the supplied SOCKS server
def _updateSocket(self, socksProxy):
+ """Hack to override module's use of socket, replacing it with
+ one that uses the supplied SOCKS server."""
self.socksProxy = socksProxy
- # Used to clear any listener relationships, etc. This is needed because
- # Python seems to cache local variables even between threads.
def clearListeners(self):
+ """Used to clear any listener relationships, etc. This is needed because
+ Python seems to cache local variables even between threads."""
+
self._listenerModules = list()
self._stopScanning = False
- # Will always be overriden by the implementer.
def setup(self, sf, userOpts=dict()):
+ """Will always be overriden by the implementer."""
pass
- # Hardly used, only in special cases where a module can find
- # aliases for a target.
def enrichTarget(self, target):
+ """Hardly used, only in special cases where a module can find
+ aliases for a target."""
pass
- # Assigns the current target this module is acting against
def setTarget(self, target):
+ """Assigns the current target this module is acting against.
+
+ Args:
+ target (str): target
+ """
self._currentTarget = target
- # Used to set the database handle, which is only to be used
- # by modules in very rare/exceptional cases (e.g. sfp__stor_db)
def setDbh(self, dbh):
+ """Used to set the database handle, which is only to be used
+ by modules in very rare/exceptional cases (e.g. sfp__stor_db)
+
+ Args:
+ dbh (SpiderFootDb): database handle
+ """
self.__sfdb__ = dbh
- # Set the scan ID
def setScanId(self, id):
+ """Set the scan ID.
+
+ Args:
+ id (str): scan ID
+ """
self.__scanId__ = id
- # Get the scan ID
def getScanId(self):
+ """Get the scan ID.
+
+ Returns:
+ str: scan ID
+ """
return self.__scanId__
- # Gets the current target this module is acting against
def getTarget(self):
+ """Gets the current target this module is acting against."""
+
if self._currentTarget is None:
print("Internal Error: Module called getTarget() but no target set.")
sys.exit(-1)
return self._currentTarget
- # Listener modules which will get notified once we have data for them to
- # work with.
def registerListener(self, listener):
+ """Listener modules which will get notified once we have data for them to
+ work with.
+
+ Args:
+ listener: TBD
+ """
+
self._listenerModules.append(listener)
def setOutputFilter(self, types):
self.__outputFilter__ = types
- # For SpiderFoot HX compatability of modules
def tempStorage(self):
+ """Module temporary storage.
+
+ Note:
+ For SpiderFoot HX compatability of modules.
+
+ Returns:
+ dict: TB
+ """
return dict()
- # Call the handleEvent() method of every other plug-in listening for
- # events from this plug-in. Remember that those plug-ins will be called
- # within the same execution context of this thread, not on their own.
def notifyListeners(self, sfEvent):
+ """Call the handleEvent() method of every other plug-in listening for
+ events from this plug-in. Remember that those plug-ins will be called
+ within the same execution context of this thread, not on their own.
+
+ Args:
+ sfEvent (SpiderFootEvent): event
+ """
+
+ if not isinstance(sfEvent, SpiderFootEvent):
+ raise TypeError("sfEvent is %s; expected SpiderFootEvent" % type(sfEvent))
+
eventName = sfEvent.eventType
if self.__outputFilter__:
@@ -2535,44 +2572,66 @@ class SpiderFootPlugin(object):
exc_type, exc_value, exc_traceback = sys.exc_info()
f.write(repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
- # For modules to use to check for when they should give back control
def checkForStop(self):
+ """For modules to use to check for when they should give back control.
+
+ Returns:
+ bool
+ """
+
scanstatus = self.__sfdb__.scanInstanceGet(self.__scanId__)
- #Ensure that scanStatus is not None
if scanstatus != None:
if scanstatus[5] == "ABORT-REQUESTED":
-
return True
return False
- # Return a list of the default configuration options for the module.
- def defaultOpts(self):
- return self.opts
-
- # What events is this module interested in for input. The format is a list
- # of event types that are applied to event types that this module wants to
- # be notified of, or * if it wants everything.
- # Will usually be overriden by the implementer, unless it is interested
- # in all events (default behavior).
def watchedEvents(self):
+ """What events is this module interested in for input. The format is a list
+ of event types that are applied to event types that this module wants to
+ be notified of, or * if it wants everything.
+ Will usually be overriden by the implementer, unless it is interested
+ in all events (default behavior).
+
+ Returns:
+ list: list of events this modules watches
+ """
+
return ['*']
- # What events this module produces
- # This is to support the end user in selecting modules based on events
- # produced.
def producedEvents(self):
- return None
+ """What events this module produces
+ This is to support the end user in selecting modules based on events
+ produced.
+
+ Returns:
+ list: list of events produced by this module
+ """
+
+ return []
- # Handle events to this module
- # Will usually be overriden by the implementer, unless it doesn't handle
- # any events.
def handleEvent(self, sfEvent):
+ """Handle events to this module.
+ Will usually be overriden by the implementer, unless it doesn't handle
+ any events.
+
+ Args:
+ sfEvent (SpiderFootEvent): event
+
+ Returns:
+ None
+ """
+
return None
- # Kick off the work (for some modules nothing will happen here, but instead
- # the work will start from the handleEvent() method.
- # Will usually be overriden by the implementer.
def start(self):
+ """Kick off the work (for some modules nothing will happen here, but instead
+ the work will start from the handleEvent() method.
+ Will usually be overriden by the implementer.
+
+ Returns:
+ None
+ """
+
return None
diff --git a/test/unit/test_spiderfootplugin.py b/test/unit/test_spiderfootplugin.py
index 2cfd753f..564d9be0 100644
--- a/test/unit/test_spiderfootplugin.py
+++ b/test/unit/test_spiderfootplugin.py
@@ -1,6 +1,7 @@
# test_spiderfootplugin.py
import sflib
-from sflib import SpiderFootPlugin, SpiderFootEvent
+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent
+from sfdb import SpiderFootDb
import unittest
class TestSpiderFootPlugin(unittest.TestCase):
@@ -8,12 +9,40 @@ class TestSpiderFootPlugin(unittest.TestCase):
Test SpiderFoot
"""
+ default_options = {
+ '_debug': False, # Debug
+ '__logging': True, # Logging in general
+ '__outputfilter': None, # Event types to filter from modules' output
+ '__blocknotif': False, # Block notifications
+ '_fatalerrors': False,
+ '_useragent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0', # User-Agent to use for HTTP requests
+ '_dnsserver': '', # Override the default resolver
+ '_fetchtimeout': 5, # number of seconds before giving up on a fetch
+ '_internettlds': 'https://publicsuffix.org/list/effective_tld_names.dat',
+ '_internettlds_cache': 72,
+ '_genericusers': "abuse,admin,billing,compliance,devnull,dns,ftp,hostmaster,inoc,ispfeedback,ispsupport,list-request,list,maildaemon,marketing,noc,no-reply,noreply,null,peering,peering-notify,peering-request,phish,phishing,postmaster,privacy,registrar,registry,root,routing-registry,rr,sales,security,spam,support,sysadmin,tech,undisclosed-recipients,unsubscribe,usenet,uucp,webmaster,www",
+ '__version__': '3.0',
+ '__database': 'spiderfoot.test.db', # note: test database file
+ '__webaddr': '127.0.0.1',
+ '__webport': 5001,
+ '__docroot': '', # don't put trailing /
+ '__modules__': None, # List of modules. Will be set after start-up.
+ '_socks1type': '',
+ '_socks2addr': '',
+ '_socks3port': '',
+ '_socks4user': '',
+ '_socks5pwd': '',
+ '_socks6dns': True,
+ '_torctlport': 9051,
+ '__logstdout': False
+ }
+
def test_init(self):
"""
Test __init__(self)
"""
sfp = SpiderFootPlugin()
- self.assertEqual(SpiderFootPlugin, type(sfp))
+ self.assertIsInstance(sfp, SpiderFootPlugin)
def test_update_socket(self):
"""
@@ -33,7 +62,6 @@ class TestSpiderFootPlugin(unittest.TestCase):
sfp.clearListeners()
self.assertEqual('TBD', 'TBD')
- @unittest.skip("overridden function")
def test_setup(self):
"""
Test setup(self, sf, userOpts=dict())
@@ -41,8 +69,9 @@ class TestSpiderFootPlugin(unittest.TestCase):
sfp = SpiderFootPlugin()
sfp.setup(None)
+ sfp.setup(None, None)
+ self.assertEqual('TBD', 'TBD')
- @unittest.skip("overridden function")
def test_enrich_target(self):
"""
Test enrichTarget(self, target)
@@ -50,24 +79,30 @@ class TestSpiderFootPlugin(unittest.TestCase):
sfp = SpiderFootPlugin()
sfp.enrichTarget(None)
+ self.assertEqual('TBD', 'TBD')
- def test_set_target(self):
+ def test_set_target_should_set_a_target(self):
"""
Test setTarget(self, target)
"""
sfp = SpiderFootPlugin()
- sfp.setTarget(None)
- self.assertEqual('TBD', 'TBD')
+ target = 'spiderfoot.net'
+ sfp.setTarget(target)
+
+ get_target = sfp.getTarget()
+ self.assertIsInstance(get_target, str)
+ self.assertEqual(target, get_target)
def test_set_dbh(self):
"""
Test setDbh(self, dbh)
"""
+ sfdb = SpiderFootDb(self.default_options, False)
sfp = SpiderFootPlugin()
- sfp.setDbh(None)
- self.assertEqual('TBD', 'TBD')
+ sfp.setDbh(sfdb)
+ self.assertIsInstance(sfp.__sfdb__, SpiderFootDb)
def test_set_scan_id(self):
"""
@@ -101,7 +136,7 @@ class TestSpiderFootPlugin(unittest.TestCase):
sfp.setTarget(target)
get_target = sfp.getTarget()
- self.assertEqual(str, type(get_target))
+ self.assertIsInstance(get_target, str)
self.assertEqual(target, get_target)
def test_get_target_invalid_target_should_exit(self):
@@ -119,13 +154,20 @@ class TestSpiderFootPlugin(unittest.TestCase):
"""
Test registerListener(self, listener)
"""
+ sfp = SpiderFootPlugin()
+ sfp.registerListener(None)
+
self.assertEqual('TBD', 'TBD')
- def test_set_output_filter(self):
+ def test_set_output_filter_should_set_output_filter(self):
"""
Test setOutputFilter(self, types)
"""
- self.assertEqual('TBD', 'TBD')
+ sfp = SpiderFootPlugin()
+
+ output_filter = "test filter"
+ sfp.setOutputFilter("test filter")
+ self.assertEqual(output_filter, sfp.__outputFilter__)
def test_temp_storage_should_return_a_dict(self):
"""
@@ -139,20 +181,45 @@ class TestSpiderFootPlugin(unittest.TestCase):
def test_notify_listeners(self):
"""
Test notifyListeners(self, sfEvent)
+
+ Todo:
+ Test with source event
"""
+ sfp = SpiderFootPlugin()
+
+ class DatabaseStub:
+ def scanInstanceGet(self, scanId):
+ return [None, None, None, None, None, None]
+
+ sfp.__sfdb__ = DatabaseStub()
+
event_type = 'ROOT'
- event_data = ''
- module = ''
- source_event = ''
+ event_data = 'test data'
+ module = 'test module'
+ source_event = None #SpiderFootEvent("ROOT", '', '', "ROOT")
evt = SpiderFootEvent(event_type, event_data, module, source_event)
-
- sfp = SpiderFootPlugin()
sfp.notifyListeners(evt)
+
self.assertEqual('TBD', 'TBD')
+ def test_notify_listeners_invalid_event_should_raise(self):
+ """
+ Test notifyListeners(self, sfEvent)
+ """
+ sfp = SpiderFootPlugin()
+
+ invalid_types = [None, "", list(), dict()]
+ for invalid_type in invalid_types:
+ with self.subTest(invalid_type=invalid_type):
+ with self.assertRaises(TypeError) as cm:
+ sfp.notifyListeners(None)
+
def test_check_for_stop(self):
"""
Test checkForStop(self)
+
+ Todo:
+ include other statuses for completeness
"""
sfp = SpiderFootPlugin()
@@ -163,22 +230,10 @@ class TestSpiderFootPlugin(unittest.TestCase):
sfp.__sfdb__ = DatabaseStub()
# pseudo-parameterized test
- # TODO could include other statuses for completeness
for status, expectedReturnValue in [("RUNNING", False), ("ABORT-REQUESTED", True)]:
returnValue = sfp.checkForStop()
self.assertEqual(returnValue, expectedReturnValue, status)
- @unittest.skip("unused function")
- def test_default_opts_should_return_a_dict(self):
- """
- Test defaultOpts(self)
- """
- sfp = SpiderFootPlugin()
-
- default_opts = sfp.defaultOpts()
- self.assertEqual(dict, type(default_opts))
-
- @unittest.skip("overridden function")
def test_watched_events_should_return_a_list(self):
"""
Test watchedEvents(self)
@@ -186,9 +241,8 @@ class TestSpiderFootPlugin(unittest.TestCase):
sfp = SpiderFootPlugin()
watched_events = sfp.watchedEvents()
- self.assertEqual(list, type(watched_events))
+ self.assertIsInstance(watched_events, list)
- @unittest.skip("overridden function")
def test_produced_events_should_return_a_list(self):
"""
Test producedEvents(self)
@@ -196,9 +250,8 @@ class TestSpiderFootPlugin(unittest.TestCase):
sfp = SpiderFootPlugin()
produced_events = sfp.producedEvents()
- self.assertEqual(list, type(produced_events))
+ self.assertIsInstance(produced_events, list)
- @unittest.skip("overridden function")
def test_handle_event(self):
"""
Test handleEvent(self, sfEvent)
@@ -212,7 +265,6 @@ class TestSpiderFootPlugin(unittest.TestCase):
sfp = SpiderFootPlugin()
sfp.handleEvent(evt)
- @unittest.skip("overridden function")
def test_start(self):
"""
Test start(self)