Python warnings.catch_warnings() Examples

The following are 30 code examples for showing how to use warnings.catch_warnings(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module warnings , or try the search function .

Example 1
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: test_gluon.py    License: Apache License 2.0 6 votes vote down vote up
def test_global_norm_clip():
    stypes = ['default', 'row_sparse']
    def check_global_norm_clip(stype, check_isfinite):
        x1 = mx.nd.ones((3,3)).tostype(stype)
        x2 = mx.nd.ones((4,4)).tostype(stype)
        norm = gluon.utils.clip_global_norm([x1, x2], 1.0, check_isfinite=check_isfinite)
        assert norm == 5.0
        assert_almost_equal(x1.asnumpy(), np.ones((3,3))/5)
        assert_almost_equal(x2.asnumpy(), np.ones((4,4))/5)

        x3 = mx.nd.array([1.0, 2.0, float('nan')]).tostype(stype)
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            gluon.utils.clip_global_norm([x1, x3], 2.0, check_isfinite=check_isfinite)
            assert len(w) == check_isfinite

    for stype in stypes:
        for check_isfinite in [True, False]:
            check_global_norm_clip(stype, check_isfinite) 
Example 2
Project: TradzQAI   Author: kkuette   File: simple_moving_average.py    License: Apache License 2.0 6 votes vote down vote up
def simple_moving_average(data, period):
    """
    Simple Moving Average.

    Formula:
    SUM(data / N)
    """
    check_for_period_error(data, period)
    # Mean of Empty Slice RuntimeWarning doesn't affect output so it is
    # supressed
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", category=RuntimeWarning)
        sma = list(map(
            lambda idx:
            np.mean(data[idx-(period-1):idx+1]),
            range(0, len(data))
            ))
    sma = fill_for_noncomputable_vals(data, sma)
    return sma 
Example 3
Project: grimoirelab-sortinghat   Author: chaoss   File: test_cmd_init.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_connection_error(self):
        """Check connection errors"""

        kwargs = {
            'user': 'nouser',
            'password': 'nopassword',
            'database': None,
            'host': self.kwargs['host'],
            'port': self.kwargs['port']
        }

        cmd = Init(**kwargs)
        code = cmd.run(self.name)
        self.assertEqual(code, CODE_DATABASE_ERROR)

        with warnings.catch_warnings(record=True):
            output = sys.stderr.getvalue().strip()
            self.assertRegexpMatches(output,
                                     DB_ACCESS_ERROR % {'user': 'nouser'}) 
Example 4
Project: grimoirelab-sortinghat   Author: chaoss   File: test_cmd_init.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_connection_error(self):
        """Check connection errors"""

        kwargs = {
            'user': 'nouser',
            'password': 'nopassword',
            'database': None,
            'host': self.kwargs['host'],
            'port': self.kwargs['port'],
            'reuse': False
        }

        cmd = Init(**kwargs)
        code = cmd.initialize(self.name)
        self.assertEqual(code, CODE_DATABASE_ERROR)

        # Context added to catch deprecation warnings raised on Python 3
        with warnings.catch_warnings(record=True):
            output = sys.stderr.getvalue().strip()
            self.assertRegexpMatches(output,
                                     DB_ACCESS_ERROR % {'user': 'nouser'}) 
Example 5
Project: jawfish   Author: war-and-code   File: test_case.py    License: MIT License 6 votes vote down vote up
def testAssertWarnsCallable(self):
        def _runtime_warn():
            warnings.warn("foo", RuntimeWarning)
        # Success when the right warning is triggered, even several times
        self.assertWarns(RuntimeWarning, _runtime_warn)
        self.assertWarns(RuntimeWarning, _runtime_warn)
        # A tuple of warning classes is accepted
        self.assertWarns((DeprecationWarning, RuntimeWarning), _runtime_warn)
        # *args and **kwargs also work
        self.assertWarns(RuntimeWarning,
                         warnings.warn, "foo", category=RuntimeWarning)
        # Failure when no warning is triggered
        with self.assertRaises(self.failureException):
            self.assertWarns(RuntimeWarning, lambda: 0)
        # Failure when another warning is triggered
        with warnings.catch_warnings():
            # Force default filter (in case tests are run with -We)
            warnings.simplefilter("default", RuntimeWarning)
            with self.assertRaises(self.failureException):
                self.assertWarns(DeprecationWarning, _runtime_warn)
        # Filters for other warnings are not modified
        with warnings.catch_warnings():
            warnings.simplefilter("error", RuntimeWarning)
            with self.assertRaises(RuntimeWarning):
                self.assertWarns(DeprecationWarning, _runtime_warn) 
Example 6
Project: DidYouMean-Python   Author: SylvainDe   File: didyoumean_sugg_tests.py    License: MIT License 6 votes vote down vote up
def test_import_star(self):
        """'import *' in nested functions."""
        # NICE_TO_HAVE
        codes = [
            func_gen(
                'func1',
                body=func_gen('func2', body='from math import *\nTrue')),
            func_gen(
                'func1',
                body='from math import *\n' + func_gen('func2', body='True')),
        ]
        sys.setrecursionlimit(1000)  # needed for weird PyPy versions
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", category=SyntaxWarning)
            for code in codes:
                self.throws(code, IMPORTSTAR)
        sys.setrecursionlimit(initial_recursion_limit) 
Example 7
Project: chainerrl   Author: chainer   File: test_async.py    License: MIT License 6 votes vote down vote up
def test_run_async_exit_code(self):

        def run_with_exit_code_0(process_idx):
            sys.exit(0)

        def run_with_exit_code_11(process_idx):
            os.kill(os.getpid(), signal.SIGSEGV)

        with warnings.catch_warnings(record=True) as ws:
            async_.run_async(4, run_with_exit_code_0)
            # There should be no AbnormalExitWarning
            self.assertEqual(
                sum(1 if issubclass(
                    w.category, async_.AbnormalExitWarning) else 0
                    for w in ws), 0)

        with warnings.catch_warnings(record=True) as ws:
            async_.run_async(4, run_with_exit_code_11)
            # There should be 4 AbnormalExitWarning
            self.assertEqual(
                sum(1 if issubclass(
                    w.category, async_.AbnormalExitWarning) else 0
                    for w in ws), 4) 
Example 8
Project: python-control   Author: python-control   File: statefbk_array_test.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_gram_wc_deprecated(self):
        A = np.array([[1., -2.], [3., -4.]])
        B = np.array([[5., 6.], [7., 8.]])
        C = np.array([[4., 5.], [6., 7.]])
        D = np.array([[13., 14.], [15., 16.]])
        sys = ss(A, B, C, D)

        # Check that default type generates a warning
        # TODO: remove this check with matrix type is deprecated
        with warnings.catch_warnings(record=True) as w:
            use_numpy_matrix(True)
            self.assertTrue(issubclass(w[-1].category, UserWarning))
            
            Wc = gram(sys, 'c')
            self.assertTrue(isinstance(Wc, np.ndarray))
            use_numpy_matrix(False) 
Example 9
Project: python-control   Author: python-control   File: frd_test.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_evalfr_deprecated(self):
        sys_tf = ct.tf([1], [1, 2, 1])
        frd_tf = FRD(sys_tf, np.logspace(-1, 1, 3))

        # Deprecated version of the call (should generate warning)
        import warnings
        with warnings.catch_warnings():
            # Make warnings generate an exception
            warnings.simplefilter('error')

            # Make sure that we get a pending deprecation warning
            self.assertRaises(PendingDeprecationWarning, frd_tf.evalfr, 1.)

        # FRD.evalfr() is being deprecated
        import warnings
        with warnings.catch_warnings():
            # Make warnings generate an exception
            warnings.simplefilter('error')

            # Make sure that we get a pending deprecation warning
            self.assertRaises(PendingDeprecationWarning, frd_tf.evalfr, 1.) 
Example 10
Project: aospy   Author: spencerahill   File: test_tutorial.py    License: Apache License 2.0 5 votes vote down vote up
def test_tutorial_notebook():
    pytest.importorskip('nbformat')
    pytest.importorskip('nbconvert')
    pytest.importorskip('matplotlib')

    import nbformat
    from nbconvert.preprocessors import ExecutePreprocessor

    rootdir = os.path.join(aospy.__path__[0], 'examples')
    with open(os.path.join(rootdir, 'tutorial.ipynb')) as nb_file:
        notebook = nbformat.read(nb_file, as_version=nbformat.NO_CONVERT)
    kernel_name = 'python' + str(sys.version[0])
    ep = ExecutePreprocessor(kernel_name=kernel_name)
    with warnings.catch_warnings(record=True):
        ep.preprocess(notebook, {}) 
Example 11
Project: aospy   Author: spencerahill   File: test_data_loader.py    License: Apache License 2.0 5 votes vote down vote up
def test_load_variable_does_not_warn(load_variable_data_loader,
                                     start_date, end_date):
    with warnings.catch_warnings(record=True) as warnlog:
        load_variable_data_loader.load_variable(
            condensation_rain,
            start_date, end_date,
            intvl_in='monthly')
    assert len(warnlog) == 0 
Example 12
Project: RF-Monitor   Author: EarToEarOak   File: legend.py    License: GNU General Public License v2.0 5 votes vote down vote up
def create(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            self._legend = self._axes.legend(fontsize='small')
        if self._legend is not None:
            self._legend.get_frame().set_alpha(0.75)
            self._legend.set_visible(self._visible) 
Example 13
Project: MPContribs   Author: materialsproject   File: translate_vicalloy.py    License: MIT License 5 votes vote down vote up
def get_translate(workdir=None):

    filename = os.path.join(workdir, "Vicalloy/Fe-Co-V_140922a_META_DATA.csv")
    compdata_f = pd.read_csv(filename, sep="\t").dropna()
    print compdata_f.head()
    x = compdata_f["Xnom (mm)"].values
    y = compdata_f["Ynom (mm)"].values
    Co_concentration = compdata_f["Co (at%)"].values
    Fe_concentration = compdata_f["Fe (at%)"].values
    V_concentration = compdata_f["V (at%)"].values
    method = "linear"
    # method = 'nearest'

    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        Co_concI = interp2d(x, y, Co_concentration, kind=method)
        Fe_concI = interp2d(x, y, Fe_concentration, kind=method)
        V_concI = interp2d(x, y, V_concentration, kind=method)

    def translate(key):
        manip_z, manip_y = key
        sample_y = manip_z - 69.5
        sample_x = (manip_y + 8) * 2
        Co = Co_concI(sample_x, sample_y)[0] / 100.0
        Fe = Fe_concI(sample_x, sample_y)[0] / 100.0
        V = V_concI(sample_x, sample_y)[0] / 100.0
        return ("Fe{:.2f}Co{:.2f}V{:.2f}".format(Fe, Co, V), sample_x, sample_y)

    return translate 
Example 14
Project: oslo.i18n   Author: openstack   File: test_message.py    License: Apache License 2.0 5 votes vote down vote up
def test_translate_message_bad_translation(self,
                                               mock_log,
                                               mock_translation):
        message_with_params = 'A message: %s'
        es_translation = 'A message in Spanish: %s %s'
        param = 'A Message param'

        translations = {message_with_params: es_translation}
        translator = fakes.FakeTranslations.translator({'es': translations})
        mock_translation.side_effect = translator

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            msg = _message.Message(message_with_params)
            msg = msg % param
            default_translation = message_with_params % param

            self.assertEqual(default_translation, msg.translation('es'))

            self.assertEqual(1, len(w))
            # Note(gibi): in python 3.4 str.__repr__ does not put the unicode
            # marker 'u' in front of the string representations so the test
            # removes that to have the same result in python 2.7 and 3.4
            self.assertEqual("Failed to insert replacement values into "
                             "translated message A message in Spanish: %s %s "
                             "(Original: 'A message: %s'): "
                             "not enough arguments for format string",
                             str(w[0].message).replace("u'", "'"))

        mock_log.debug.assert_called_with(('Failed to insert replacement '
                                           'values into translated message '
                                           '%s (Original: %r): %s'),
                                          es_translation,
                                          message_with_params,
                                          mock.ANY) 
Example 15
Project: oslo.i18n   Author: openstack   File: test_message.py    License: Apache License 2.0 5 votes vote down vote up
def test_translate_message_bad_default_translation(self,
                                                       mock_log,
                                                       mock_local,
                                                       mock_translation):
        message_with_params = 'A message: %s'
        es_translation = 'A message in Spanish: %s %s'
        param = 'A Message param'

        translations = {message_with_params: es_translation}
        translator = fakes.FakeTranslations.translator({'es': translations})
        mock_translation.side_effect = translator

        msg = _message.Message(message_with_params)

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            msg = msg % param
            self.assertEqual(1, len(w))
            # Note(gibi): in python 3.4 str.__repr__ does not put the unicode
            # marker 'u' in front of the string representations so the test
            # removes that to have the same result in python 2.7 and 3.4
            self.assertEqual("Failed to insert replacement values into "
                             "translated message A message in Spanish: %s %s "
                             "(Original: 'A message: %s'): "
                             "not enough arguments for format string",
                             str(w[0].message).replace("u'", "'"))

        mock_log.debug.assert_called_with(('Failed to insert replacement '
                                           'values into translated message '
                                           '%s (Original: %r): %s'),
                                          es_translation,
                                          message_with_params,
                                          mock.ANY)
        mock_log.reset_mock()

        default_translation = message_with_params % param
        self.assertEqual(default_translation, msg)
        self.assertFalse(mock_log.warning.called) 
Example 16
Project: nmp_qc   Author: priba   File: Plotter.py    License: MIT License 5 votes vote down vote up
def plot_graph(self, am, position=None, cls=None, fig_name='graph.png'):

        with warnings.catch_warnings():
            warnings.filterwarnings("ignore")

            g = nx.from_numpy_matrix(am)

            if position is None:
                position=nx.drawing.circular_layout(g)

            fig = plt.figure()

            if cls is None:
                cls='r'
            else:
                # Make a user-defined colormap.
                cm1 = mcol.LinearSegmentedColormap.from_list("MyCmapName", ["r", "b"])

                # Make a normalizer that will map the time values from
                # [start_time,end_time+1] -> [0,1].
                cnorm = mcol.Normalize(vmin=0, vmax=1)

                # Turn these into an object that can be used to map time values to colors and
                # can be passed to plt.colorbar().
                cpick = cm.ScalarMappable(norm=cnorm, cmap=cm1)
                cpick.set_array([])
                cls = cpick.to_rgba(cls)
                plt.colorbar(cpick, ax=fig.add_subplot(111))


            nx.draw(g, pos=position, node_color=cls, ax=fig.add_subplot(111))

            fig.savefig(os.path.join(self.plotdir, fig_name)) 
Example 17
Project: neuropythy   Author: noahbenson   File: core.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def load_freesurfer_geometry(filename, to='mesh', warn=False):
    '''
    load_freesurfer_geometry(filename) yields the data stored at the freesurfer geometry file given
      by filename. The optional argument 'to' may be used to change the kind of data that is
      returned.

    The following are valid settings for the 'to' keyword argument:
      * 'mesh' (the default) yields a mesh object
      * 'tess' yields a tess object (discarding coordinates)
      * 'raw' yields a tuple of numpy arrays, identical to the read_geometry return value.
    '''
    if not warn:
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore',
                                    category=UserWarning,
                                    module='nibabel')
            (xs, fs, info) = fsio.read_geometry(filename, read_metadata=True)
    else:
        (xs, fs, info) = fsio.read_geometry(filename, read_metadata=True)
    # see if there's chirality data here...
    filename = os.path.split(filename)[1]
    filename = filename.lower()
    if   filename.startswith('lh'): info['chirality'] = 'lh.'
    elif filename.startswith('rh'): info['chirality'] = 'rh.'
    # parse it into something
    to = to.lower()
    if to in ['mesh', 'auto', 'automatic']:
        return geo.Mesh(fs, xs, meta_data=info)
    elif to in ['tess', 'tesselation']:
        return geo.Tesselation(fs, meta_data=info)
    elif to in ['coords', 'coordinates']:
        return xs
    elif to in ['triangles', 'faces']:
        return fs
    elif to in ['meta', 'meta_data']:
        return info
    elif to =='raw':
        return (xs, fs)
    else:
        raise ValueError('Could not understand \'to\' argument: %s' % to) 
Example 18
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: block.py    License: Apache License 2.0 5 votes vote down vote up
def _infer_attrs(self, infer_fn, attr, *args):
        """Generic infer attributes."""
        inputs, out = self._get_graph(*args)
        args, _ = _flatten(args, "input")
        with warnings.catch_warnings(record=True) as w:
            arg_attrs, _, aux_attrs = getattr(out, infer_fn)(
                **{i.name: getattr(j, attr) for i, j in zip(inputs, args)})
            if arg_attrs is None:
                raise ValueError(w[0].message)
        sdict = {i: j for i, j in zip(out.list_arguments(), arg_attrs)}
        sdict.update({name : attr for name, attr in \
             zip(out.list_auxiliary_states(), aux_attrs)})
        for i in self.collect_params().values():
            setattr(i, attr, sdict[i.name]) 
Example 19
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: test_viz.py    License: Apache License 2.0 5 votes vote down vote up
def test_plot_network():
    # Test warnings for cyclic graph
    net = mx.sym.Variable('data')
    net = mx.sym.FullyConnected(data=net, name='fc', num_hidden=128)
    net = mx.sym.Activation(data=net, name='relu1', act_type="relu")
    net = mx.sym.FullyConnected(data=net, name='fc', num_hidden=10)
    net = mx.sym.SoftmaxOutput(data=net, name='out')
    with warnings.catch_warnings(record=True) as w:
        digraph = mx.viz.plot_network(net, shape={'data': (100, 200)},
                                      node_attrs={"fixedsize": "false"})
    assert len(w) == 1
    assert "There are multiple variables with the same name in your graph" in str(w[-1].message)
    assert "fc" in str(w[-1].message) 
Example 20
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: test_gluon.py    License: Apache License 2.0 5 votes vote down vote up
def test_sequential_warning():
    with warnings.catch_warnings(record=True) as w:
        # The following line permits the test to pass if run multiple times
        warnings.simplefilter('always')
        b = gluon.nn.Sequential()
        b.add(gluon.nn.Dense(20))
        b.hybridize()
        assert len(w) == 1 
Example 21
Project: DOTA_models   Author: ringringyi   File: render_spec_with_graphviz.py    License: Apache License 2.0 5 votes vote down vote up
def master_spec_graph(master_spec):
  """Constructs a master spec graph.

  Args:
    master_spec: MasterSpec proto.

  Raises:
    TypeError, if master_spec is not the right type. N.B. that this may be
    raised if you import proto classes in non-standard ways (e.g. dynamically).

  Returns:
    SVG graph contents as a string.
  """
  if not isinstance(master_spec, spec_pb2.MasterSpec):
    raise TypeError("master_spec_graph() expects a MasterSpec input.")

  graph = pygraphviz.AGraph(directed=True)

  graph.node_attr.update(
      shape="box",
      style="filled",
      fillcolor="white",
      fontname="roboto, helvetica, arial",
      fontsize=11)
  graph.edge_attr.update(fontname="roboto, helvetica, arial", fontsize=11)

  for component in master_spec.component:
    graph.add_node(component.name, label=_component_contents(component))

  for component in master_spec.component:
    for linked_feature in component.linked_feature:
      graph.add_edge(
          linked_feature.source_component,
          component.name,
          label=_linked_feature_label(linked_feature))

  with warnings.catch_warnings():
    # Fontconfig spews some warnings, suppress them for now. (Especially because
    # they can clutter IPython notebooks).
    warnings.simplefilter("ignore")
    return graph.draw(format="svg", prog="dot") 
Example 22
Project: OpenFermion-Cirq   Author: quantumlib   File: _compat_test.py    License: Apache License 2.0 5 votes vote down vote up
def test_deprecated_test():

    @deprecated_test
    def test():
        f()

    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('ignore')
        warnings.simplefilter('default', DeprecationWarning)
        test()
        assert len(w) == 0 
Example 23
Project: TradzQAI   Author: kkuette   File: local.py    License: Apache License 2.0 5 votes vote down vote up
def setAgent(self, agent=None, device=None):
        if agent:
            self.env.model_name = agent
        if self.settings['agent']['type'].split('_')[0].upper() in self.src_agents():
            import warnings
            with warnings.catch_warnings():
                warnings.filterwarnings("ignore",category=FutureWarning)
                from TradzQAI.agents.agent import Agent
                self.agent = Agent
                self.device = device
        else:
            raise ValueError('could not import %s' % self.settings['agent']['type'].split('_')[0].upper()) 
Example 24
Project: TradzQAI   Author: kkuette   File: live.py    License: Apache License 2.0 5 votes vote down vote up
def setAgent(self, agent=None, device=None):
        if agent:
            self.env.model_name = agent
        if self.settings['agent']['type'].split('_')[0].upper() in self.src_agents():
            import warnings
            with warnings.catch_warnings():
                warnings.filterwarnings("ignore",category=FutureWarning)
                from TradzQAI.agents.agent import Agent
                self.agent = Agent
                self.device = device
        else:
            raise ValueError('could not import %s' % self.settings['agent']['type'].split('_')[0].upper()) 
Example 25
Project: grimoirelab-sortinghat   Author: chaoss   File: test_cmd_load.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_invalid_format(self):
        """Check whether it prints an error when parsing invalid files"""

        code = self.cmd.run(datadir('sortinghat_invalid.json'))
        self.assertEqual(code, CODE_INVALID_FORMAT_ERROR)
        output = sys.stderr.getvalue().strip('\n').split('\n')[0]
        self.assertEqual(output, LOAD_IDENTITIES_INVALID_JSON_FORMAT_ERROR)

        code = self.cmd.run(datadir('sortinghat_ids_missing_keys.json'))
        self.assertEqual(code, CODE_INVALID_FORMAT_ERROR)
        output = sys.stderr.getvalue().strip('\n').split('\n')[-1]
        self.assertEqual(output, LOAD_IDENTITIES_MISSING_KEYS_ERROR)

        # Context added to catch deprecation warnings raised on Python 3
        with warnings.catch_warnings(record=True):
            code = self.cmd.run(datadir('sortinghat_orgs_invalid_json.json'))
            self.assertEqual(code, CODE_INVALID_FORMAT_ERROR)
            output = sys.stderr.getvalue().strip('\n').split('\n')[-1]
            self.assertRegexpMatches(output, LOAD_ORGS_INVALID_FORMAT_ERROR)

        code = self.cmd.run(datadir('sortinghat_orgs_missing_keys.json'))
        self.assertEqual(code, CODE_INVALID_FORMAT_ERROR)
        output = sys.stderr.getvalue().strip('\n').split('\n')[-1]
        self.assertEqual(output, LOAD_ORGS_MISSING_KEYS_ERROR)

        code = self.cmd.run(datadir('sortinghat_orgs_invalid_top.json'))
        self.assertEqual(code, CODE_INVALID_FORMAT_ERROR)
        output = sys.stderr.getvalue().strip('\n').split('\n')[-1]
        self.assertEqual(output, LOAD_ORGS_IS_TOP_ERROR)

        code = self.cmd.run(datadir('sortinghat_blacklist_empty_strings.json'))
        self.assertEqual(code, CODE_INVALID_FORMAT_ERROR)
        output = sys.stderr.getvalue().strip('\n').split('\n')[-1]
        self.assertEqual(output, LOAD_BLACKLIST_EMPTY_STRINGS_ERROR) 
Example 26
Project: grimoirelab-sortinghat   Author: chaoss   File: test_cmd_init.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_existing_db_error(self):
        """Check if it returns an error when tries to create the registry twice"""

        code1 = self.cmd.run(self.name)
        self.assertEqual(code1, CMD_SUCCESS)

        code2 = self.cmd.run(self.name)
        self.assertEqual(code2, CODE_DATABASE_EXISTS)

        # Context added to catch deprecation warnings raised on Python 3
        with warnings.catch_warnings(record=True):
            output = sys.stderr.getvalue().strip()
            self.assertRegexpMatches(output,
                                     DB_EXISTS_ERROR % {'database': self.name}) 
Example 27
Project: grimoirelab-sortinghat   Author: chaoss   File: test_cmd_init.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_existing_db_error(self):
        """Check if it returns an error when tries to create the registry twice"""

        code1 = self.cmd.initialize(self.name)
        self.assertEqual(code1, CMD_SUCCESS)

        code2 = self.cmd.initialize(self.name)
        self.assertEqual(code2, CODE_DATABASE_EXISTS)

        # Context added to catch deprecation warnings raised on Python 3
        with warnings.catch_warnings(record=True):
            output = sys.stderr.getvalue().strip()
            self.assertRegexpMatches(output,
                                     DB_EXISTS_ERROR % {'database': self.name}) 
Example 28
Project: securityheaders   Author: koenbuyens   File: findingformatterfactory.py    License: Apache License 2.0 5 votes vote down vote up
def populate(self):
        #path = securityheaders.formatters.__path__[0]
        #with warnings.catch_warnings():
        #    warnings.simplefilter("ignore")
        #    Util.load_all_modules_from_dir(path)
        clazzes = list(Util.inheritors(FindingFormatter))
        all_my_base_classes = {cls: cls for cls in clazzes}
        for clazz in all_my_base_classes:
            self.clazzes[clazz.__name__] = clazz 
Example 29
Project: securityheaders   Author: koenbuyens   File: modelfactory.py    License: Apache License 2.0 5 votes vote down vote up
def populate(self):
#        path = securityheaders.models.__path__[0]
#        with warnings.catch_warnings():
#            warnings.simplefilter("ignore")
#            Util.load_all_modules_from_dir(path)
        clazzes = list(Util.inheritors(Header))
        clazzes.extend(Util.inheritors(Directive))
        clazzes.extend(Util.inheritors(Keyword))
        for header in list(Util.inheritors(Header)):
            if hasattr(header,'headerkey'):
                self.headers[header.headerkey] = header
    
        all_my_base_classes = {cls: cls for cls in clazzes}
        for clazz in all_my_base_classes:
            self.clazzes[clazz.__name__] = clazz 
Example 30
Project: calmjs   Author: calmjs   File: test_runtime.py    License: GNU General Public License v2.0 5 votes vote down vote up
def test_runtime_error_deprecation(self):
        stub_stdouts(self)
        working_set = mocks.WorkingSet({'calmjs.runtime': [
            'deprecated = calmjs.tests.test_runtime:deprecated',
        ]})
        rt = runtime.Runtime(working_set=working_set, prog='dummy')
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            with self.assertRaises(SystemExit):
                rt.error(rt.argparser, 'deprecated', 'simulated')
        self.assertIn('Runtime.error is deprecated', str(w[-1].message))