Python warnings.simplefilter() Examples

The following are 30 code examples of warnings.simplefilter(). 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 also want to check out all available functions/classes of the module warnings , or try the search function .
Example #1
Source Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: test_gluon.py    License: Apache License 2.0 7 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
Source 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
Source Project: calmjs   Author: calmjs   File: test_testing.py    License: GNU General Public License v2.0 6 votes vote down vote up
def test_rmtree_test(self):
        path = mkdtemp(self)
        utils.rmtree(path)
        self.assertFalse(exists(path))
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            utils.rmtree(path)
            self.assertFalse(w)

        utils.stub_item_attr_value(
            self, utils, 'rmtree_', utils.fake_error(IOError))
        path2 = mkdtemp(self)

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            utils.rmtree(path2)
            self.assertIn("rmtree failed to remove", str(w[-1].message)) 
Example #4
Source Project: sanic   Author: huge-success   File: app.py    License: MIT License 6 votes vote down vote up
def register_blueprint(self, *args, **kwargs):
        """
        Proxy method provided for invoking the :func:`blueprint` method

        .. note::
            To be deprecated in 1.0. Use :func:`blueprint` instead.

        :param args: Blueprint object or (list, tuple) thereof
        :param kwargs: option dictionary with blueprint defaults
        :return: None
        """

        if self.debug:
            warnings.simplefilter("default")
        warnings.warn(
            "Use of register_blueprint will be deprecated in "
            "version 1.0.  Please use the blueprint method"
            " instead",
            DeprecationWarning,
        )
        return self.blueprint(*args, **kwargs) 
Example #5
Source 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
Source 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
Source Project: python-control   Author: python-control   File: iosys_test.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setUp(self):
        # Turn off numpy matrix warnings
        import warnings
        warnings.simplefilter('ignore', category=PendingDeprecationWarning)

        # Create a single input/single output linear system
        self.siso_linsys = ct.StateSpace(
            [[-1, 1], [0, -2]], [[0], [1]], [[1, 0]], [[0]])

        # Create a multi input/multi output linear system
        self.mimo_linsys1 = ct.StateSpace(
            [[-1, 1], [0, -2]], [[1, 0], [0, 1]],
            [[1, 0], [0, 1]], np.zeros((2,2)))

        # Create a multi input/multi output linear system
        self.mimo_linsys2 = ct.StateSpace(
            [[-1, 1], [0, -2]], [[0, 1], [1, 0]],
            [[1, 0], [0, 1]], np.zeros((2,2)))

        # Create simulation parameters
        self.T = np.linspace(0, 10, 100)
        self.U = np.sin(self.T)
        self.X0 = [0, 0] 
Example #8
Source 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 #9
Source Project: monero-python   Author: monero-ecosystem   File: test_wallet.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_filter_mempool_filter_address_and_payment_id(self):
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            # mempool excluded
            pmts = self.wallet.incoming(
                local_address='9tQoHWyZ4yXUgbz9nvMcFZUfDy5hxcdZabQCxmNCUukKYicXegsDL7nQpcUa3A1pF6K3fhq3scsyY88tdB1MqucULcKzWZC',
                payment_id='03f6649304ea4cb2')
            self.assertEqual(len(pmts), 0)
            # mempool included
            pmts = self.wallet.incoming(
                unconfirmed=True,
                local_address='9tQoHWyZ4yXUgbz9nvMcFZUfDy5hxcdZabQCxmNCUukKYicXegsDL7nQpcUa3A1pF6K3fhq3scsyY88tdB1MqucULcKzWZC',
                payment_id='03f6649304ea4cb2')
            self.assertEqual(len(pmts), 1)
            self.assertEqual(
                pmts[0].transaction.hash,
                'd29264ad317e8fdb55ea04484c00420430c35be7b3fe6dd663f99aebf41a786c')
            self.assertEqual(len(w), 0) 
Example #10
Source Project: monero-python   Author: monero-ecosystem   File: test_wallet.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_filter_mempool_filter_txid(self):
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            # mempool excluded
            pmts = self.wallet.incoming(
                tx_id='d29264ad317e8fdb55ea04484c00420430c35be7b3fe6dd663f99aebf41a786c')
            self.assertEqual(len(pmts), 0)
            # mempool included
            pmts = self.wallet.incoming(
                unconfirmed=True,
                tx_id='d29264ad317e8fdb55ea04484c00420430c35be7b3fe6dd663f99aebf41a786c')
            self.assertEqual(len(pmts), 1)
            self.assertEqual(
                pmts[0].transaction.hash,
                'd29264ad317e8fdb55ea04484c00420430c35be7b3fe6dd663f99aebf41a786c')
            self.assertEqual(len(w), 0) 
Example #11
Source Project: vergeml   Author: mme   File: __main__.py    License: MIT License 5 votes vote down vote up
def _configure_logging(level=logging.INFO):
    logging.addLevelName(logging.DEBUG, 'Debug:')
    logging.addLevelName(logging.INFO, 'Info:')
    logging.addLevelName(logging.WARNING, 'Warning!')
    logging.addLevelName(logging.CRITICAL, 'Critical!')
    logging.addLevelName(logging.ERROR, 'Error!')

    logging.basicConfig(format='%(levelname)s %(message)s', level=logging.INFO)

    if not sys.warnoptions:
        import warnings
        warnings.simplefilter("ignore")
        # TODO hack to get rid of deprecation warning that appeared allthough filters
        # are set to ignore. Is there a more sane way?
        warnings.warn = lambda *args, **kwargs: None 
Example #12
Source 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
Source 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
Source 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
Source 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
Source Project: mmdetection   Author: open-mmlab   File: inference.py    License: Apache License 2.0 5 votes vote down vote up
def init_detector(config, checkpoint=None, device='cuda:0'):
    """Initialize a detector from config file.

    Args:
        config (str or :obj:`mmcv.Config`): Config file path or the config
            object.
        checkpoint (str, optional): Checkpoint path. If left as None, the model
            will not load any weights.

    Returns:
        nn.Module: The constructed detector.
    """
    if isinstance(config, str):
        config = mmcv.Config.fromfile(config)
    elif not isinstance(config, mmcv.Config):
        raise TypeError('config must be a filename or Config object, '
                        f'but got {type(config)}')
    config.model.pretrained = None
    model = build_detector(config.model, test_cfg=config.test_cfg)
    if checkpoint is not None:
        checkpoint = load_checkpoint(model, checkpoint)
        if 'CLASSES' in checkpoint['meta']:
            model.CLASSES = checkpoint['meta']['CLASSES']
        else:
            warnings.simplefilter('once')
            warnings.warn('Class names are not saved in the checkpoint\'s '
                          'meta data, use COCO classes by default.')
            model.CLASSES = get_classes('coco')
    model.cfg = config  # save the config in the model for convenience
    model.to(device)
    model.eval()
    return model 
Example #17
Source 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 #18
Source 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 #19
Source 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 #20
Source 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 #21
Source 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 #22
Source 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)) 
Example #23
Source Project: calmjs   Author: calmjs   File: test_cli.py    License: GNU General Public License v2.0 5 votes vote down vote up
def test_create_for_module_vars_and_warning(self):
        stub_os_environ(self)
        tmpdir = mkdtemp(self)
        values = {}

        class MgrDriver(cli.PackageManagerDriver):
            def __init__(self, *a, **kw):
                kw['pkg_manager_bin'] = 'mgr'
                kw['working_dir'] = tmpdir
                super(MgrDriver, self).__init__(*a, **kw)

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            driver = MgrDriver.create_for_module_vars(values)
            self.assertTrue(issubclass(w[-1].category, RuntimeWarning))
            self.assertIn(
                "Unable to locate the 'mgr' binary or runtime",
                str(w[-1].message))

        self.assertTrue(isinstance(driver, MgrDriver))
        # Normally, these will be global names.
        self.assertIn('mgr_install', values)
        self.assertIn('mgr_init', values)
        self.assertIn('get_mgr_version', values)

    # Should really put more tests of these kind in here, but the more
    # concrete implementations have done so.  This weird version here
    # is mostly just for laughs. 
Example #24
Source Project: calmjs   Author: calmjs   File: test_toolchain.py    License: GNU General Public License v2.0 5 votes vote down vote up
def test_construction(self):
        with pretty_logging(stream=StringIO()) as s:
            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter('always')
                Spec(test_targets='/')

        self.assertIn(
            "Spec key 'test_targets' has been remapped to 'test_targetpaths' "
            "in calmjs-3.0.0;", str(w[-1].message)
        )
        self.assertIn(
            "Spec key 'test_targets' has been remapped to 'test_targetpaths' "
            "in calmjs-3.0.0;", s.getvalue()
        ) 
Example #25
Source Project: calmjs   Author: calmjs   File: test_toolchain.py    License: GNU General Public License v2.0 5 votes vote down vote up
def test_set(self):
        with pretty_logging(stream=StringIO()) as s:
            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter('always')
                spec = Spec()
                spec['test_source_map'] = '/'

        self.assertIn(
            "Spec key 'test_source_map' has been remapped to "
            "'test_sourcepath' in calmjs-3.0.0;", str(w[-1].message)
        )
        self.assertIn(
            "Spec key 'test_source_map' has been remapped to "
            "'test_sourcepath' in calmjs-3.0.0;", s.getvalue()
        ) 
Example #26
Source Project: calmjs   Author: calmjs   File: test_toolchain.py    License: GNU General Public License v2.0 5 votes vote down vote up
def test_getitem(self):
        spec = Spec(test_sourcepath='/')
        with pretty_logging(stream=StringIO()) as s:
            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter('always')
                self.assertEqual(spec['test_source_map'], '/')

        self.assertIn(
            "Spec key 'test_source_map' has been remapped to "
            "'test_sourcepath' in calmjs-3.0.0;", str(w[-1].message)
        )
        self.assertIn(
            "Spec key 'test_source_map' has been remapped to "
            "'test_sourcepath' in calmjs-3.0.0;", s.getvalue()
        ) 
Example #27
Source Project: calmjs   Author: calmjs   File: test_toolchain.py    License: GNU General Public License v2.0 5 votes vote down vote up
def test_generate_source_map(self):
        # this is an actual attribute
        with pretty_logging(stream=StringIO()) as s:
            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter('always')
                spec = Spec(generate_source_map=True)
                self.assertTrue(spec['generate_source_map'], '/')

        self.assertEqual(len(w), 0)
        self.assertEqual(s.getvalue(), '') 
Example #28
Source Project: calmjs   Author: calmjs   File: test_toolchain.py    License: GNU General Public License v2.0 5 votes vote down vote up
def test_toolchain_attributes(self):
        # should really be read/write, but in generate these are not
        # set so...
        with pretty_logging(stream=StringIO()) as s:
            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter('always')
                toolchain = NullToolchain()
                # assert existing via old property, then set using old
                # property, to see it reflected in new.
                self.assertEqual(toolchain.sourcemap_suffix, '_sourcepath')
                toolchain.sourcemap_suffix = 'foo'
                self.assertEqual(toolchain.sourcepath_suffix, 'foo')

                self.assertEqual(toolchain.target_suffix, '_targetpaths')
                toolchain.target_suffix = 'foo'
                self.assertEqual(toolchain.targetpath_suffix, 'foo')

        self.assertIn(
            "sourcemap_suffix has been renamed to sourcepath_suffix",
            str(w[0].message)
        )
        self.assertEqual(len(w), 4)
        self.assertIn(
            "sourcemap_suffix has been renamed to sourcepath_suffix",
            s.getvalue()
        )
        self.assertIn(
            "target_suffix has been renamed to targetpath_suffix",
            s.getvalue()
        ) 
Example #29
Source Project: calmjs   Author: calmjs   File: test_argparse.py    License: GNU General Public License v2.0 5 votes vote down vote up
def test_deprecation(self):
        import warnings
        argparser = ArgumentParser(prog='prog', add_help=False)
        argparser.add_argument('-n', '--normal', action='store')
        argparser.add_argument(
            '-d', '--deprecated', action='store', deprecation=True)
        argparser.add_argument(
            '--bye', action=StoreDelimitedListBase, deprecation='bye')

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            # test that they store stuff
            args = argparser.parse_args(['-n', 'hello'])
            self.assertEqual(args.normal, 'hello')
            args = argparser.parse_args(['-d', 'hello'])
            self.assertEqual(args.deprecated, 'hello')
            args = argparser.parse_args(['--deprecated', 'hello'])
            self.assertEqual(args.deprecated, 'hello')
            args = argparser.parse_args(['--bye', 'hello,goodbye'])
            self.assertEqual(args.bye, ['hello', 'goodbye'])

        # and the warnings are triggered
        self.assertEqual(
            "option '-d' is deprecated", str(w[0].message))
        self.assertEqual(
            "option '--deprecated' is deprecated", str(w[1].message))
        self.assertEqual(
            "option '--bye' is deprecated: bye", str(w[2].message))

        stream = StringIO()
        argparser.print_help(file=stream)
        # deprecated options are not visible on help
        self.assertNotIn("--deprecated", stream.getvalue())
        self.assertNotIn("--bye", stream.getvalue())
        self.assertIn("--normal", stream.getvalue()) 
Example #30
Source Project: calmjs   Author: calmjs   File: runtime.py    License: GNU General Public License v2.0 5 votes vote down vote up
def main(args=None, runtime_cls=CalmJSRuntime):
    bootstrap = BootstrapRuntime()
    # None to distinguish args from unspecified or specified as [], but
    # ultimately the value must be a list.
    args = norm_args(args)
    # Use the bootstrap runtime to set the global runtime attributes
    # (i.e. for logging and such).
    bootstrap(args)

    # all the minimum arguments acquired, bootstrap the execution.
    with warnings.catch_warnings(record=True) as records:
        # Note that this is a workaround for some versions of Python.
        # The full details as to why is documented in the
        # BaseRuntime.__call__ implementation.
        warnings.simplefilter('always')
        # log down the construction of the bootstrap class.
        with pretty_logging(
                logger='', level=bootstrap.bootstrap_log_level,
                stream=sys.stderr):
            runtime = runtime_cls()
            # access the argparser property to trigger its construction
            # inside this logger context, so that any messages passed to
            # the logger will be correctly handled.
            runtime.argparser

            # finally, ensure all captured records (thus far) are logged
            for record in records:
                logger.warning(record.message)
                logger.debug(
                    '%s triggered at %s:%s', record.category.__name__,
                    record.filename, record.lineno,
                )

        # Running this outside of the logger, as the BaseRuntime will do
        # its logging.
        if runtime(args):
            sys.exit(0)
        else:
            sys.exit(1)