Esempio n. 1
0
func (s *S) TestMap(c *gc.C) {
	s.sch = schema.Map(schema.String(), schema.Int())
	out, err := s.sch.Coerce(map[string]interface{}{"a": 1, "b": int8(2)}, aPath)
	c.Assert(err, gc.IsNil)
	c.Assert(out, gc.DeepEquals, map[interface{}]interface{}{"a": int64(1), "b": int64(2)})

	out, err = s.sch.Coerce(42, aPath)
	c.Assert(out, gc.IsNil)
	c.Assert(err, gc.ErrorMatches, "<path>: expected map, got int\\(42\\)")

	out, err = s.sch.Coerce(nil, aPath)
	c.Assert(out, gc.IsNil)
	c.Assert(err, gc.ErrorMatches, "<path>: expected map, got nothing")

	out, err = s.sch.Coerce(map[int]int{1: 1}, aPath)
	c.Assert(out, gc.IsNil)
	c.Assert(err, gc.ErrorMatches, "<path>: expected string, got int\\(1\\)")

	out, err = s.sch.Coerce(map[string]bool{"a": true}, aPath)
	c.Assert(out, gc.IsNil)
	c.Assert(err, gc.ErrorMatches, `<path>\.a: expected int, got bool\(true\)`)

	// First path entry shouldn't have dots in an error message.
	out, err = s.sch.Coerce(map[string]bool{"a": true}, nil)
	c.Assert(out, gc.IsNil)
	c.Assert(err, gc.ErrorMatches, `a: expected int, got bool\(true\)`)

	// Error should work even when path is nil.
	out, err = s.sch.Coerce(nil, nil)
	c.Assert(out, gc.IsNil)
	c.Assert(err, gc.ErrorMatches, `expected map, got nothing`)
}
Esempio n. 2
0
File: fields.go Progetto: cmars/oo
	v, err := c.checker.Coerce(v, path)
	if err != nil {
		return v, err
	}
	for _, allow := range c.vals {
		if allow == v {
			return v, nil
		}
	}
	return nil, fmt.Errorf("%sexpected one of %v, got %#v", pathPrefix(path), c.vals, v)
}

type attrsC struct{}

var (
	attrMapChecker   = schema.Map(schema.String(), schema.String())
	attrSliceChecker = schema.List(schema.String())
)

func (c attrsC) Coerce(v interface{}, path []string) (interface{}, error) {
	// TODO consider allowing only the map variant.
	switch reflect.TypeOf(v).Kind() {
	case reflect.String:
		s, err := schema.String().Coerce(v, path)
		if err != nil {
			return nil, errors.Mask(err)
		}
		result, err := keyvalues.Parse(strings.Fields(s.(string)), true)
		if err != nil {
			return nil, fmt.Errorf("%s%v", pathPrefix(path), err)
		}