pax_global_header 0000666 0000000 0000000 00000000064 14520671313 0014514 g ustar 00root root 0000000 0000000 52 comment=41e08deedca9242377d5c6c6a3a3581e36b748b3
schema-1.2.0/ 0000775 0000000 0000000 00000000000 14520671313 0012754 5 ustar 00root root 0000000 0000000 schema-1.2.0/.github/ 0000775 0000000 0000000 00000000000 14520671313 0014314 5 ustar 00root root 0000000 0000000 schema-1.2.0/.github/workflows/ 0000775 0000000 0000000 00000000000 14520671313 0016351 5 ustar 00root root 0000000 0000000 schema-1.2.0/.github/workflows/gotest.yaml 0000664 0000000 0000000 00000000551 14520671313 0020543 0 ustar 00root root 0000000 0000000 name: Go
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.17
- name: Build
run: go build -v ./...
- name: Test
run: go test -v ./...
schema-1.2.0/LICENSE 0000664 0000000 0000000 00000021501 14520671313 0013760 0 ustar 00root root 0000000 0000000 All files in this repository are licensed as follows. If you contribute
to this repository, it is assumed that you license your contribution
under the same license unless you state otherwise.
All files Copyright (C) 2015 Canonical Ltd. unless otherwise specified in the file.
This software is licensed under the LGPLv3, included below.
As a special exception to the GNU Lesser General Public License version 3
("LGPL3"), the copyright holders of this Library give you permission to
convey to a third party a Combined Work that links statically or dynamically
to this Library without providing any Minimal Corresponding Source or
Minimal Application Code as set out in 4d or providing the installation
information set out in section 4e, provided that you comply with the other
provisions of LGPL3 and provided that you meet, for the Application the
terms and conditions of the license(s) which apply to the Application.
Except as stated in this special exception, the provisions of LGPL3 will
continue to comply in full to this Library. If you modify this Library, you
may apply this exception to your version of this Library, but you are not
obliged to do so. If you do not wish to do so, delete this exception
statement from your version. This exception does not (and cannot) modify any
license terms which apply to the Application, with which you must still
comply.
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
schema-1.2.0/Makefile 0000664 0000000 0000000 00000000037 14520671313 0014414 0 ustar 00root root 0000000 0000000 default: check
check:
go test schema-1.2.0/README.md 0000664 0000000 0000000 00000000170 14520671313 0014231 0 ustar 00root root 0000000 0000000 juju/schema
===========
This package provides helpers for coercing dynamically typed data structures
into known forms.
schema-1.2.0/checker.go 0000664 0000000 0000000 00000003552 14520671313 0014714 0 ustar 00root root 0000000 0000000 // Copyright 2015 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package schema
import (
"strings"
)
// The Coerce method of the Checker interface is called recursively when
// v is being validated. If err is nil, newv is used as the new value
// at the recursion point. If err is non-nil, v is taken as invalid and
// may be either ignored or error out depending on where in the schema
// checking process the error happened. Checkers like OneOf may continue
// with an alternative, for instance.
type Checker interface {
Coerce(v interface{}, path []string) (newv interface{}, err error)
}
// Any returns a Checker that succeeds with any input value and
// results in the value itself unprocessed.
func Any() Checker {
return anyC{}
}
type anyC struct{}
func (c anyC) Coerce(v interface{}, path []string) (interface{}, error) {
return v, nil
}
// OneOf returns a Checker that attempts to Coerce the value with each
// of the provided checkers. The value returned by the first checker
// that succeeds will be returned by the OneOf checker itself. If no
// checker succeeds, OneOf will return an error on coercion.
func OneOf(options ...Checker) Checker {
return oneOfC{options}
}
type oneOfC struct {
options []Checker
}
func (c oneOfC) Coerce(v interface{}, path []string) (interface{}, error) {
for _, o := range c.options {
newv, err := o.Coerce(v, path)
if err == nil {
return newv, nil
}
}
return nil, error_{"", v, path}
}
// pathAsPrefix returns a string consisting of the path elements
// suitable for using as the prefix of an error message. If path
// starts with a ".", the dot is omitted.
func pathAsPrefix(path []string) string {
if len(path) == 0 {
return ""
}
var s string
if path[0] == "." {
s = strings.Join(path[1:], "")
} else {
s = strings.Join(path, "")
}
if s == "" {
return ""
}
return s + ": "
}
schema-1.2.0/const.go 0000664 0000000 0000000 00000002662 14520671313 0014437 0 ustar 00root root 0000000 0000000 // Copyright 2015 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package schema
import (
"fmt"
"reflect"
)
// Const returns a Checker that only succeeds if the input matches
// value exactly. The value is compared with reflect.DeepEqual.
func Const(value interface{}) Checker {
return constC{value}
}
type constC struct {
value interface{}
}
func (c constC) Coerce(v interface{}, path []string) (interface{}, error) {
if reflect.DeepEqual(v, c.value) {
return v, nil
}
return nil, error_{fmt.Sprintf("%#v", c.value), v, path}
}
// Nil returns a Checker that only succeeds if the input is nil. To tweak the
// error message, valueLabel can contain a label of the value being checked to
// be empty, e.g. "my special name". If valueLabel is "", "value" will be used
// as a label instead.
//
// Example 1:
// schema.Nil("widget").Coerce(42, nil) will return an error message
// like `expected empty widget, got int(42)`.
//
// Example 2:
// schema.Nil("").Coerce("", nil) will return an error message like
// `expected empty value, got string("")`.
func Nil(valueLabel string) Checker {
if valueLabel == "" {
valueLabel = "value"
}
return nilC{valueLabel}
}
type nilC struct {
valueLabel string
}
func (c nilC) Coerce(v interface{}, path []string) (interface{}, error) {
if reflect.DeepEqual(v, nil) {
return v, nil
}
label := fmt.Sprintf("empty %s", c.valueLabel)
return nil, error_{label, v, path}
}
schema-1.2.0/errors.go 0000664 0000000 0000000 00000001257 14520671313 0014624 0 ustar 00root root 0000000 0000000 // Copyright 2015 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package schema
import (
"fmt"
)
type error_ struct {
want string
got interface{}
path []string
}
func (e error_) Error() string {
path := pathAsPrefix(e.path)
if e.want == "" {
return fmt.Sprintf("%sunexpected value %#v", path, e.got)
}
if e.got == nil {
return fmt.Sprintf("%sexpected %s, got nothing", path, e.want)
}
return fmt.Sprintf("%sexpected %s, got %T(%#v)", path, e.want, e.got, e.got)
}
func parseError(path []string, expected string, err error) error {
prefix := pathAsPrefix(path)
return fmt.Errorf("%sconversion to %s: %s", prefix, expected, err.Error())
}
schema-1.2.0/fieldmap.go 0000664 0000000 0000000 00000010647 14520671313 0015074 0 ustar 00root root 0000000 0000000 // Copyright 2015 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package schema
import (
"fmt"
"reflect"
)
// Omit is a marker for FieldMap and StructFieldMap defaults parameter.
// If a field is not present in the map and defaults to Omit, the missing
// field will be ommitted from the coerced map as well.
var Omit omit
type omit struct{}
type Fields map[string]Checker
type Defaults map[string]interface{}
// FieldMap returns a Checker that accepts a map value with defined
// string keys. Every key has an independent checker associated,
// and processing will only succeed if all the values succeed
// individually. If a field fails to be processed, processing stops
// and returns with the underlying error.
//
// Fields in defaults will be set to the provided value if not present
// in the coerced map. If the default value is schema.Omit, the
// missing field will be omitted from the coerced map.
//
// The coerced output value has type map[string]interface{}.
func FieldMap(fields Fields, defaults Defaults) Checker {
return fieldMapC{fields, defaults, false}
}
// StrictFieldMap returns a Checker that acts as the one returned by FieldMap,
// but the Checker returns an error if it encounters an unknown key.
func StrictFieldMap(fields Fields, defaults Defaults) Checker {
return fieldMapC{fields, defaults, true}
}
type fieldMapC struct {
fields Fields
defaults Defaults
strict bool
}
var stringType = reflect.TypeOf("")
func hasStrictStringKeys(rv reflect.Value) bool {
if rv.Type().Key() == stringType {
return true
}
if rv.Type().Key().Kind() != reflect.Interface {
return false
}
for _, k := range rv.MapKeys() {
if k.Elem().Type() != stringType {
return false
}
}
return true
}
func (c fieldMapC) Coerce(v interface{}, path []string) (interface{}, error) {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Map {
return nil, error_{"map", v, path}
}
if !hasStrictStringKeys(rv) {
return nil, error_{"map[string]", v, path}
}
if c.strict {
for _, k := range rv.MapKeys() {
ks := k.String()
if _, ok := c.fields[ks]; !ok {
return nil, fmt.Errorf("%sunknown key %q (value %#v)", pathAsPrefix(path), ks, rv.MapIndex(k).Interface())
}
}
}
vpath := append(path, ".", "?")
out := make(map[string]interface{}, rv.Len())
for k, checker := range c.fields {
valuev := rv.MapIndex(reflect.ValueOf(k))
var value interface{}
if valuev.IsValid() {
value = valuev.Interface()
} else if dflt, ok := c.defaults[k]; ok {
if dflt == Omit {
continue
}
value = dflt
}
vpath[len(vpath)-1] = k
newv, err := checker.Coerce(value, vpath)
if err != nil {
return nil, err
}
out[k] = newv
}
for k, v := range c.defaults {
if v == Omit {
continue
}
if _, ok := out[k]; !ok {
checker, ok := c.fields[k]
if !ok {
return nil, fmt.Errorf("got default value for unknown field %q", k)
}
vpath[len(vpath)-1] = k
newv, err := checker.Coerce(v, vpath)
if err != nil {
return nil, err
}
out[k] = newv
}
}
return out, nil
}
// FieldMapSet returns a Checker that accepts a map value checked
// against one of several FieldMap checkers. The actual checker
// used is the first one whose checker associated with the selector
// field processes the map correctly. If no checker processes
// the selector value correctly, an error is returned.
//
// The coerced output value has type map[string]interface{}.
func FieldMapSet(selector string, maps []Checker) Checker {
fmaps := make([]fieldMapC, len(maps))
for i, m := range maps {
if fmap, ok := m.(fieldMapC); ok {
if checker, _ := fmap.fields[selector]; checker == nil {
panic("FieldMapSet has a FieldMap with a missing selector")
}
fmaps[i] = fmap
} else {
panic("FieldMapSet got a non-FieldMap checker")
}
}
return mapSetC{selector, fmaps}
}
type mapSetC struct {
selector string
fmaps []fieldMapC
}
func (c mapSetC) Coerce(v interface{}, path []string) (interface{}, error) {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Map {
return nil, error_{"map", v, path}
}
var selector interface{}
selectorv := rv.MapIndex(reflect.ValueOf(c.selector))
if selectorv.IsValid() {
selector = selectorv.Interface()
for _, fmap := range c.fmaps {
_, err := fmap.fields[c.selector].Coerce(selector, path)
if err != nil {
continue
}
return fmap.Coerce(v, path)
}
}
return nil, error_{"supported selector", selector, append(path, ".", c.selector)}
}
schema-1.2.0/go.mod 0000664 0000000 0000000 00000000302 14520671313 0014055 0 ustar 00root root 0000000 0000000 module github.com/juju/schema
go 1.20
require gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127
require (
github.com/kr/pretty v0.1.0 // indirect
github.com/kr/text v0.1.0 // indirect
)
schema-1.2.0/go.sum 0000664 0000000 0000000 00000001133 14520671313 0014105 0 ustar 00root root 0000000 0000000 github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
schema-1.2.0/lists.go 0000664 0000000 0000000 00000001761 14520671313 0014446 0 ustar 00root root 0000000 0000000 // Copyright 2015 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package schema
import (
"reflect"
"strconv"
)
// List returns a Checker that accepts a slice value with values
// that are processed with the elem checker. If any element of the
// provided slice value fails to be processed, processing will stop
// and return with the obtained error.
//
// The coerced output value has type []interface{}.
func List(elem Checker) Checker {
return listC{elem}
}
type listC struct {
elem Checker
}
func (c listC) Coerce(v interface{}, path []string) (interface{}, error) {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Slice {
return nil, error_{"list", v, path}
}
path = append(path, "[", "?", "]")
l := rv.Len()
out := make([]interface{}, 0, l)
for i := 0; i != l; i++ {
path[len(path)-2] = strconv.Itoa(i)
elem, err := c.elem.Coerce(rv.Index(i).Interface(), path)
if err != nil {
return nil, err
}
out = append(out, elem)
}
return out, nil
}
schema-1.2.0/maps.go 0000664 0000000 0000000 00000004327 14520671313 0014251 0 ustar 00root root 0000000 0000000 // Copyright 2015 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package schema
import (
"fmt"
"reflect"
)
// Map returns a Checker that accepts a map value. Every key and value
// in the map are processed with the respective checker, and if any
// value fails to be coerced, processing stops and returns with the
// underlying error.
//
// The coerced output value has type map[interface{}]interface{}.
func Map(key Checker, value Checker) Checker {
return mapC{key, value}
}
type mapC struct {
key Checker
value Checker
}
func (c mapC) Coerce(v interface{}, path []string) (interface{}, error) {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Map {
return nil, error_{"map", v, path}
}
vpath := append(path, ".", "?")
l := rv.Len()
out := make(map[interface{}]interface{}, l)
keys := rv.MapKeys()
for i := 0; i != l; i++ {
k := keys[i]
newk, err := c.key.Coerce(k.Interface(), path)
if err != nil {
return nil, err
}
vpath[len(vpath)-1] = fmt.Sprint(k.Interface())
newv, err := c.value.Coerce(rv.MapIndex(k).Interface(), vpath)
if err != nil {
return nil, err
}
out[newk] = newv
}
return out, nil
}
// StringMap returns a Checker that accepts a map value. Every key in
// the map must be a string, and every value in the map are processed
// with the provided checker. If any value fails to be coerced,
// processing stops and returns with the underlying error.
//
// The coerced output value has type map[string]interface{}.
func StringMap(value Checker) Checker {
return stringMapC{value}
}
type stringMapC struct {
value Checker
}
func (c stringMapC) Coerce(v interface{}, path []string) (interface{}, error) {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Map {
return nil, error_{"map", v, path}
}
vpath := append(path, ".", "?")
key := String()
l := rv.Len()
out := make(map[string]interface{}, l)
keys := rv.MapKeys()
for i := 0; i != l; i++ {
k := keys[i]
newk, err := key.Coerce(k.Interface(), path)
if err != nil {
return nil, err
}
vpath[len(vpath)-1] = fmt.Sprint(k.Interface())
newv, err := c.value.Coerce(rv.MapIndex(k).Interface(), vpath)
if err != nil {
return nil, err
}
out[newk.(string)] = newv
}
return out, nil
}
schema-1.2.0/numeric.go 0000664 0000000 0000000 00000012741 14520671313 0014752 0 ustar 00root root 0000000 0000000 // Copyright 2015 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package schema
import (
"reflect"
"strconv"
)
// Bool returns a Checker that accepts boolean values only.
func Bool() Checker {
return boolC{}
}
type boolC struct{}
func (c boolC) Coerce(v interface{}, path []string) (interface{}, error) {
if v != nil {
switch reflect.TypeOf(v).Kind() {
case reflect.Bool:
return v, nil
case reflect.String:
val, err := strconv.ParseBool(reflect.ValueOf(v).String())
if err == nil {
return val, nil
}
}
}
return nil, error_{"bool", v, path}
}
// Int returns a Checker that accepts any integer value, and returns
// the same value consistently typed as an int64.
func Int() Checker {
return intC{}
}
type intC struct{}
func (c intC) Coerce(v interface{}, path []string) (interface{}, error) {
if v == nil {
return nil, error_{"int", v, path}
}
switch reflect.TypeOf(v).Kind() {
case reflect.Int:
case reflect.Int8:
case reflect.Int16:
case reflect.Int32:
case reflect.Int64:
case reflect.String:
val, err := strconv.ParseInt(reflect.ValueOf(v).String(), 0, 64)
if err == nil {
return val, nil
} else {
return nil, error_{"int", v, path}
}
default:
return nil, error_{"int", v, path}
}
return reflect.ValueOf(v).Int(), nil
}
// Uint returns a Checker that accepts any integer or unsigned value, and
// returns the same value consistently typed as an uint64. If the integer
// value is negative an error is raised.
func Uint() Checker {
return uintC{}
}
type uintC struct{}
func (c uintC) Coerce(v interface{}, path []string) (interface{}, error) {
if v == nil {
return nil, error_{"uint", v, path}
}
switch reflect.TypeOf(v).Kind() {
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return reflect.ValueOf(v).Uint(), nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
val := reflect.ValueOf(v).Int()
if val < 0 {
return nil, error_{"uint", v, path}
}
// All positive int64 values fit into uint64.
return uint64(val), nil
case reflect.String:
val, err := strconv.ParseUint(reflect.ValueOf(v).String(), 0, 64)
if err == nil {
return val, nil
} else {
return nil, error_{"uint", v, path}
}
default:
return nil, error_{"uint", v, path}
}
}
// ForceInt returns a Checker that accepts any integer or float value, and
// returns the same value consistently typed as an int. This is required
// in order to handle the interface{}/float64 type conversion performed by
// the JSON serializer used as part of the API infrastructure.
func ForceInt() Checker {
return forceIntC{}
}
type forceIntC struct{}
func (c forceIntC) Coerce(v interface{}, path []string) (interface{}, error) {
if v != nil {
switch vv := reflect.TypeOf(v); vv.Kind() {
case reflect.String:
vstr := reflect.ValueOf(v).String()
intValue, err := strconv.ParseInt(vstr, 0, 64)
if err == nil {
return int(intValue), nil
}
floatValue, err := strconv.ParseFloat(vstr, 64)
if err == nil {
return int(floatValue), nil
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return int(reflect.ValueOf(v).Int()), nil
case reflect.Float32, reflect.Float64:
return int(reflect.ValueOf(v).Float()), nil
}
}
return nil, error_{"number", v, path}
}
// ForceUint returns a Checker that accepts any integer or float value, and
// returns the same value consistently typed as an uint64. This is required
// in order to handle the interface{}/float64 type conversion performed by
// the JSON serializer used as part of the API infrastructure. If the integer
// value is negative an error is raised.
func ForceUint() Checker {
return forceUintC{}
}
type forceUintC struct{}
func (c forceUintC) Coerce(v interface{}, path []string) (interface{}, error) {
if v != nil {
switch vv := reflect.TypeOf(v); vv.Kind() {
case reflect.String:
vstr := reflect.ValueOf(v).String()
intValue, err := strconv.ParseUint(vstr, 0, 64)
if err == nil {
return intValue, nil
}
floatValue, err := strconv.ParseFloat(vstr, 64)
if err == nil {
if floatValue < 0 {
return nil, error_{"uint", v, path}
}
return uint64(floatValue), nil
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return reflect.ValueOf(v).Uint(), nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
val := reflect.ValueOf(v).Int()
if val < 0 {
return nil, error_{"uint", v, path}
}
// All positive int64 values fit into uint64.
return uint64(val), nil
case reflect.Float32, reflect.Float64:
val := reflect.ValueOf(v).Float()
if val < 0 {
return nil, error_{"uint", v, path}
}
return uint64(val), nil
}
}
return nil, error_{"uint", v, path}
}
// Float returns a Checker that accepts any float value, and returns
// the same value consistently typed as a float64.
func Float() Checker {
return floatC{}
}
type floatC struct{}
func (c floatC) Coerce(v interface{}, path []string) (interface{}, error) {
if v == nil {
return nil, error_{"float", v, path}
}
switch reflect.TypeOf(v).Kind() {
case reflect.Float32, reflect.Float64:
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
default:
return nil, error_{"float", v, path}
}
var floatValue float64
return reflect.ValueOf(v).Convert( reflect.TypeOf(floatValue) ).Float() , nil
}
schema-1.2.0/package_test.go 0000664 0000000 0000000 00000000317 14520671313 0015736 0 ustar 00root root 0000000 0000000 // Copyright 2015 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package schema_test
import (
"testing"
gc "gopkg.in/check.v1"
)
func Test(t *testing.T) {
gc.TestingT(t)
}
schema-1.2.0/schema_test.go 0000664 0000000 0000000 00000055411 14520671313 0015610 0 ustar 00root root 0000000 0000000 // Copyright 2011, 2012, 2013 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package schema_test
import (
"fmt"
"math"
"net/url"
"time"
gc "gopkg.in/check.v1"
"github.com/juju/schema"
)
var aPath = []string{""}
type Dummy struct{}
func (d *Dummy) Coerce(value interface{}, path []string) (coerced interface{}, err error) {
return "i-am-dummy", nil
}
type S struct{}
var _ = gc.Suite(&S{})
func (s *S) TestConst(c *gc.C) {
sch := schema.Const("foo")
out, err := sch.Coerce("foo", aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, "foo")
out, err = sch.Coerce(42, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `: expected "foo", got int\(42\)`)
out, err = sch.Coerce(nil, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `: expected "foo", got nothing`)
}
func (s *S) TestNilSuccess(c *gc.C) {
assertSuccess := func(sch schema.Checker) {
out, err := sch.Coerce(nil, aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.IsNil)
}
sch := schema.Nil("")
assertSuccess(sch)
sch = schema.Nil("any label")
assertSuccess(sch)
}
var nonNilValues = []interface{}{42, "", "foo", false, 3.14, 0}
func (s *S) TestNilFailuresWithEmptyLabel(c *gc.C) {
sch := schema.Nil("")
testCheckerFailsForEachBadValueWithErrorPrefix(sch, c, nonNilValues, `: expected empty value`)
}
func (s *S) TestNilFailuresWithNonEmptyLabel(c *gc.C) {
sch := schema.Nil("wallet")
testCheckerFailsForEachBadValueWithErrorPrefix(sch, c, nonNilValues, `: expected empty wallet`)
}
func (s *S) TestNonEmptyStringSuccess(c *gc.C) {
assertSuccess := func(sch schema.Checker) {
out, err := sch.Coerce("non-empty value is ok", aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, "non-empty value is ok")
}
sch := schema.NonEmptyString("")
assertSuccess(sch)
sch = schema.NonEmptyString("any label")
assertSuccess(sch)
}
var badNonEmptyStringValues = []interface{}{42, "", []string{"x"}, false, 3.14, 0}
func (s *S) TestNonEmptyStringWithEmptyLabel(c *gc.C) {
sch := schema.NonEmptyString("")
testCheckerFailsForEachBadValueWithErrorPrefix(sch, c, badNonEmptyStringValues, `: expected non-empty string`)
}
func (s *S) TestNonEmptyStringWithNonEmptyLabel(c *gc.C) {
sch := schema.NonEmptyString("free beer")
testCheckerFailsForEachBadValueWithErrorPrefix(sch, c, badNonEmptyStringValues, `: expected non-empty free beer`)
}
func testCheckerFailsForEachBadValueWithErrorPrefix(sch schema.Checker, c *gc.C, badValues []interface{}, errorPrefix string) {
for _, badValue := range badValues {
out, err := sch.Coerce(badValue, aPath)
c.Check(out, gc.IsNil)
errorSuffix := fmt.Sprintf(", got %T(%#v)", badValue, badValue)
c.Check(err, gc.NotNil)
c.Check(err.Error(), gc.Equals, errorPrefix+errorSuffix)
}
}
func (s *S) TestAny(c *gc.C) {
sch := schema.Any()
out, err := sch.Coerce("foo", aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, "foo")
out, err = sch.Coerce(nil, aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, nil)
}
func (s *S) TestOneOf(c *gc.C) {
sch := schema.OneOf(schema.Const("foo"), schema.Const(42))
out, err := sch.Coerce("foo", aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, "foo")
out, err = sch.Coerce(42, aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, 42)
out, err = sch.Coerce("bar", aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `: unexpected value "bar"`)
}
func (s *S) TestBool(c *gc.C) {
sch := schema.Bool()
for _, trueValue := range []interface{}{true, "1", "true", "True", "TRUE"} {
out, err := sch.Coerce(trueValue, aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, true)
}
for _, falseValue := range []interface{}{false, "0", "false", "False", "FALSE"} {
out, err := sch.Coerce(falseValue, aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, false)
}
out, err := sch.Coerce(42, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `: expected bool, got int\(42\)`)
out, err = sch.Coerce(nil, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, ": expected bool, got nothing")
}
func (s *S) TestInt(c *gc.C) {
sch := schema.Int()
out, err := sch.Coerce(42, aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, int64(42))
out, err = sch.Coerce(int8(42), aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, int64(42))
out, err = sch.Coerce("42", aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, int64(42))
out, err = sch.Coerce(true, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `: expected int, got bool\(true\)`)
out, err = sch.Coerce(nil, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, ": expected int, got nothing")
}
func (s *S) TestUint(c *gc.C) {
sch := schema.Uint()
out, err := sch.Coerce(42, aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, uint64(42))
out, err = sch.Coerce(int8(42), aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, uint64(42))
out, err = sch.Coerce(uint8(42), aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, uint64(42))
out, err = sch.Coerce("42", aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, uint64(42))
out, err = sch.Coerce("-42", aPath)
c.Assert(out, gc.IsNil)
c.Assert(err.Error(), gc.Equals, `: expected uint, got string("-42")`)
out, err = sch.Coerce(-42, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err.Error(), gc.Equals, ": expected uint, got int(-42)")
out, err = sch.Coerce(true, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err.Error(), gc.Equals, ": expected uint, got bool(true)")
out, err = sch.Coerce(nil, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err.Error(), gc.Equals, ": expected uint, got nothing")
}
func (s *S) TestForceInt(c *gc.C) {
sch := schema.ForceInt()
out, err := sch.Coerce(42, aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, int(42))
out, err = sch.Coerce("42", aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, int(42))
out, err = sch.Coerce("42.66", aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, int(42))
out, err = sch.Coerce(int8(42), aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, int(42))
out, err = sch.Coerce(float32(42), aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, int(42))
out, err = sch.Coerce(float64(42), aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, int(42))
out, err = sch.Coerce(42.66, aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, int(42))
// If an out of range value is provided, that value is truncated,
// generating unexpected results, but no error is raised.
out, err = sch.Coerce(float64(math.MaxInt64+1), aPath)
c.Assert(err, gc.IsNil)
out, err = sch.Coerce(true, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `: expected number, got bool\(true\)`)
out, err = sch.Coerce(nil, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, ": expected number, got nothing")
}
func (s *S) TestForceUint(c *gc.C) {
sch := schema.ForceUint()
out, err := sch.Coerce(42, aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, uint64(42))
out, err = sch.Coerce(-42, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err.Error(), gc.Equals, `: expected uint, got int(-42)`)
out, err = sch.Coerce("-42", aPath)
c.Assert(out, gc.IsNil)
c.Assert(err.Error(), gc.Equals, `: expected uint, got string("-42")`)
out, err = sch.Coerce("42", aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, uint64(42))
out, err = sch.Coerce("42.66", aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, uint64(42))
out, err = sch.Coerce(int8(42), aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, uint64(42))
out, err = sch.Coerce(uint8(42), aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, uint64(42))
out, err = sch.Coerce(float32(42), aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, uint64(42))
out, err = sch.Coerce(float64(42), aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, uint64(42))
out, err = sch.Coerce(42.66, aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, uint64(42))
out, err = sch.Coerce(float64(-42), aPath)
c.Assert(out, gc.IsNil)
c.Assert(err.Error(), gc.Equals, `: expected uint, got float64(-42)`)
// If an out of range value is provided, that value is truncated,
// generating unexpected results, but no error is raised.
out, err = sch.Coerce(float64(math.MaxInt64+1), aPath)
c.Assert(err, gc.IsNil)
out, err = sch.Coerce(true, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `: expected uint, got bool\(true\)`)
out, err = sch.Coerce(nil, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, ": expected uint, got nothing")
}
func (s *S) TestFloat(c *gc.C) {
sch := schema.Float()
out, err := sch.Coerce(float32(1.0), aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, float64(1.0))
out, err = sch.Coerce(float64(1.0), aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, float64(1.0))
out, err = sch.Coerce(int8(1), aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, float64(1))
out, err = sch.Coerce(int64(math.MaxInt64), aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, float64(math.MaxInt64))
out, err = sch.Coerce(int64(math.MinInt64), aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, float64(math.MinInt64))
out, err = sch.Coerce(uint64(0), aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, float64(0))
out, err = sch.Coerce(uint64(math.MaxUint64), aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, float64(math.MaxUint64))
out, err = sch.Coerce(true, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `: expected float, got bool\(true\)`)
out, err = sch.Coerce(nil, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, ": expected float, got nothing")
}
func (s *S) TestString(c *gc.C) {
sch := schema.String()
out, err := sch.Coerce("foo", aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, "foo")
out, err = sch.Coerce(true, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `: expected string, got bool\(true\)`)
out, err = sch.Coerce(nil, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, ": expected string, got nothing")
}
func (s *S) TestURL(c *gc.C) {
mustParse := func(s string) *url.URL {
u, err := url.Parse(s)
c.Assert(err, gc.IsNil)
return u
}
sch := schema.URL()
out, err := sch.Coerce("foo", aPath)
c.Assert(err, gc.IsNil)
expected := mustParse("foo")
c.Assert(*(out.(*url.URL)), gc.Equals, *expected)
out, err = sch.Coerce(true, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `: expected url string, got bool\(true\)`)
out, err = sch.Coerce(nil, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, ": expected url string, got nothing")
out, err = sch.Coerce(":::", aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `: expected valid url, got string\(":::"\)`)
}
func (s *S) TestSimpleRegexp(c *gc.C) {
sch := schema.SimpleRegexp()
out, err := sch.Coerce("[0-9]+", aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, "[0-9]+")
out, err = sch.Coerce(1, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `: expected regexp string, got int\(1\)`)
out, err = sch.Coerce("[", aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `: expected valid regexp, got string\("\["\)`)
out, err = sch.Coerce(nil, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `: expected regexp string, got nothing`)
}
func (s *S) TestList(c *gc.C) {
sch := schema.List(schema.Int())
out, err := sch.Coerce([]int8{1, 2}, aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.DeepEquals, []interface{}{int64(1), int64(2)})
out, err = sch.Coerce(42, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, ": expected list, got int\\(42\\)")
out, err = sch.Coerce(nil, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, ": expected list, got nothing")
out, err = sch.Coerce([]interface{}{1, true}, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `\[1\]: expected int, got bool\(true\)`)
}
func (s *S) TestMap(c *gc.C) {
sch := schema.Map(schema.String(), schema.Int())
out, err := 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 = sch.Coerce(42, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, ": expected map, got int\\(42\\)")
out, err = sch.Coerce(nil, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, ": expected map, got nothing")
out, err = sch.Coerce(map[int]int{1: 1}, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, ": expected string, got int\\(1\\)")
out, err = sch.Coerce(map[string]bool{"a": true}, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `\.a: expected int, got bool\(true\)`)
// First path entry shouldn't have dots in an error message.
out, err = 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 = sch.Coerce(nil, nil)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `expected map, got nothing`)
}
func (s *S) TestStringMap(c *gc.C) {
sch := schema.StringMap(schema.Int())
out, err := sch.Coerce(map[string]interface{}{"a": 1, "b": int8(2)}, aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.DeepEquals, map[string]interface{}{"a": int64(1), "b": int64(2)})
out, err = sch.Coerce(42, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, ": expected map, got int\\(42\\)")
out, err = sch.Coerce(nil, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, ": expected map, got nothing")
out, err = sch.Coerce(map[int]int{1: 1}, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, ": expected string, got int\\(1\\)")
out, err = sch.Coerce(map[string]bool{"a": true}, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `\.a: expected int, got bool\(true\)`)
// First path entry shouldn't have dots in an error message.
out, err = sch.Coerce(map[string]bool{"a": true}, nil)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `a: expected int, got bool\(true\)`)
}
func assertFieldMap(c *gc.C, sch schema.Checker) {
out, err := sch.Coerce(map[string]interface{}{"a": "A", "b": "B"}, aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.DeepEquals, map[string]interface{}{"a": "A", "b": "B", "c": "C"})
out, err = sch.Coerce(42, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, ": expected map, got int\\(42\\)")
out, err = sch.Coerce(nil, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, ": expected map, got nothing")
out, err = sch.Coerce(map[string]interface{}{"a": "A", "b": "C"}, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `\.b: expected "B", got string\("C"\)`)
out, err = sch.Coerce(map[string]interface{}{"b": "B"}, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `\.a: expected "A", got nothing`)
// b is optional
out, err = sch.Coerce(map[string]interface{}{"a": "A"}, aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.DeepEquals, map[string]interface{}{"a": "A", "c": "C"})
// First path entry shouldn't have dots in an error message.
out, err = sch.Coerce(map[string]bool{"a": true}, nil)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `a: expected "A", got bool\(true\)`)
}
func (s *S) TestFieldMapBasic(c *gc.C) {
fields := schema.Fields{
"a": schema.Const("A"),
"b": schema.Const("B"),
"c": schema.Const("C"),
}
defaults := schema.Defaults{
"b": schema.Omit,
"c": "C",
}
sch := schema.FieldMap(fields, defaults)
assertFieldMap(c, sch)
out, err := sch.Coerce(map[string]interface{}{"a": "A", "b": "B", "d": "D"}, aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.DeepEquals, map[string]interface{}{"a": "A", "b": "B", "c": "C"})
out, err = sch.Coerce(map[string]interface{}{"a": "A", "d": "D"}, aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.DeepEquals, map[string]interface{}{"a": "A", "c": "C"})
out, err = sch.Coerce(123, aPath)
c.Assert(err, gc.ErrorMatches, `: expected map, got int\(123\)`)
c.Assert(out, gc.Equals, nil)
out, err = sch.Coerce(map[int]string{}, aPath)
c.Assert(err, gc.ErrorMatches, `: expected map\[string], got map\[int]string\(map\[int]string{}\)`)
c.Assert(out, gc.Equals, nil)
type strKey string
out, err = sch.Coerce(map[strKey]string{"a": "A"}, aPath)
c.Assert(err, gc.ErrorMatches, `: expected map\[string], got map\[schema_test\.strKey]string\(map\[schema_test.strKey]string{"a":"A"}\)`)
c.Assert(out, gc.Equals, nil)
}
func (s *S) TestFieldMapInterfaceKey(c *gc.C) {
fields := schema.Fields{
"a": schema.Const("A"),
}
sch := schema.FieldMap(fields, nil)
out, err := sch.Coerce(map[interface{}]interface{}{"a": "A"}, aPath)
c.Assert(err, gc.IsNil)
c.Check(out, gc.DeepEquals, map[string]interface{}{"a": "A"})
_, err = sch.Coerce(map[interface{}]interface{}{1: "A"}, aPath)
c.Check(err, gc.ErrorMatches, `: expected map\[string], got map\[interface {}]interface {}\(map\[interface {}]interface {}{1:"A"}\)`)
}
func (s *S) TestFieldMapDefaultInvalid(c *gc.C) {
fields := schema.Fields{
"a": schema.Const("A"),
}
defaults := schema.Defaults{
"a": "B",
}
sch := schema.FieldMap(fields, defaults)
_, err := sch.Coerce(map[string]interface{}{}, aPath)
c.Assert(err, gc.ErrorMatches, `.a: expected "A", got string\("B"\)`)
}
func (s *S) TestStrictFieldMap(c *gc.C) {
fields := schema.Fields{
"a": schema.Const("A"),
"b": schema.Const("B"),
"c": schema.Const("C"),
}
defaults := schema.Defaults{
"b": schema.Omit,
"c": "C",
}
sch := schema.StrictFieldMap(fields, defaults)
assertFieldMap(c, sch)
out, err := sch.Coerce(map[string]interface{}{"a": "A", "b": "B", "d": "D"}, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `: unknown key "d" \(value "D"\)`)
out, err = sch.Coerce(map[string]interface{}{"a": "A", "b": "B", "d": "D"}, nil)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `unknown key "d" \(value "D"\)`)
}
func (s *S) TestSchemaMap(c *gc.C) {
fields1 := schema.FieldMap(schema.Fields{
"type": schema.Const(1),
"a": schema.Const(2),
}, nil)
fields2 := schema.FieldMap(schema.Fields{
"type": schema.Const(3),
"b": schema.Const(4),
}, nil)
sch := schema.FieldMapSet("type", []schema.Checker{fields1, fields2})
out, err := sch.Coerce(map[string]int{"type": 1, "a": 2}, aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.DeepEquals, map[string]interface{}{"type": 1, "a": 2})
out, err = sch.Coerce(map[string]int{"type": 3, "b": 4}, aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.DeepEquals, map[string]interface{}{"type": 3, "b": 4})
out, err = sch.Coerce(map[string]int{}, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `\.type: expected supported selector, got nothing`)
out, err = sch.Coerce(map[string]int{"type": 2}, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `\.type: expected supported selector, got int\(2\)`)
out, err = sch.Coerce(map[string]int{"type": 3, "b": 5}, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `\.b: expected 4, got int\(5\)`)
out, err = sch.Coerce(42, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `: expected map, got int\(42\)`)
out, err = sch.Coerce(nil, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `: expected map, got nothing`)
// First path entry shouldn't have dots in an error message.
out, err = sch.Coerce(map[string]int{"a": 1}, nil)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `type: expected supported selector, got nothing`)
}
func (s *S) TestUUID(c *gc.C) {
sch := schema.UUID()
out, err := sch.Coerce("6216dfc3-6e82-408f-9f74-8565e63e6158", aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, "6216dfc3-6e82-408f-9f74-8565e63e6158")
out, err = sch.Coerce("uuid", aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `: expected uuid, got string\(\"uuid\"\)`)
out, err = sch.Coerce(nil, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err, gc.ErrorMatches, ": expected uuid, got nothing")
}
func (s *S) TestTime(c *gc.C) {
sch := schema.Time()
var empty time.Time
value := time.Date(2016, 10, 9, 12, 34, 56, 0, time.UTC)
out, err := sch.Coerce("", aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, empty)
out, err = sch.Coerce(value.Format(time.RFC3339Nano), aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, value)
out, err = sch.Coerce("invalid", aPath)
c.Assert(out, gc.IsNil)
c.Assert(err.Error(), gc.Equals, `: conversion to time: parsing time "invalid" as "2006-01-02T15:04:05.999999999Z07:00": cannot parse "invalid" as "2006"`)
out, err = sch.Coerce(42, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err.Error(), gc.Equals, ": expected string or time.Time, got int(42)")
out, err = sch.Coerce(nil, aPath)
c.Assert(out, gc.IsNil)
c.Assert(err.Error(), gc.Equals, ": expected string or time.Time, got nothing")
}
func (s *S) TestStringified(c *gc.C) {
sch := schema.Stringified()
out, err := sch.Coerce(true, aPath)
c.Assert(err, gc.IsNil)
c.Check(out, gc.Equals, "true")
out, err = sch.Coerce(10, aPath)
c.Assert(err, gc.IsNil)
c.Check(out, gc.Equals, "10")
out, err = sch.Coerce(1.1, aPath)
c.Assert(err, gc.IsNil)
c.Check(out, gc.Equals, "1.1")
out, err = sch.Coerce("spam", aPath)
c.Assert(err, gc.IsNil)
c.Check(out, gc.Equals, "spam")
_, err = sch.Coerce(map[string]string{}, aPath)
c.Check(err, gc.ErrorMatches, ".* unexpected value .*")
_, err = sch.Coerce([]string{}, aPath)
c.Check(err, gc.ErrorMatches, ".* unexpected value .*")
sch = schema.Stringified(schema.StringMap(schema.String()))
out, err = sch.Coerce(map[string]string{"a": "b"}, aPath)
c.Assert(err, gc.IsNil)
c.Check(out, gc.Equals, `map[string]string{"a":"b"}`)
}
func (s *S) TestSize(c *gc.C) {
sch := schema.Size()
//Invalid size
out, err := sch.Coerce("18X", aPath)
c.Assert(err.Error(), gc.Equals, "invalid multiplier suffix \"X\", expected one of MGTPEZY")
c.Assert(out, gc.IsNil)
//Valid Size
out, err = sch.Coerce("18G", aPath)
c.Assert(err, gc.IsNil)
c.Assert(out, gc.Equals, uint64(18432))
//Empty string
out, err = sch.Coerce("", aPath)
c.Assert(err.Error(), gc.Equals, ": expected empty string, got string(\"\")")
c.Assert(out, gc.IsNil)
//Nil
out, err = sch.Coerce(nil, aPath)
c.Assert(err.Error(), gc.Equals, ": expected string, got nothing")
c.Assert(out, gc.IsNil)
//Invalid type
var foo int
out, err = sch.Coerce(foo, aPath)
c.Assert(err.Error(), gc.Equals, ": expected string, got int(0)")
c.Assert(out, gc.IsNil)
}
schema-1.2.0/size.go 0000664 0000000 0000000 00000004165 14520671313 0014263 0 ustar 00root root 0000000 0000000 // Copyright 2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package schema
import (
"fmt"
"math"
"strconv"
"strings"
"reflect"
"unicode"
)
// Size returns a Checker that accepts a string value, and returns
// the parsed string as a size in mebibytes see: https://godoc.org/github.com/juju/utils#ParseSize
func Size() Checker {
return sizeC{}
}
type sizeC struct{}
// Coerce implements Checker Coerce method.
func (c sizeC) Coerce(v interface{}, path []string) (interface{}, error) {
if v == nil {
return nil, error_{"string", v, path}
}
typeOf := reflect.TypeOf(v).Kind()
if typeOf != reflect.String {
return nil, error_{"string", v, path}
}
value := reflect.ValueOf(v).String()
if value == "" {
return nil, error_{"empty string", v, path}
}
v, err := parseSize(value)
if err != nil {
return nil, err
}
return v, nil
}
// parseSize parses the string as a size, in mebibytes.
//
// The string must be a is a non-negative number with
// an optional multiplier suffix (M, G, T, P, E, Z, or Y).
// If the suffix is not specified, "M" is implied.
//
// Note: this function has been copied from github.com/juju/utils
// to avoid that heavy dependency.
func parseSize(str string) (MB uint64, err error) {
// Find the first non-digit/period:
i := strings.IndexFunc(str, func(r rune) bool {
return r != '.' && !unicode.IsDigit(r)
})
var multiplier float64 = 1
if i > 0 {
suffix := str[i:]
multiplier = 0
for j := 0; j < len(sizeSuffixes); j++ {
base := string(sizeSuffixes[j])
// M, MB, or MiB are all valid.
switch suffix {
case base, base + "B", base + "iB":
multiplier = float64(sizeSuffixMultiplier(j))
break
}
}
if multiplier == 0 {
return 0, fmt.Errorf("invalid multiplier suffix %q, expected one of %s", suffix, []byte(sizeSuffixes))
}
str = str[:i]
}
val, err := strconv.ParseFloat(str, 64)
if err != nil || val < 0 {
return 0, fmt.Errorf("expected a non-negative number, got %q", str)
}
val *= multiplier
return uint64(math.Ceil(val)), nil
}
var sizeSuffixes = "MGTPEZY"
func sizeSuffixMultiplier(i int) int {
return 1 << uint(i*10)
}
schema-1.2.0/size_test.go 0000664 0000000 0000000 00000002320 14520671313 0015311 0 ustar 00root root 0000000 0000000 // Copyright 2014 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package schema
import (
gc "gopkg.in/check.v1"
)
var _ = gc.Suite(&sizeSuite{})
type sizeSuite struct {}
func (*sizeSuite) TestParseSize(c *gc.C) {
type test struct {
in string
out uint64
err string
}
tests := []test{{
in: "",
err: `expected a non-negative number, got ""`,
}, {
in: "-1",
err: `expected a non-negative number, got "-1"`,
}, {
in: "1MZ",
err: `invalid multiplier suffix "MZ", expected one of MGTPEZY`,
}, {
in: "0",
out: 0,
}, {
in: "123",
out: 123,
}, {
in: "1M",
out: 1,
}, {
in: "0.5G",
out: 512,
}, {
in: "0.5GB",
out: 512,
}, {
in: "0.5GiB",
out: 512,
}, {
in: "0.5T",
out: 524288,
}, {
in: "0.5P",
out: 536870912,
}, {
in: "0.0009765625E",
out: 1073741824,
}, {
in: "1Z",
out: 1125899906842624,
}, {
in: "1Y",
out: 1152921504606846976,
}}
for i, test := range tests {
c.Logf("test %d: %+v", i, test)
size, err := parseSize(test.in)
if test.err != "" {
c.Assert(err, gc.NotNil)
c.Assert(err, gc.ErrorMatches, test.err)
} else {
c.Assert(err, gc.IsNil)
c.Assert(size, gc.Equals, test.out)
}
}
}
schema-1.2.0/strings.go 0000664 0000000 0000000 00000010023 14520671313 0014770 0 ustar 00root root 0000000 0000000 // Copyright 2015 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package schema
import (
"fmt"
"net/url"
"reflect"
"regexp"
)
// String returns a Checker that accepts a string value only and returns
// it unprocessed.
func String() Checker {
return stringC{}
}
type stringC struct{}
func (c stringC) Coerce(v interface{}, path []string) (interface{}, error) {
if v != nil && reflect.TypeOf(v).Kind() == reflect.String {
return reflect.ValueOf(v).String(), nil
}
return nil, error_{"string", v, path}
}
// URL returns a Checker that accepts a string value that must be parseable as a
// URL, and returns a *net.URL.
func URL() Checker {
return urlC{}
}
type urlC struct{}
func (c urlC) Coerce(v interface{}, path []string) (interface{}, error) {
if v != nil && reflect.TypeOf(v).Kind() == reflect.String {
s := reflect.ValueOf(v).String()
u, err := url.Parse(s)
if err != nil {
return nil, error_{"valid url", s, path}
}
return u, nil
}
return nil, error_{"url string", v, path}
}
// SimpleRegexp returns a checker that accepts a string value that is
// a valid regular expression and returns it unprocessed.
func SimpleRegexp() Checker {
return sregexpC{}
}
type sregexpC struct{}
func (c sregexpC) Coerce(v interface{}, path []string) (interface{}, error) {
// XXX The regexp package happens to be extremely simple right now.
// Once exp/regexp goes mainstream, we'll have to update this
// logic to use a more widely accepted regexp subset.
if v != nil && reflect.TypeOf(v).Kind() == reflect.String {
s := reflect.ValueOf(v).String()
_, err := regexp.Compile(s)
if err != nil {
return nil, error_{"valid regexp", s, path}
}
return v, nil
}
return nil, error_{"regexp string", v, path}
}
// UUID returns a Checker that accepts a string value only and returns
// it unprocessed.
func UUID() Checker {
return uuidC{}
}
type uuidC struct{}
var uuidregex = regexp.MustCompile(`[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}`)
func (c uuidC) Coerce(v interface{}, path []string) (interface{}, error) {
if v != nil && reflect.TypeOf(v).Kind() == reflect.String {
uuid := reflect.ValueOf(v).String()
if uuidregex.MatchString(uuid) {
return uuid, nil
}
}
return nil, error_{"uuid", v, path}
}
// Stringified returns a checker that accepts a bool/int/float/string
// value and returns its string. Other value types may be supported by
// passing in their checkers.
func Stringified(checkers ...Checker) Checker {
return stringifiedC{
checkers: checkers,
}
}
type stringifiedC struct {
checkers []Checker
}
func (c stringifiedC) Coerce(v interface{}, path []string) (interface{}, error) {
if newStr, err := String().Coerce(v, path); err == nil {
return newStr, nil
}
_, err := OneOf(append(c.checkers,
Bool(),
Int(),
Float(),
String(),
URL(),
)...).Coerce(v, path)
if err != nil {
return nil, err
}
return fmt.Sprintf("%#v", v), nil
}
// NonEmptyString returns a Checker that only accepts non-empty strings. To
// tweak the error message, valueLabel can contain a label of the value being
// checked, e.g. "my special name". If valueLabel is "", "string" will be used
// as a label instead.
//
// Example 1:
// schema.NonEmptyString("widget").Coerce("", nil) will return an error message
// like `expected non-empty widget, got string("")`.
//
// Example 2:
// schema.NonEmptyString("").Coerce("", nil) will return an error message like
// `expected non-empty string, got string("")`.
func NonEmptyString(valueLabel string) Checker {
if valueLabel == "" {
valueLabel = "string"
}
return nonEmptyStringC{valueLabel}
}
type nonEmptyStringC struct {
valueLabel string
}
func (c nonEmptyStringC) Coerce(v interface{}, path []string) (interface{}, error) {
label := fmt.Sprintf("non-empty %s", c.valueLabel)
invalidError := error_{label, v, path}
if v == nil || reflect.TypeOf(v).Kind() != reflect.String {
return nil, invalidError
}
if stringValue := reflect.ValueOf(v).String(); stringValue != "" {
return stringValue, nil
}
return nil, invalidError
}
schema-1.2.0/time.go 0000664 0000000 0000000 00000001656 14520671313 0014251 0 ustar 00root root 0000000 0000000 // Copyright 2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package schema
import (
"reflect"
"time"
)
// Time returns a Checker that accepts a string value, and returns
// the parsed time.Time value. Emtpy strings are considered empty times.
func Time() Checker {
return timeC{}
}
type timeC struct{}
// Coerce implements Checker Coerce method.
func (c timeC) Coerce(v interface{}, path []string) (interface{}, error) {
if v == nil {
return nil, error_{"string or time.Time", v, path}
}
var empty time.Time
switch reflect.TypeOf(v).Kind() {
case reflect.TypeOf(empty).Kind():
return v, nil
case reflect.String:
vstr := reflect.ValueOf(v).String()
if vstr == "" {
return empty, nil
}
v, err := time.Parse(time.RFC3339Nano, vstr)
if err != nil {
return nil, parseError(path, "time", err)
}
return v, nil
default:
return nil, error_{"string or time.Time", v, path}
}
}
schema-1.2.0/time_duration.go 0000664 0000000 0000000 00000003417 14520671313 0016153 0 ustar 00root root 0000000 0000000 // Copyright 2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package schema
import (
"reflect"
"time"
)
// TimeDuration returns a Checker that accepts a string or time.Duration value,
// and returns the parsed time.Duration value.
// Empty strings are considered empty time.Duration.
func TimeDuration() Checker {
return timeDurationC{}
}
type timeDurationC struct{}
// Coerce implements Checker Coerce method.
func (c timeDurationC) Coerce(v interface{}, path []string) (interface{}, error) {
return asTimeDuration(v, path)
}
// TimeDurationString returns a Checker that accepts a string or time.Duration
// value, and returns the time.Duration encoded as a string. The encoding
// uses the time.Duration.String() method.
// Empty strings are considered empty time.Duration.
func TimeDurationString() Checker {
return timeDurationStringC{}
}
type timeDurationStringC struct{}
// Coerce implements Checker Coerce method.
func (c timeDurationStringC) Coerce(v interface{}, path []string) (interface{}, error) {
dur, err := asTimeDuration(v, path)
if err != nil || dur == nil {
return "", err
}
d, ok := dur.(time.Duration)
if !ok {
return "", nil
}
return d.String(), nil
}
func asTimeDuration(v interface{}, path []string) (interface{}, error) {
if v == nil {
return nil, error_{want: "string or time.Duration", got: v, path: path}
}
var empty time.Duration
switch reflect.TypeOf(v).Kind() {
case reflect.TypeOf(empty).Kind():
return v, nil
case reflect.String:
vstr := reflect.ValueOf(v).String()
if vstr == "" {
return empty, nil
}
v, err := time.ParseDuration(vstr)
if err != nil {
return nil, parseError(path, "duration", err)
}
return v, nil
default:
return nil, error_{"string or time.Duration", v, path}
}
}
schema-1.2.0/time_duration_test.go 0000664 0000000 0000000 00000004241 14520671313 0017206 0 ustar 00root root 0000000 0000000 // Copyright 2023 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package schema_test
import (
"time"
"github.com/juju/schema"
gc "gopkg.in/check.v1"
)
type timeDurationSuite struct{}
var _ = gc.Suite(&timeDurationSuite{})
func (s *timeDurationSuite) TestTimeDuration(c *gc.C) {
sch := schema.TimeDuration()
var empty time.Duration
out, err := sch.Coerce("", aPath)
c.Assert(err, gc.IsNil)
c.Check(out, gc.Equals, empty)
value, _ := time.ParseDuration("18h")
out, err = sch.Coerce("18h", aPath)
c.Assert(err, gc.IsNil)
c.Check(out, gc.Equals, value)
out, err = sch.Coerce("failure", aPath)
c.Assert(err.Error(), gc.Equals, ": conversion to duration: time: invalid duration \"failure\"")
c.Check(out, gc.IsNil)
out, err = sch.Coerce(42, aPath)
c.Assert(err.Error(), gc.Equals, ": expected string or time.Duration, got int(42)")
c.Check(out, gc.IsNil)
out, err = sch.Coerce(nil, aPath)
c.Assert(err.Error(), gc.Equals, ": expected string or time.Duration, got nothing")
c.Check(out, gc.IsNil)
}
func (s *timeDurationSuite) TestTimeDurationString(c *gc.C) {
sch := schema.TimeDurationString()
out, err := sch.Coerce("", aPath)
c.Assert(err, gc.IsNil)
c.Check(out, gc.Equals, "0s")
out, err = sch.Coerce("18h", aPath)
c.Assert(err, gc.IsNil)
// We get the long form because it's hours are greater than seconds.
c.Check(out, gc.Equals, "18h0m0s")
out, err = sch.Coerce("42m", aPath)
c.Assert(err, gc.IsNil)
c.Check(out, gc.Equals, "42m0s")
out, err = sch.Coerce("42s", aPath)
c.Assert(err, gc.IsNil)
c.Check(out, gc.Equals, "42s")
out, err = sch.Coerce("42ms", aPath)
c.Assert(err, gc.IsNil)
c.Check(out, gc.Equals, "42ms")
out, err = sch.Coerce("failure", aPath)
c.Assert(err.Error(), gc.Equals, ": conversion to duration: time: invalid duration \"failure\"")
c.Check(out, gc.Equals, "")
out, err = sch.Coerce(42, aPath)
c.Assert(err.Error(), gc.Equals, ": expected string or time.Duration, got int(42)")
c.Check(out, gc.Equals, "")
out, err = sch.Coerce(nil, aPath)
c.Assert(err.Error(), gc.Equals, ": expected string or time.Duration, got nothing")
c.Check(out, gc.Equals, "")
}