Python traitlets.TraitError() Examples

The following are 30 code examples of traitlets.TraitError(). 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 traitlets , or try the search function .
Example #1
Source File: test_color.py    From cesiumpy with Apache License 2.0 6 votes vote down vote up
def test_alpha(self):
        aqua = cesiumpy.color.AQUA

        res = aqua.set_alpha(0.3)
        exp = "Cesium.Color.AQUA.withAlpha(0.3)"
        self.assertEqual(res.script, exp)

        res = aqua.withAlpha(0.3)
        exp = "Cesium.Color.AQUA.withAlpha(0.3)"
        self.assertEqual(res.script, exp)

        res = aqua.withAlpha(1.0)
        exp = "Cesium.Color.AQUA.withAlpha(1.0)"
        self.assertEqual(res.script, exp)

        res = aqua.withAlpha(0.0)
        exp = "Cesium.Color.AQUA.withAlpha(0.0)"
        self.assertEqual(res.script, exp)

        msg = "The value of the 'alpha' trait of a ColorConstant instance should"
        with nose.tools.assert_raises_regexp(traitlets.TraitError, msg):
            aqua.withAlpha(1.1) 
Example #2
Source File: test_entity.py    From cesiumpy with Apache License 2.0 6 votes vote down vote up
def test_ellipsoid(self):
        e = cesiumpy.Ellipsoid(position=(-70, 40, 0), radii=(20, 30, 40), material=cesiumpy.color.GREEN)
        exp = "{position : Cesium.Cartesian3.fromDegrees(-70.0, 40.0, 0.0), ellipsoid : {radii : new Cesium.Cartesian3(20.0, 30.0, 40.0), material : Cesium.Color.GREEN}}"
        self.assertEqual(e.script, exp)

        e = e.copy()
        self.assertEqual(e.script, exp)

        e = cesiumpy.Ellipsoid(position=(-70, 40, 0), radii=(20, 30, 40), material=cesiumpy.color.RED, name='XXX')
        exp = '{name : "XXX", position : Cesium.Cartesian3.fromDegrees(-70.0, 40.0, 0.0), ellipsoid : {radii : new Cesium.Cartesian3(20.0, 30.0, 40.0), material : Cesium.Color.RED}}'
        self.assertEqual(e.script, exp)

        e = e.copy()
        self.assertEqual(e.script, exp)

        msg = "The 'radii' trait of an Ellipsoid instance must be a Cartesian3"
        with nose.tools.assert_raises_regexp(traitlets.TraitError, msg):
            cesiumpy.Ellipsoid(position=(-70, 40, 0), radii=(20, 30, 40, 10, 50)) 
Example #3
Source File: test_entity.py    From cesiumpy with Apache License 2.0 6 votes vote down vote up
def test_material_property(self):
        msg = "The 'material' trait of a Box instance must be a Material or None"
        with nose.tools.assert_raises_regexp(traitlets.TraitError, msg):
            cesiumpy.Box(position=[-120, 40, 0], dimensions=(10, 20, 30),
                         material=1)

        b = cesiumpy.Box(position=[-120, 40, 0], dimensions=(10, 20, 30),
                         material='red')
        exp = """{position : Cesium.Cartesian3.fromDegrees(-120.0, 40.0, 0.0), box : {dimensions : new Cesium.Cartesian3(10.0, 20.0, 30.0), material : Cesium.Color.RED}}"""
        self.assertEqual(b.script, exp)

        msg = "The 'material' trait of a Box instance must be a Material or None"
        with nose.tools.assert_raises_regexp(traitlets.TraitError, msg):
            b.material = 1

        b.material = 'blue'
        exp = """{position : Cesium.Cartesian3.fromDegrees(-120.0, 40.0, 0.0), box : {dimensions : new Cesium.Cartesian3(10.0, 20.0, 30.0), material : Cesium.Color.BLUE}}"""
        self.assertEqual(b.script, exp) 
Example #4
Source File: trait_types.py    From pySINDy with MIT License 6 votes vote down vote up
def validate(self, obj, value):
        value = super(NumberFormat, self).validate(obj, value)
        re_match = _number_format_re.match(value)
        if re_match is None:
            self.error(obj, value)
        else:
            format_type = re_match.group(9)
            if format_type is None:
                return value
            elif format_type in _number_format_types:
                return value
            else:
                raise traitlets.TraitError(
                    'The type specifier of a NumberFormat trait must '
                    'be one of {}, but a value of \'{}\' was '
                    'specified.'.format(
                        list(_number_format_types), format_type)
                ) 
Example #5
Source File: test_tool.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_tool_simple():
    """test the very basic functionality of a Tool"""

    class MyTool(Tool):
        description = "test"
        userparam = Float(5.0, help="parameter").tag(config=True)

    tool = MyTool()
    tool.userparam = 1.0
    tool.log_level = "DEBUG"
    tool.log.info("test")
    with pytest.raises(SystemExit) as exc:
        tool.run([])
    assert exc.value.code == 0

    # test parameters changes:
    tool.userparam = 4.0
    with pytest.raises(TraitError):
        tool.userparam = "badvalue" 
Example #6
Source File: test_entity.py    From cesiumpy with Apache License 2.0 6 votes vote down vote up
def test_color_property(self):
        msg = "The 'color' trait of a Point instance must be a Color or None"
        with nose.tools.assert_raises_regexp(traitlets.TraitError, msg):
            cesiumpy.Point(position=[-120, 40, 0], color=1)

        b = cesiumpy.Point(position=[-120, 40, 0], color='red')
        exp = """{position : Cesium.Cartesian3.fromDegrees(-120.0, 40.0, 0.0), point : {pixelSize : 10.0, color : Cesium.Color.RED}}"""
        self.assertEqual(b.script, exp)

        msg = "The 'color' trait of a Point instance must be a Color or None"
        with nose.tools.assert_raises_regexp(traitlets.TraitError, msg):
            b.color = 1

        b.color = 'blue'
        exp = """{position : Cesium.Cartesian3.fromDegrees(-120.0, 40.0, 0.0), point : {pixelSize : 10.0, color : Cesium.Color.BLUE}}"""
        self.assertEqual(b.script, exp) 
Example #7
Source File: test_entity.py    From cesiumpy with Apache License 2.0 6 votes vote down vote up
def test_outlineColor_property(self):
        msg = "The 'outlineColor' trait of a Box instance must be a Color or None"
        with nose.tools.assert_raises_regexp(traitlets.TraitError, msg):
            cesiumpy.Box(position=[-120, 40, 0], dimensions=(10, 20, 30),
                         outlineColor=1)

        b = cesiumpy.Box(position=[-120, 40, 0], dimensions=(10, 20, 30),
                         outlineColor='red')
        exp = """{position : Cesium.Cartesian3.fromDegrees(-120.0, 40.0, 0.0), box : {dimensions : new Cesium.Cartesian3(10.0, 20.0, 30.0), outlineColor : Cesium.Color.RED}}"""
        self.assertEqual(b.script, exp)

        msg = "The 'outlineColor' trait of a Box instance must be a Color or None"
        with nose.tools.assert_raises_regexp(traitlets.TraitError, msg):
            b.outlineColor = 1

        b.outlineColor = 'blue'
        exp = """{position : Cesium.Cartesian3.fromDegrees(-120.0, 40.0, 0.0), box : {dimensions : new Cesium.Cartesian3(10.0, 20.0, 30.0), outlineColor : Cesium.Color.BLUE}}"""
        self.assertEqual(b.script, exp) 
Example #8
Source File: traittypes.py    From traittypes with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def validate(self, obj, value):
        if value is None and not self.allow_none:
            self.error(obj, value)
        if value is None or value is Undefined:
            return super(Array, self).validate(obj, value)
        try:
            r = np.asarray(value, dtype=self.dtype)
            if isinstance(value, np.ndarray) and r is not value:
                warnings.warn(
                    'Given trait value dtype "%s" does not match required type "%s". '
                    'A coerced copy has been created.' % (
                        np.dtype(value.dtype).name,
                        np.dtype(self.dtype).name))
            value = r
        except (ValueError, TypeError) as e:
            raise TraitError(e)
        return super(Array, self).validate(obj, value) 
Example #9
Source File: test_numtraits.py    From numtraits with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_ndim_2d(self):
        with pytest.raises(TraitError) as exc:
            self.ap.g = np.ones((3, 6, 3))
        assert exc.value.args[0] == "g should be a 2-d array" 
Example #10
Source File: application.py    From paperboy with Apache License 2.0 5 votes vote down vote up
def _validate_backend(self, proposed):
        if proposed['value'] not in ('custom', 'dummy', 'git', 'sqla',):
            raise TraitError('backend not recognized: %s'.format(proposed['value']))
        return proposed['value'] 
Example #11
Source File: application.py    From paperboy with Apache License 2.0 5 votes vote down vote up
def _validate_auth(self, proposed):
        if proposed['value'] not in ('custom', 'none', 'sqla',):
            raise TraitError('backend not recognized: %s'.format(proposed['value']))
        return proposed['value']
    ##########################################

    ###########
    # Storage #
    ###########
    # FIXME doesnt allow default_value yet 
Example #12
Source File: forms.py    From paperboy with Apache License 2.0 5 votes vote down vote up
def _validate_type(self, proposal):
        if proposal['value'] not in _FORM_IMPLEMENTED:
            raise TraitError('Unrecognized type : {}'.format(proposal['value']))
        return proposal['value'] 
Example #13
Source File: test_numtraits.py    From numtraits with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_strictly_positive(self):
        self.ap.c = (1., 2., 3.)
        with pytest.raises(TraitError) as exc:
            self.ap.c = (0., 2., 3.)
        assert exc.value.args[0] == "All values of c should be strictly positive"
        with pytest.raises(TraitError) as exc:
            self.ap.c = (0., -1., 3.)
        assert exc.value.args[0] == "All values of c should be strictly positive" 
Example #14
Source File: test_numtraits.py    From numtraits with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_negative(self):
        self.ap.d = (-1., -2., 0.)
        with pytest.raises(TraitError) as exc:
            self.ap.d = (-1., -2., 1.)
        assert exc.value.args[0] == "All values of d should be negative" 
Example #15
Source File: test_numtraits.py    From numtraits with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_strictly_negative(self):
        self.ap.e = (-1., -2., -3.)
        with pytest.raises(TraitError) as exc:
            self.ap.e = (-1., -2., 0.)
        assert exc.value.args[0] == "All values of e should be strictly negative"
        with pytest.raises(TraitError) as exc:
            self.ap.e = (-1., -2., 1.)
        assert exc.value.args[0] == "All values of e should be strictly negative" 
Example #16
Source File: test_numtraits.py    From numtraits with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_range(self):
        self.ap.f = (3., 3.5, 4.)
        with pytest.raises(TraitError) as exc:
            self.ap.f = (0., 3.5, 4.)
        assert exc.value.args[0] == "All values of f should be in the range [3:4]"
        with pytest.raises(TraitError) as exc:
            self.ap.f = (0., 3.5, 7.)
        assert exc.value.args[0] == "All values of f should be in the range [3:4]" 
Example #17
Source File: test_numtraits.py    From numtraits with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_invalid_type(self):

            with pytest.raises(TraitError) as exc:
                self.aup.a = 5
            assert exc.value.args[0] == 'a should be given as an Astropy Quantity instance'

            with pytest.raises(TraitError) as exc:
                self.aup.b = np.ones((2, 5))
            assert exc.value.args[0] == 'b should be given as an Astropy Quantity instance' 
Example #18
Source File: forms.py    From paperboy with Apache License 2.0 5 votes vote down vote up
def _validate_type(self, proposal):
        if proposal['value'] not in _DOM_IMPLEMENTED:
            raise TraitError('Unrecognized type : {}'.format(proposal['value']))
        return proposal['value'] 
Example #19
Source File: test_selectioncontainer.py    From pySINDy with MIT License 5 votes vote down vote up
def test_selected_index_out_of_bounds(self):
        with self.assertRaises(TraitError):
            Accordion(self.children, selected_index=-1) 
Example #20
Source File: job.py    From paperboy with Apache License 2.0 5 votes vote down vote up
def _validate_interval(self, proposal):
        if proposal['value'] not in _INTERVAL_TYPES:
            raise TraitError('Unrecognized type : {}'.format(proposal['value']))
        return proposal['value'] 
Example #21
Source File: test_event_source.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_from_config_invalid_type():
    dataset = get_dataset_path("gamma_test_large.simtel.gz")
    EventSource.input_url.default_value = dataset
    config = Config({"EventSource": {"input_url": 124}})
    with pytest.raises(TraitError):
        EventSource.from_config(config=config, parent=None) 
Example #22
Source File: component.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, config=None, parent=None, **kwargs):
        """
        Parameters
        ----------
        config : traitlets.loader.Config
            Configuration specified by config file or cmdline arguments.
            Used to set traitlet values.
        parent: Tool or Component
            If a Component is created by another Component or Tool,
            you need to pass the creating Component as parent, e.g.
            `parent=self`. This makes sure the config is correctly
            handed down to the child components.
            Do not pass config in this case.
        kwargs
            Traitlets to be overridden.
            TraitError is raised if kwargs contains a key that does not
            correspond to a traitlet.
        """
        if parent is not None and config is not None:
            raise ValueError(
                "Only one of `config` or `parent` allowed"
                " If you create a Component as part of another, give `parent=self`"
                " and not `config`"
            )
        super().__init__(parent=parent, config=config, **kwargs)

        for key, value in kwargs.items():
            if not self.has_trait(key):
                raise TraitError(f"Traitlet does not exist: {key}")

        # set up logging (for some reason the logger registered by LoggingConfig
        # doesn't use a child logger of the parent by default)
        if self.parent:
            self.log = self.parent.log.getChild(self.__class__.__name__)
        else:
            self.log = getLogger(
                self.__class__.__module__ + "." + self.__class__.__name__
            ) 
Example #23
Source File: test_component.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_extra_missing():
    """ check that setting an incorrect trait raises an exception """
    with pytest.raises(TraitError):
        ExampleSubclass1(extra=229.0) 
Example #24
Source File: test_component.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_component_kwarg_setting():
    """ check that we can construct a component by setting traits via kwargs """
    comp = ExampleComponent(param=3)
    assert comp.param == 3

    # Invalid type
    with pytest.raises(TraitError):
        comp = ExampleComponent(param="badvalue")

    # Invalid traitlet
    with pytest.raises(TraitError):
        comp = ExampleComponent(incorrect="wrong") 
Example #25
Source File: test_component.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_component_simple():
    """
    very basic test to construct a component and check
    that it's traits work correctly
    """
    comp = ExampleComponent()

    assert comp.has_trait("param") is True
    comp.param = 1.2

    with pytest.raises(TraitError):
        comp.param = "badvalue" 
Example #26
Source File: utils.py    From binderhub with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def validate(self, obj, value):
        """
        Validate that the passed in value is a valid memory specification

        It could either be a pure int, when it is taken as a byte value.
        If it has one of the suffixes, it is converted into the appropriate
        pure byte value.
        """
        if isinstance(value, (int, float)):
            return int(value)

        try:
            num = float(value[:-1])
        except ValueError:
            raise TraitError(
                "{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T".format(
                    val=value
                )
            )
        suffix = value[-1]
        if suffix not in self.UNIT_SUFFIXES:
            raise TraitError(
                "{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T".format(
                    val=value
                )
            )
        else:
            return int(float(num) * self.UNIT_SUFFIXES[suffix]) 
Example #27
Source File: app.py    From binderhub with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def docker_build_host_validate(self, proposal):
        parts = urlparse(proposal.value)
        if parts.scheme != 'unix' or parts.netloc != '':
            raise TraitError("Only unix domain sockets on same node are supported for build_docker_host")
        return proposal.value 
Example #28
Source File: test_widget_box.py    From pySINDy with MIT License 5 votes vote down vote up
def test_construction_invalid_style(self):
        with self.assertRaises(TraitError):
            widgets.Box(box_style='invalid') 
Example #29
Source File: test_set_state.py    From pySINDy with MIT License 5 votes vote down vote up
def test_set_state_int_to_float():
    w = NumberWidget()

    # Set Int to float
    with nt.assert_raises(TraitError):
        w.set_state(dict(
            i = 3.5
        )) 
Example #30
Source File: test_interaction.py    From pySINDy with MIT License 5 votes vote down vote up
def test_int_range_logic():
    irsw = widgets.IntRangeSlider
    w = irsw(value=(2, 4), min=0, max=6)
    check_widget(w, cls=irsw, value=(2, 4), min=0, max=6)
    w.upper = 3
    w.max = 3
    check_widget(w, cls=irsw, value=(2, 3), min=0, max=3)

    w.min = 0
    w.max = 6
    w.lower = 2
    w.upper = 4
    check_widget(w, cls=irsw, value=(2, 4), min=0, max=6)
    w.value = (0, 1) #lower non-overlapping range
    check_widget(w, cls=irsw, value=(0, 1), min=0, max=6)
    w.value = (5, 6) #upper non-overlapping range
    check_widget(w, cls=irsw, value=(5, 6), min=0, max=6)
    w.lower = 2
    check_widget(w, cls=irsw, value=(2, 6), min=0, max=6)

    with nt.assert_raises(TraitError):
        w.min = 7
    with nt.assert_raises(TraitError):
        w.max = -1

    w = irsw(min=2, max=3, value=(2, 3))
    check_widget(w, min=2, max=3, value=(2, 3))
    w = irsw(min=100, max=200, value=(125, 175))
    check_widget(w, value=(125, 175))

    with nt.assert_raises(TraitError):
        irsw(min=2, max=1)