Commit bbbf7911 by Mariusz Kupidura Committed by GitHub

Refactor tests (#332)

* Move tests to tests/ directory
* Remove unused `tox.ini` file
* Add flake8 compliance
* Add `lint` target to `tests` target in the Makefile
parent 550bcf44
...@@ -10,4 +10,4 @@ if [[ "$(uname -s)" == "Darwin" ]]; then ...@@ -10,4 +10,4 @@ if [[ "$(uname -s)" == "Darwin" ]]; then
source ~/.venv/bin/activate source ~/.venv/bin/activate
fi fi
make tests lint make lint tests
\ No newline at end of file \ No newline at end of file
...@@ -11,7 +11,7 @@ run: ...@@ -11,7 +11,7 @@ run:
docker run -it --rm $(RSF_IMAGE) docker run -it --rm $(RSF_IMAGE)
lint: lint:
flake8 --exclude=__init__.py --ignore=$(FLAKE8_IGNORED_RULES) $(MODULES) flake8 --exclude=__init__.py --ignore=$(FLAKE8_IGNORED_RULES) tests $(MODULES)
tests: clean tests: clean
ifeq ($(MODULES), routersploit) ifeq ($(MODULES), routersploit)
......
from routersploit.test.test_case import RoutersploitTestCase
import unittest
import logging import logging
import unittest
from routersploit.utils import NonStringIterable from routersploit.utils import NonStringIterable
logging.getLogger().addHandler(logging.NullHandler()) logging.getLogger().addHandler(logging.NullHandler())
...@@ -17,7 +16,8 @@ class RoutersploitTestCase(unittest.TestCase): ...@@ -17,7 +16,8 @@ class RoutersploitTestCase(unittest.TestCase):
self.assertIn( self.assertIn(
decorator_name, decorator_name,
decorator_list, decorator_list,
msg="'{}' method should be decorated with 'module_required'".format(function.__name__) msg="'{}' method should be decorated "
"with 'module_required'".format(function.__name__)
) )
def assertIsSubset(self, subset, container): def assertIsSubset(self, subset, container):
......
import unittest
import os import os
import unittest
import pexpect import pexpect
from routersploit.test import RoutersploitTestCase from tests.test_case import RoutersploitTestCase
class RoutersploitCompleterTest(RoutersploitTestCase): class RoutersploitCompleterTest(RoutersploitTestCase):
def __init__(self, methodName='runTest'): def __init__(self, methodName='runTest'):
super(RoutersploitCompleterTest, self).__init__(methodName) super(RoutersploitCompleterTest, self).__init__(methodName)
self.cli_path = os.path.abspath(os.path.join(__file__, os.pardir, os.pardir, os.pardir, 'rsf.py')) self.cli_path = os.path.abspath(
os.path.join(__file__, os.pardir, os.pardir, 'rsf.py')
)
self.raw_prompt = "\033[4mrsf\033[0m > " self.raw_prompt = "\033[4mrsf\033[0m > "
self.module_prompt = lambda x: "\033[4mrsf\033[0m (\033[91m{}\033[0m) > ".format(x) self.module_prompt = lambda \
x: "\033[4mrsf\033[0m (\033[91m{}\033[0m) > ".format(x)
def setUp(self): def setUp(self):
self.rsf = pexpect.spawn('python {}'.format(self.cli_path)) self.rsf = pexpect.spawn('python {}'.format(self.cli_path))
...@@ -32,7 +34,9 @@ class RoutersploitCompleterTest(RoutersploitTestCase): ...@@ -32,7 +34,9 @@ class RoutersploitCompleterTest(RoutersploitTestCase):
def test_raw_commands_no_module(self): def test_raw_commands_no_module(self):
self.rsf.send("\t\t") self.rsf.send("\t\t")
self.assertPrompt('exec exit help search show use \r\n', self.raw_prompt) self.assertPrompt(
'exec exit help search show use \r\n',
self.raw_prompt)
def test_complete_use_raw(self): def test_complete_use_raw(self):
self.rsf.send("u\t\t") self.rsf.send("u\t\t")
...@@ -249,7 +253,8 @@ class RoutersploitCompleterTest(RoutersploitTestCase): ...@@ -249,7 +253,8 @@ class RoutersploitCompleterTest(RoutersploitTestCase):
self.set_module() self.set_module()
self.rsf.send("show \t\t") self.rsf.send("show \t\t")
self.assertPrompt( self.assertPrompt(
'all creds devices exploits info options scanners\r\n', 'all creds devices exploits '
'info options scanners\r\n',
self.module_prompt('FTP Bruteforce') self.module_prompt('FTP Bruteforce')
) )
......
import unittest
import os import os
import unittest
try: import mock
import unittest.mock as mock
except ImportError:
import mock
from routersploit.test import RoutersploitTestCase from routersploit.exploits import Exploit, GLOBAL_OPTS, Option
from routersploit.exploits import Exploit, Option, GLOBAL_OPTS from tests.test_case import RoutersploitTestCase
def suffix(x): def suffix(x):
...@@ -29,8 +26,10 @@ class TestExploitBar(Exploit): ...@@ -29,8 +26,10 @@ class TestExploitBar(Exploit):
class TestExploitWithValidators(Exploit): class TestExploitWithValidators(Exploit):
doo = Option(default="default_value", description="description_three", validators=suffix) doo = Option(default="default_value", description="description_three",
paa = Option(default="default_value", description="description_three", validators=(suffix, SUFFIX)) validators=suffix)
paa = Option(default="default_value", description="description_three",
validators=(suffix, SUFFIX))
class OptionTest(RoutersploitTestCase): class OptionTest(RoutersploitTestCase):
...@@ -66,7 +65,8 @@ class OptionTest(RoutersploitTestCase): ...@@ -66,7 +65,8 @@ class OptionTest(RoutersploitTestCase):
def test_if_validator_is_applied_in_specific_order(self): def test_if_validator_is_applied_in_specific_order(self):
self.exploit_with_validators.paa = "new_value" self.exploit_with_validators.paa = "new_value"
self.assertEqual(self.exploit_with_validators.paa, "new_value_suffix_SUFFIX") self.assertEqual(self.exploit_with_validators.paa,
"new_value_suffix_SUFFIX")
def test_if_exploit_option_is_picked_up_before_global(self): def test_if_exploit_option_is_picked_up_before_global(self):
GLOBAL_OPTS['doo'] = 'global_doo' GLOBAL_OPTS['doo'] = 'global_doo'
...@@ -85,9 +85,11 @@ class OptionTest(RoutersploitTestCase): ...@@ -85,9 +85,11 @@ class OptionTest(RoutersploitTestCase):
self.assertEqual(self.exploit_with_validators.doo, 'global_doo_suffix') self.assertEqual(self.exploit_with_validators.doo, 'global_doo_suffix')
def test_str_representation(self): def test_str_representation(self):
with mock.patch.object(TestExploitFoo, "__module__", new_callable=mock.PropertyMock) as mock_module: with mock.patch.object(TestExploitFoo, "__module__",
new_callable=mock.PropertyMock) as mock_module:
mock_module.return_value = "routersploit.modules.exploits.foo.bar" mock_module.return_value = "routersploit.modules.exploits.foo.bar"
self.assertEqual(str(TestExploitFoo()), os.path.join('exploits', 'foo', 'bar')) self.assertEqual(str(TestExploitFoo()),
os.path.join('exploits', 'foo', 'bar'))
def test_exploit_options_property(self): def test_exploit_options_property(self):
self.assertEqual(self.exploit_bar.options, ['paa', 'target', 'doo']) self.assertEqual(self.exploit_bar.options, ['paa', 'target', 'doo'])
......
import unittest
import os import os
import unittest
try: import mock
import unittest.mock as mock
except ImportError:
import mock
from routersploit.exploits import Exploit, Option, GLOBAL_OPTS from routersploit.exploits import Exploit, Option, GLOBAL_OPTS
from routersploit.interpreter import RoutersploitInterpreter from routersploit.interpreter import RoutersploitInterpreter
from routersploit.test import RoutersploitTestCase from tests.test_case import RoutersploitTestCase
class TestExploitFoo(Exploit): class TestExploitFoo(Exploit):
...@@ -17,16 +14,19 @@ class TestExploitFoo(Exploit): ...@@ -17,16 +14,19 @@ class TestExploitFoo(Exploit):
class RoutersploitInterpreterTest(RoutersploitTestCase): class RoutersploitInterpreterTest(RoutersploitTestCase):
def setUp(self): def setUp(self):
RoutersploitInterpreter.setup = mock.Mock() RoutersploitInterpreter.setup = mock.Mock()
self.interpreter = RoutersploitInterpreter() self.interpreter = RoutersploitInterpreter()
self.interpreter.current_module = mock.MagicMock() self.interpreter.current_module = mock.MagicMock()
self.raw_prompt_default = "\001\033[4m\002rsf\001\033[0m\002 > " self.raw_prompt_default = "\001\033[4m\002rsf\001\033[0m\002 > "
self.module_prompt_default = lambda x: "\001\033[4m\002rsf\001\033[0m\002 (\001\033[91m\002{}\001\033[0m\002) > ".format(x) self.module_prompt_default = (
lambda x: "\001\033[4m\002rsf\001\033[0m\002 "
"(\001\033[91m\002{}\001\033[0m\002) > ".format(x)
)
GLOBAL_OPTS.clear() GLOBAL_OPTS.clear()
def prepare_prompt_env_variables(self, raw_prompt=None, module_prompt=None): def prepare_prompt_env_variables(self, raw_prompt=None,
module_prompt=None):
if raw_prompt: if raw_prompt:
os.environ["RSF_RAW_PROMPT"] = raw_prompt os.environ["RSF_RAW_PROMPT"] = raw_prompt
else: else:
...@@ -43,7 +43,8 @@ class RoutersploitInterpreterTest(RoutersploitTestCase): ...@@ -43,7 +43,8 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
except KeyError: except KeyError:
pass pass
getattr(self.interpreter, '_{}__parse_prompt'.format(self.interpreter.__class__.__name__))() getattr(self.interpreter, '_{}__parse_prompt'.format(
self.interpreter.__class__.__name__))()
@mock.patch('routersploit.utils.print_success') @mock.patch('routersploit.utils.print_success')
def test_command_set(self, mock_print_success): def test_command_set(self, mock_print_success):
...@@ -59,7 +60,8 @@ class RoutersploitInterpreterTest(RoutersploitTestCase): ...@@ -59,7 +60,8 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
self.interpreter.command_set('rhost {}'.format(new_rhost_value)) self.interpreter.command_set('rhost {}'.format(new_rhost_value))
self.interpreter.command_set('port {}'.format(new_port_value)) self.interpreter.command_set('port {}'.format(new_port_value))
self.assertEqual(self.interpreter.current_module.rhost, new_rhost_value) self.assertEqual(self.interpreter.current_module.rhost,
new_rhost_value)
self.assertEqual(self.interpreter.current_module.port, new_port_value) self.assertEqual(self.interpreter.current_module.port, new_port_value)
with self.assertRaises(KeyError): with self.assertRaises(KeyError):
...@@ -68,7 +70,8 @@ class RoutersploitInterpreterTest(RoutersploitTestCase): ...@@ -68,7 +70,8 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
self.assertEqual( self.assertEqual(
mock_print_success.mock_calls, mock_print_success.mock_calls,
[mock.call({'rhost': new_rhost_value}), mock.call({'port': new_port_value})] [mock.call({'rhost': new_rhost_value}),
mock.call({'port': new_port_value})]
) )
@mock.patch('routersploit.utils.print_error') @mock.patch('routersploit.utils.print_error')
...@@ -78,11 +81,14 @@ class RoutersploitInterpreterTest(RoutersploitTestCase): ...@@ -78,11 +81,14 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
known_options = ['known_option_1', 'known_option_2'] known_options = ['known_option_1', 'known_option_2']
self.interpreter.current_module.options = known_options self.interpreter.current_module.options = known_options
self.interpreter.command_set('{} doesnt_matter_value'.format(unknown_option)) self.interpreter.command_set(
'{} doesnt_matter_value'.format(unknown_option))
self.assertEqual( self.assertEqual(
mock_print_error.mock_calls, mock_print_error.mock_calls,
[mock.call("You can't set option '{}'.\nAvailable options: {}".format(unknown_option, known_options))] [mock.call(
"You can't set option '{}'.\nAvailable options: {}".format(
unknown_option, known_options))]
) )
@mock.patch('routersploit.utils.print_success') @mock.patch('routersploit.utils.print_success')
...@@ -96,16 +102,20 @@ class RoutersploitInterpreterTest(RoutersploitTestCase): ...@@ -96,16 +102,20 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
self.assertEqual(self.interpreter.current_module.rhost, rhost) self.assertEqual(self.interpreter.current_module.rhost, rhost)
self.assertEqual(self.interpreter.current_module.port, port) self.assertEqual(self.interpreter.current_module.port, port)
self.interpreter.command_set('rhost {}'.format(new_rhost_value), glob=True) self.interpreter.command_set('rhost {}'.format(new_rhost_value),
self.interpreter.command_set('port {}'.format(new_port_value), glob=True) glob=True)
self.interpreter.command_set('port {}'.format(new_port_value),
glob=True)
self.assertEqual(self.interpreter.current_module.rhost, new_rhost_value) self.assertEqual(self.interpreter.current_module.rhost,
new_rhost_value)
self.assertEqual(self.interpreter.current_module.port, new_port_value) self.assertEqual(self.interpreter.current_module.port, new_port_value)
self.assertEqual(GLOBAL_OPTS['rhost'], new_rhost_value) self.assertEqual(GLOBAL_OPTS['rhost'], new_rhost_value)
self.assertEqual(GLOBAL_OPTS['port'], new_port_value) self.assertEqual(GLOBAL_OPTS['port'], new_port_value)
self.assertEqual( self.assertEqual(
mock_print_success.mock_calls, mock_print_success.mock_calls,
[mock.call({'rhost': new_rhost_value}), mock.call({'port': new_port_value})] [mock.call({'rhost': new_rhost_value}),
mock.call({'port': new_port_value})]
) )
@mock.patch('routersploit.utils.print_success') @mock.patch('routersploit.utils.print_success')
...@@ -116,10 +126,13 @@ class RoutersploitInterpreterTest(RoutersploitTestCase): ...@@ -116,10 +126,13 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
self.interpreter.command_setg('target {}'.format(new_target_value)) self.interpreter.command_setg('target {}'.format(new_target_value))
self.assertEqual(self.interpreter.current_module.target, new_target_value) self.assertEqual(self.interpreter.current_module.target,
new_target_value)
self.interpreter.current_module = TestExploitFoo() self.interpreter.current_module = TestExploitFoo()
# self.assertEqual(self.interpreter.current_module.target, new_target_value) self.assertEqual(self.interpreter.current_module.target,
mock_print_success.assert_called_once_with({'target': '{}'.format(new_target_value)}) new_target_value)
mock_print_success.assert_called_once_with(
{'target': '{}'.format(new_target_value)})
@mock.patch('routersploit.utils.print_success') @mock.patch('routersploit.utils.print_success')
def test_command_unsetg(self, mock_print_success): def test_command_unsetg(self, mock_print_success):
...@@ -133,20 +146,24 @@ class RoutersploitInterpreterTest(RoutersploitTestCase): ...@@ -133,20 +146,24 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
unknown_option = "unknown" unknown_option = "unknown"
GLOBAL_OPTS['foo'] = 'bar' GLOBAL_OPTS['foo'] = 'bar'
self.interpreter.command_unsetg('{} doesnt_matter_value'.format(unknown_option)) self.interpreter.command_unsetg(
mock_print_error.assert_called_once_with("You can't unset global option '{}'.\n" '{} doesnt_matter_value'.format(unknown_option))
"Available global options: ['foo']".format(unknown_option)) mock_print_error.assert_called_once_with(
"You can't unset global option '{}'.\n"
"Available global options: ['foo']".format(unknown_option))
@mock.patch('routersploit.utils.print_status') @mock.patch('routersploit.utils.print_status')
def test_command_run(self, mock_print_status): def test_command_run(self, mock_print_status):
with mock.patch.object(self.interpreter.current_module, 'run') as mock_run: with mock.patch.object(self.interpreter.current_module,
'run') as mock_run:
self.interpreter.command_run() self.interpreter.command_run()
mock_run.assert_called_once_with() mock_run.assert_called_once_with()
mock_print_status.assert_called_once_with('Running module...') mock_print_status.assert_called_once_with('Running module...')
@mock.patch('routersploit.utils.print_success') @mock.patch('routersploit.utils.print_success')
def test_command_check_target_vulnerable(self, mock_print_success): def test_command_check_target_vulnerable(self, mock_print_success):
with mock.patch.object(self.interpreter.current_module, 'check') as mock_check: with mock.patch.object(self.interpreter.current_module,
'check') as mock_check:
mock_check.return_value = True mock_check.return_value = True
self.interpreter.command_check() self.interpreter.command_check()
mock_check.assert_called_once_with() mock_check.assert_called_once_with()
...@@ -154,7 +171,8 @@ class RoutersploitInterpreterTest(RoutersploitTestCase): ...@@ -154,7 +171,8 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
@mock.patch('routersploit.utils.print_error') @mock.patch('routersploit.utils.print_error')
def test_command_check_target_not_vulnerable(self, print_error): def test_command_check_target_not_vulnerable(self, print_error):
with mock.patch.object(self.interpreter.current_module, 'check') as mock_check: with mock.patch.object(self.interpreter.current_module,
'check') as mock_check:
mock_check.return_value = False mock_check.return_value = False
self.interpreter.command_check() self.interpreter.command_check()
mock_check.assert_called_once_with() mock_check.assert_called_once_with()
...@@ -162,23 +180,28 @@ class RoutersploitInterpreterTest(RoutersploitTestCase): ...@@ -162,23 +180,28 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
@mock.patch('routersploit.utils.print_status') @mock.patch('routersploit.utils.print_status')
def test_command_check_target_could_not_be_verified_1(self, print_status): def test_command_check_target_could_not_be_verified_1(self, print_status):
with mock.patch.object(self.interpreter.current_module, 'check') as mock_check: with mock.patch.object(self.interpreter.current_module,
'check') as mock_check:
mock_check.return_value = "something" mock_check.return_value = "something"
self.interpreter.command_check() self.interpreter.command_check()
mock_check.assert_called_once_with() mock_check.assert_called_once_with()
print_status.assert_called_once_with('Target could not be verified') print_status.assert_called_once_with(
'Target could not be verified')
@mock.patch('routersploit.utils.print_status') @mock.patch('routersploit.utils.print_status')
def test_command_check_target_could_not_be_verified_2(self, print_status): def test_command_check_target_could_not_be_verified_2(self, print_status):
with mock.patch.object(self.interpreter.current_module, 'check') as mock_check: with mock.patch.object(self.interpreter.current_module,
'check') as mock_check:
mock_check.return_value = None mock_check.return_value = None
self.interpreter.command_check() self.interpreter.command_check()
mock_check.assert_called_once_with() mock_check.assert_called_once_with()
print_status.assert_called_once_with('Target could not be verified') print_status.assert_called_once_with(
'Target could not be verified')
@mock.patch('routersploit.utils.print_error') @mock.patch('routersploit.utils.print_error')
def test_command_check_not_supported_by_module(self, print_error): def test_command_check_not_supported_by_module(self, print_error):
with mock.patch.object(self.interpreter.current_module, 'check') as mock_check: with mock.patch.object(self.interpreter.current_module,
'check') as mock_check:
exception = NotImplementedError("Not available") exception = NotImplementedError("Not available")
mock_check.side_effect = exception mock_check.side_effect = exception
self.interpreter.command_check() self.interpreter.command_check()
...@@ -189,8 +212,13 @@ class RoutersploitInterpreterTest(RoutersploitTestCase): ...@@ -189,8 +212,13 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
@mock.patch('traceback.format_exc') @mock.patch('traceback.format_exc')
@mock.patch('routersploit.utils.print_error') @mock.patch('routersploit.utils.print_error')
@mock.patch('routersploit.utils.print_status') @mock.patch('routersploit.utils.print_status')
def test_command_run_exception_during_exploit_execution(self, mock_print_status, mock_print_error, mock_format_exc, mock_exc_info): def test_command_run_exception_during_exploit_execution(self,
with mock.patch.object(self.interpreter.current_module, 'run') as mock_run: mock_print_status,
mock_print_error,
mock_format_exc,
mock_exc_info):
with mock.patch.object(self.interpreter.current_module,
'run') as mock_run:
mock_run.side_effect = RuntimeError mock_run.side_effect = RuntimeError
mock_format_exc.return_value = stacktrace = "stacktrace" mock_format_exc.return_value = stacktrace = "stacktrace"
mock_exc_info.return_value = info = "info" mock_exc_info.return_value = info = "info"
...@@ -217,59 +245,75 @@ class RoutersploitInterpreterTest(RoutersploitTestCase): ...@@ -217,59 +245,75 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
self.assertEqual(self.raw_prompt_default, self.interpreter.prompt) self.assertEqual(self.raw_prompt_default, self.interpreter.prompt)
def test_default_raw_prompt_wrong_env_variable_format(self): def test_default_raw_prompt_wrong_env_variable_format(self):
self.prepare_prompt_env_variables(raw_prompt="wrong_format >") # no '{host}' substring self.prepare_prompt_env_variables(
raw_prompt="wrong_format >") # no '{host}' substring
self.interpreter.current_module = None self.interpreter.current_module = None
self.assertEqual(self.raw_prompt_default, self.interpreter.prompt) self.assertEqual(self.raw_prompt_default, self.interpreter.prompt)
def test_custom_module_prompt(self): def test_custom_module_prompt(self):
self.prepare_prompt_env_variables(module_prompt="*{host}*{module} >>>") self.prepare_prompt_env_variables(module_prompt="*{host}*{module} >>>")
module_name = "module_name" module_name = "module_name"
self.interpreter.current_module._MagicMock__info__ = {'name': module_name} self.interpreter.current_module._MagicMock__info__ = {
self.assertEqual("*rsf*{} >>>".format(module_name), self.interpreter.prompt) 'name': module_name}
self.assertEqual("*rsf*{} >>>".format(module_name),
self.interpreter.prompt)
def test_default_module_prompt_no_env_variable(self): def test_default_module_prompt_no_env_variable(self):
self.prepare_prompt_env_variables() self.prepare_prompt_env_variables()
name = "current_module_name" name = "current_module_name"
self.interpreter.current_module._MagicMock__info__ = {'name': name} self.interpreter.current_module._MagicMock__info__ = {'name': name}
self.assertEqual(self.module_prompt_default(name), self.interpreter.prompt) self.assertEqual(self.module_prompt_default(name),
self.interpreter.prompt)
def test_default_module_prompt_wrong_env_variable_format_1(self): def test_default_module_prompt_wrong_env_variable_format_1(self):
self.prepare_prompt_env_variables(raw_prompt="{module} >") # no '{host}' substring self.prepare_prompt_env_variables(
raw_prompt="{module} >") # no '{host}' substring
name = "current_module_name" name = "current_module_name"
self.interpreter.current_module._MagicMock__info__ = {'name': name} self.interpreter.current_module._MagicMock__info__ = {'name': name}
self.assertEqual(self.module_prompt_default(name), self.interpreter.prompt) self.assertEqual(self.module_prompt_default(name),
self.interpreter.prompt)
def test_default_module_prompt_wrong_env_variable_format_2(self): def test_default_module_prompt_wrong_env_variable_format_2(self):
self.prepare_prompt_env_variables(module_prompt="{host} >") # no '{module}' substring self.prepare_prompt_env_variables(
module_prompt="{host} >") # no '{module}' substring
name = "current_module_name" name = "current_module_name"
self.interpreter.current_module._MagicMock__info__ = {'name': name} self.interpreter.current_module._MagicMock__info__ = {'name': name}
self.assertEqual(self.module_prompt_default(name), self.interpreter.prompt) self.assertEqual(self.module_prompt_default(name),
self.interpreter.prompt)
def test_module_prompt_module_has_no_metadata(self): def test_module_prompt_module_has_no_metadata(self):
del self.interpreter.current_module._MagicMock__info__ del self.interpreter.current_module._MagicMock__info__
self.assertEqual(self.module_prompt_default('UnnamedModule'), self.interpreter.prompt) self.assertEqual(self.module_prompt_default('UnnamedModule'),
self.interpreter.prompt)
def test_module_prompt_module_has_no_name_key_in_metadata(self): def test_module_prompt_module_has_no_name_key_in_metadata(self):
self.interpreter.current_module._MagicMock__info__ = {} self.interpreter.current_module._MagicMock__info__ = {}
self.assertEqual(self.module_prompt_default('UnnamedModule'), self.interpreter.prompt) self.assertEqual(self.module_prompt_default('UnnamedModule'),
self.interpreter.prompt)
def test_suggested_commands_with_loaded_module_and_no_global_value_set(self): def test_suggested_commands_with_loaded_module_and_no_global_value_set(
self):
self.assertEqual( self.assertEqual(
list(self.interpreter.suggested_commands()), list(self.interpreter.suggested_commands()),
['back', 'check', 'exec ', 'exit', 'help', 'run', 'search ', 'set ', 'setg ', 'show ', 'use '] # Extra space at the end because of following param ['back', 'check', 'exec ', 'exit', 'help', 'run', 'search ',
'set ', 'setg ', 'show ', 'use ']
# Extra space at the end because of following param
) )
def test_suggested_commands_with_loaded_module_and_global_value_set(self): def test_suggested_commands_with_loaded_module_and_global_value_set(self):
GLOBAL_OPTS['key'] = 'value' GLOBAL_OPTS['key'] = 'value'
self.assertEqual( self.assertEqual(
list(self.interpreter.suggested_commands()), list(self.interpreter.suggested_commands()),
['back', 'check', 'exec ', 'exit', 'help', 'run', 'search ', 'set ', 'setg ', 'show ', 'unsetg ', 'use '] # Extra space at the end because of following param ['back', 'check', 'exec ', 'exit', 'help', 'run', 'search ',
'set ', 'setg ', 'show ', 'unsetg ', 'use ']
# Extra space at the end because of following param
) )
def test_suggested_commands_without_loaded_module(self): def test_suggested_commands_without_loaded_module(self):
self.interpreter.current_module = None self.interpreter.current_module = None
self.assertEqual( self.assertEqual(
self.interpreter.suggested_commands(), # Extra space at the end because of following param self.interpreter.suggested_commands(),
# Extra space at the end because of following param
['exec ', 'exit', 'help', 'search ', 'show ', 'use '] ['exec ', 'exit', 'help', 'search ', 'show ', 'use ']
) )
...@@ -284,12 +328,14 @@ class RoutersploitInterpreterTest(RoutersploitTestCase): ...@@ -284,12 +328,14 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
self.interpreter.current_module = None self.interpreter.current_module = None
self.interpreter.modules = [module_path, 'doo/pa/foo/bar'] self.interpreter.modules = [module_path, 'doo/pa/foo/bar']
exploit_class = mock.MagicMock(name="password_disclosure_module") exploit_class = mock.MagicMock(name="password_disclosure_module")
mocked_import_module.return_value = mocked_module = mock.MagicMock(name='module') mocked_import_module.return_value = mocked_module = mock.MagicMock(
name='module')
mocked_module.Exploit = exploit_class mocked_module.Exploit = exploit_class
self.interpreter.command_use(module_path) self.interpreter.command_use(module_path)
mocked_import_module.assert_called_once_with('routersploit.modules.exploits.foo.bar') mocked_import_module.assert_called_once_with(
'routersploit.modules.exploits.foo.bar')
self.assertEqual(self.interpreter.current_module, exploit_class()) self.assertEqual(self.interpreter.current_module, exploit_class())
@mock.patch('importlib.import_module') @mock.patch('importlib.import_module')
...@@ -303,17 +349,20 @@ class RoutersploitInterpreterTest(RoutersploitTestCase): ...@@ -303,17 +349,20 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
self.interpreter.current_module = None self.interpreter.current_module = None
self.interpreter.modules = [module_path, 'doo/pa/foo/bar'] self.interpreter.modules = [module_path, 'doo/pa/foo/bar']
exploit_class = mock.MagicMock(name="password_disclosure_module") exploit_class = mock.MagicMock(name="password_disclosure_module")
mocked_import_module.return_value = mocked_module = mock.MagicMock(name='module') mocked_import_module.return_value = mocked_module = mock.MagicMock(
name='module')
mocked_module.Exploit = exploit_class mocked_module.Exploit = exploit_class
self.interpreter.command_use(module_path) self.interpreter.command_use(module_path)
mocked_import_module.assert_called_once_with('routersploit.modules.creds.foo.bar.baz') mocked_import_module.assert_called_once_with(
'routersploit.modules.creds.foo.bar.baz')
self.assertEqual(self.interpreter.current_module, exploit_class()) self.assertEqual(self.interpreter.current_module, exploit_class())
@mock.patch('importlib.import_module') @mock.patch('importlib.import_module')
@mock.patch('routersploit.utils.print_error') @mock.patch('routersploit.utils.print_error')
def test_command_use_unknown_module(self, mocked_print_error, mocked_import_module): def test_command_use_unknown_module(self, mocked_print_error,
mocked_import_module):
""" Testing command_use() """ Testing command_use()
* Unknown module * Unknown module
...@@ -325,18 +374,21 @@ class RoutersploitInterpreterTest(RoutersploitTestCase): ...@@ -325,18 +374,21 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
self.interpreter.command_use(module_path) self.interpreter.command_use(module_path)
mocked_import_module.assert_called_once_with('routersploit.modules.creds.foo.bar.baz') mocked_import_module.assert_called_once_with(
'routersploit.modules.creds.foo.bar.baz')
mocked_print_error.assert_called_once_with( mocked_print_error.assert_called_once_with(
"Error during loading 'routersploit/modules/creds/foo/bar/baz'\n\n" "Error during loading 'routersploit/modules/creds/foo/bar/baz'\n\n"
"Error: Not working\n\n" "Error: Not working\n\n"
"It should be valid path to the module. Use <tab> key multiple times for completion." "It should be valid path to the module. "
"Use <tab> key multiple times for completion."
) )
self.assertEqual(self.interpreter.current_module, None) self.assertEqual(self.interpreter.current_module, None)
@mock.patch('importlib.import_module') @mock.patch('importlib.import_module')
@mock.patch('routersploit.utils.print_error') @mock.patch('routersploit.utils.print_error')
def test_command_use_unknown_extension(self, mocked_print_error, mocked_import_module): def test_command_use_unknown_extension(self, mocked_print_error,
mocked_import_module):
""" Testing command_use() """ Testing command_use()
* Unknown Exploit * Unknown Exploit
...@@ -345,16 +397,19 @@ class RoutersploitInterpreterTest(RoutersploitTestCase): ...@@ -345,16 +397,19 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
module_path = "exploits/foo/bar" module_path = "exploits/foo/bar"
self.interpreter.current_module = None self.interpreter.current_module = None
self.interpreter.modules = [module_path, 'doo/pa/foo/bar'] self.interpreter.modules = [module_path, 'doo/pa/foo/bar']
mocked_import_module.return_value = mocked_module = mock.MagicMock(name='module') mocked_import_module.return_value = mocked_module = mock.MagicMock(
name='module')
del mocked_module.Exploit del mocked_module.Exploit
self.interpreter.command_use(module_path) self.interpreter.command_use(module_path)
mocked_import_module.assert_called_once_with('routersploit.modules.exploits.foo.bar') mocked_import_module.assert_called_once_with(
'routersploit.modules.exploits.foo.bar')
mocked_print_error.assert_called_once_with( mocked_print_error.assert_called_once_with(
"Error during loading 'routersploit/modules/exploits/foo/bar'\n\n" "Error during loading 'routersploit/modules/exploits/foo/bar'\n\n"
"Error: Exploit\n\n" "Error: Exploit\n\n"
"It should be valid path to the module. Use <tab> key multiple times for completion." "It should be valid path to the module. "
"Use <tab> key multiple times for completion."
) )
self.assertEqual(self.interpreter.current_module, None) self.assertEqual(self.interpreter.current_module, None)
...@@ -412,8 +467,10 @@ class RoutersploitInterpreterTest(RoutersploitTestCase): ...@@ -412,8 +467,10 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
'bar': 'bar_desc', 'bar': 'bar_desc',
'baz': 'baz_desc' 'baz': 'baz_desc'
} }
self.interpreter.current_module.options = ['target', 'port', 'foo', 'bar', 'baz'] self.interpreter.current_module.options = ['target', 'port', 'foo',
self.interpreter.current_module.exploit_attributes.__getitem__.side_effect = lambda key: exploit_attributes[key] 'bar', 'baz']
self.interpreter.current_module.exploit_attributes\
.__getitem__.side_effect = lambda key: exploit_attributes[key]
self.interpreter.current_module.foo = 1 self.interpreter.current_module.foo = 1
self.interpreter.current_module.bar = 2 self.interpreter.current_module.bar = 2
...@@ -427,10 +484,14 @@ class RoutersploitInterpreterTest(RoutersploitTestCase): ...@@ -427,10 +484,14 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
[ [
mock.call('\nTarget options:'), mock.call('\nTarget options:'),
mock.call(), mock.call(),
mock.call(' Name Current settings Description '), mock.call(
mock.call(' ---- ---------------- ----------- '), ' Name Current settings Description '),
mock.call(' target 127.0.0.1 target_desc '), mock.call(
mock.call(' port 22 port_desc '), ' ---- ---------------- ----------- '),
mock.call(
' target 127.0.0.1 target_desc '),
mock.call(
' port 22 port_desc '),
mock.call(), mock.call(),
mock.call('\nModule options:'), mock.call('\nModule options:'),
mock.call(), mock.call(),
...@@ -445,13 +506,15 @@ class RoutersploitInterpreterTest(RoutersploitTestCase): ...@@ -445,13 +506,15 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
) )
@mock.patch('routersploit.utils.print_info') @mock.patch('routersploit.utils.print_info')
def test_command_show_options_when_there_is_no_module_opts(self, mock_print): def test_command_show_options_when_there_is_no_module_opts(self,
mock_print):
exploit_attributes = { exploit_attributes = {
'target': 'target_desc', 'target': 'target_desc',
'port': 'port_desc', 'port': 'port_desc',
} }
self.interpreter.current_module.options = ['target', 'port'] self.interpreter.current_module.options = ['target', 'port']
self.interpreter.current_module.exploit_attributes.__getitem__.side_effect = lambda key: exploit_attributes[key] self.interpreter.current_module.exploit_attributes\
.__getitem__.side_effect = lambda key: exploit_attributes[key]
self.interpreter.current_module.target = '127.0.0.1' self.interpreter.current_module.target = '127.0.0.1'
self.interpreter.current_module.port = 22 self.interpreter.current_module.port = 22
...@@ -462,26 +525,33 @@ class RoutersploitInterpreterTest(RoutersploitTestCase): ...@@ -462,26 +525,33 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
[ [
mock.call('\nTarget options:'), mock.call('\nTarget options:'),
mock.call(), mock.call(),
mock.call(' Name Current settings Description '), mock.call(
mock.call(' ---- ---------------- ----------- '), ' Name Current settings Description '),
mock.call(' target 127.0.0.1 target_desc '), mock.call(
mock.call(' port 22 port_desc '), ' ---- ---------------- ----------- '),
mock.call(
' target 127.0.0.1 target_desc '),
mock.call(
' port 22 port_desc '),
mock.call(), mock.call(),
mock.call(), mock.call(),
] ]
) )
def test_command_show(self): def test_command_show(self):
with mock.patch.object(self.interpreter, "_show_options") as mock_show_options: with mock.patch.object(self.interpreter,
"_show_options") as mock_show_options:
self.interpreter.command_show("options") self.interpreter.command_show("options")
mock_show_options.assert_called_once_with("options") mock_show_options.assert_called_once_with("options")
@mock.patch('routersploit.utils.print_error') @mock.patch('routersploit.utils.print_error')
def test_command_show_unknown_sub_command(self, mock_print_error): def test_command_show_unknown_sub_command(self, mock_print_error):
self.interpreter.command_show('unknown_sub_command') self.interpreter.command_show('unknown_sub_command')
mock_print_error.assert_called_once_with("Unknown 'show' sub-command 'unknown_sub_command'. " mock_print_error.assert_called_once_with(
"What do you want to show?\n" "Unknown 'show' sub-command 'unknown_sub_command'. "
"Possible choices are: {}".format(self.interpreter.show_sub_commands)) "What do you want to show?\n"
"Possible choices are: {}".format(
self.interpreter.show_sub_commands))
@mock.patch('routersploit.utils.print_info') @mock.patch('routersploit.utils.print_info')
def test_show_all(self, mock_print): def test_show_all(self, mock_print):
...@@ -672,7 +742,8 @@ class RoutersploitInterpreterTest(RoutersploitTestCase): ...@@ -672,7 +742,8 @@ class RoutersploitInterpreterTest(RoutersploitTestCase):
self.assertEqual( self.assertEqual(
print_error.mock_calls, print_error.mock_calls,
[ [
mock.call("Please specify search keyword. e.g. 'search cisco'"), mock.call(
"Please specify search keyword. e.g. 'search cisco'"),
] ]
) )
......
import unittest import unittest
from routersploit.utils import iter_modules from routersploit.utils import iter_modules
from routersploit.test import RoutersploitTestCase from tests.test_case import RoutersploitTestCase
class ModuleTest(RoutersploitTestCase): class ModuleTest(RoutersploitTestCase):
...@@ -17,7 +17,8 @@ class ModuleTest(RoutersploitTestCase): ...@@ -17,7 +17,8 @@ class ModuleTest(RoutersploitTestCase):
self.module = module self.module = module
def __str__(self): def __str__(self):
return " ".join([super(ModuleTest, self).__str__(), self.module.__module__]) return " ".join(
[super(ModuleTest, self).__str__(), self.module.__module__])
@property @property
def module_metadata(self): def module_metadata(self):
......
from __future__ import absolute_import
import unittest import unittest
try: import mock
import unittest.mock as mock
except ImportError:
import mock
from .. import utils from routersploit import utils
from . import RoutersploitTestCase from tests.test_case import RoutersploitTestCase
class UtilsTest(RoutersploitTestCase): class UtilsTest(RoutersploitTestCase):
@mock.patch('os.walk') @mock.patch('os.walk')
def test_load_modules_01(self, mock_walk): def test_load_modules_01(self, mock_walk):
mock_walk.return_value = ( mock_walk.return_value = (
('/Abs/Path/routersploit/routersploit/modules', ['asmax', 'creds'], ['__init__.py', '__init__.pyc']), ('/Abs/Path/routersploit/routersploit/modules', ['asmax', 'creds'],
('/Abs/Path/routersploit/routersploit/modules/creds', [], ['__init__.py', '__init__.pyc', 'ftp_bruteforce.py', 'ftp_bruteforce.pyc']), ['__init__.py', '__init__.pyc']),
('/Abs/Path/routersploit/routersploit/modules/exploits/asmax', [], ['__init__.py', '__init__.pyc', 'asmax_exploit.py', 'asmax_exploit.pyc']), ('/Abs/Path/routersploit/routersploit/modules/creds', [],
['__init__.py', '__init__.pyc', 'ftp_bruteforce.py',
'ftp_bruteforce.pyc']),
('/Abs/Path/routersploit/routersploit/modules/exploits/asmax', [],
['__init__.py', '__init__.pyc', 'asmax_exploit.py',
'asmax_exploit.pyc']),
) )
path = 'path/to/module' path = 'path/to/module'
...@@ -35,9 +35,14 @@ class UtilsTest(RoutersploitTestCase): ...@@ -35,9 +35,14 @@ class UtilsTest(RoutersploitTestCase):
@mock.patch('os.walk') @mock.patch('os.walk')
def test_load_modules_import_error_02(self, mock_walk): def test_load_modules_import_error_02(self, mock_walk):
mock_walk.return_value = ( mock_walk.return_value = (
('/Abs/Path/routersploit/routersploit/modules', ['asmax', 'creds'], ['__init__.py', '__init__.pyc']), ('/Abs/Path/routersploit/routersploit/modules', ['asmax', 'creds'],
('/Abs/Path/routersploit/routersploit/modules/creds', [], ['__init__.py', '__init__.pyc', 'ftp_bruteforce.py', 'ftp_bruteforce.pyc']), ['__init__.py', '__init__.pyc']),
('/Abs/Path/routersploit/routersploit/modules/exploits/asmax', [], ['__init__.py', '__init__.pyc', 'asmax_exploit.py', 'asmax_exploit.pyc', 'asmax_multi.py', 'asmax_multi.pyc']), ('/Abs/Path/routersploit/routersploit/modules/creds', [],
['__init__.py', '__init__.pyc', 'ftp_bruteforce.py',
'ftp_bruteforce.pyc']),
('/Abs/Path/routersploit/routersploit/modules/exploits/asmax', [],
['__init__.py', '__init__.pyc', 'asmax_exploit.py',
'asmax_exploit.pyc', 'asmax_multi.py', 'asmax_multi.pyc']),
) )
path = 'path/to/module' path = 'path/to/module'
......
import unittest import unittest
try: import mock
import unittest.mock as mock
except ImportError:
import mock
from routersploit.test import RoutersploitTestCase
from routersploit import validators from routersploit import validators
from routersploit.exceptions import OptionValidationError from routersploit.exceptions import OptionValidationError
from tests.test_case import RoutersploitTestCase
class ValidatorsTest(RoutersploitTestCase): class ValidatorsTest(RoutersploitTestCase):
...@@ -15,10 +12,12 @@ class ValidatorsTest(RoutersploitTestCase): ...@@ -15,10 +12,12 @@ class ValidatorsTest(RoutersploitTestCase):
self.assertEqual(validators.url("127.0.0.1"), "http://127.0.0.1") self.assertEqual(validators.url("127.0.0.1"), "http://127.0.0.1")
def test_url_already_with_http_prefix(self): def test_url_already_with_http_prefix(self):
self.assertEqual(validators.url("http://127.0.0.1"), "http://127.0.0.1") self.assertEqual(validators.url("http://127.0.0.1"),
"http://127.0.0.1")
def test_url_already_with_https_prefix(self): def test_url_already_with_https_prefix(self):
self.assertEqual(validators.url("https://127.0.0.1"), "https://127.0.0.1") self.assertEqual(validators.url("https://127.0.0.1"),
"https://127.0.0.1")
def test_ipv4_valid_address(self): def test_ipv4_valid_address(self):
address = "127.0.0.1" address = "127.0.0.1"
...@@ -139,7 +138,8 @@ class ValidatorsTest(RoutersploitTestCase): ...@@ -139,7 +138,8 @@ class ValidatorsTest(RoutersploitTestCase):
def test_choice_1(self): def test_choice_1(self):
valid_values = ["test1", "test2"] valid_values = ["test1", "test2"]
selected_value = "test1" selected_value = "test1"
self.assertEqual(validators.choice(valid_values)(selected_value), selected_value) self.assertEqual(validators.choice(valid_values)(selected_value),
selected_value)
def test_choice_2(self): def test_choice_2(self):
valid_values = ["test1", "test2"] valid_values = ["test1", "test2"]
......
[tox]
skipsdist = True
envlist = py27
[testenv]
deps =
mock
pexpect
-r{toxinidir}/requirements.txt
commands=python -m unittest discover
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment