How to use the bandit.core.utils function in bandit

To help you get started, we’ve selected a few bandit examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github PyCQA / bandit / tests / unit / core / test_config.py View on Github external
def test_yaml_invalid(self):
        # When the config yaml file isn't valid, sys.exit(2) is called.

        # The following is invalid because it starts a sequence and doesn't
        # end it.
        invalid_yaml = '- [ something'
        f = self.useFixture(TempFile(invalid_yaml))
        self.assertRaisesRegex(
            utils.ConfigError, f.name, config.BanditConfig, f.name)
github PyCQA / bandit / tests / unit / core / test_util.py View on Github external
def test_get_module_qualname_from_path_abs_typical(self):
        '''Test get_module_qualname_from_path with typical absolute paths.'''

        name = b_utils.get_module_qualname_from_path(os.path.join(
            self.tempdir, 'good', 'a', 'b', 'c', 'test_typical.py'))
        self.assertEqual('good.a.b.c.test_typical', name)
github PyCQA / bandit / tests / unit / core / test_config.py View on Github external
def test_blacklist_error(self):
        msg = (" : Config file has an include or exclude reference to legacy "
               "test '%s' but no configuration data for it. Configuration "
               "data is required for this test. Please consider switching to "
               "the new config file format, the tool "
               "'bandit-config-generator' can help you with this.")

        for name in ["blacklist_call",
                     "blacklist_imports",
                     "blacklist_imports_func"]:

            self.config._config = (
                {"profiles": {"test": {"include": [name]}}})
            try:
                self.config.validate('')
            except utils.ConfigError as e:
                self.assertEqual(msg % name, e.message)
github PyCQA / bandit / tests / unit / cli / test_main.py View on Github external
def test_main_invalid_config(self):
        # Test that bandit exits when a config file contains invalid YAML
        # content
        with mock.patch('bandit.core.config.BanditConfig.__init__'
                        ) as mock_bandit_config:
            mock_bandit_config.side_effect = utils.ConfigError('', '')
            # assert a SystemExit with code 2
            self.assertRaisesRegex(SystemExit, '2', bandit.main)
github PyCQA / bandit / bandit / core / test_properties.py View on Github external
def wrapper(func):
        if not hasattr(func, "_checks"):
            func._checks = []
        func._checks.extend(utils.check_ast_node(a) for a in args)

        LOG.debug('checks() decorator executed')
        LOG.debug('  func._checks: %s', func._checks)
        return func
    return wrapper
github PyCQA / bandit / bandit / cli / main.py View on Github external
for t in target:
            for root, _, filenames in os.walk(t):
                for filename in fnmatch.filter(filenames, '.bandit'):
                    bandit_files.append(os.path.join(root, filename))

        if len(bandit_files) > 1:
            LOG.error('Multiple .bandit files found - scan separately or '
                      'choose one with --ini\n\t%s', ', '.join(bandit_files))
            sys.exit(2)

        elif len(bandit_files) == 1:
            ini_file = bandit_files[0]
            LOG.info('Found project level .bandit file: %s', bandit_files[0])

    if ini_file:
        return utils.parse_ini_file(ini_file)
    else:
        return None
github PyCQA / bandit / bandit / core / config.py View on Github external
def _test(key, block, exclude, include):
            if key in exclude or key in include:
                if self._config.get(block) is None:
                    raise utils.ConfigError(message.format(key), path)
github PyCQA / bandit / bandit / core / node_visitor.py View on Github external
def post_visit(self, node):
        self.depth -= 1
        LOG.debug("%s\texiting : %s", self.depth, hex(id(node)))

        # HACK(tkelsey): this is needed to clean up post-recursion stuff that
        # gets setup in the visit methods for these node types.
        if isinstance(node, (ast.FunctionDef, ast.ClassDef)):
            self.namespace = b_utils.namespace_path_split(self.namespace)[0]
github PyCQA / bandit / bandit / cli / main.py View on Github external
https://docs.python.org/3/library/string.html

    The following tests were discovered and loaded:
    -----------------------------------------------
    ''')
    parser.epilog = dedent_text + "\t{0}".format(plugin_list)

    # setup work - parse arguments, and initialize BanditManager
    args = parser.parse_args()
    # Check if `--msg-template` is not present without custom formatter
    if args.output_format != 'custom' and args.msg_template is not None:
        parser.error("--msg-template can only be used with --format=custom")

    try:
        b_conf = b_config.BanditConfig(config_file=args.config_file)
    except utils.ConfigError as e:
        LOG.error(e)
        sys.exit(2)

    # Handle .bandit files in projects to pass cmdline args from file
    ini_options = _get_options_from_ini(args.ini_path, args.targets)
    if ini_options:
        # prefer command line, then ini file
        args.excluded_paths = _log_option_source(
            args.excluded_paths,
            ini_options.get('exclude'),
            'excluded paths')

        args.skips = _log_option_source(
            args.skips,
            ini_options.get('skips'),
            'skipped tests')
github PyCQA / bandit / bandit / core / context.py View on Github external
def function_def_defaults_qual(self):
        '''Get a list of fully qualified default values in a function def

        :return: List of defaults
        '''
        defaults = []
        if ('node' in self._context and
                hasattr(self._context['node'], 'args') and
                hasattr(self._context['node'].args, 'defaults')):
            for default in self._context['node'].args.defaults:
                defaults.append(utils.get_qual_attr(
                    default,
                    self._context['import_aliases']))
        return defaults