Fix the dependency issue (#231)

This commit is contained in:
Robbie Zhang
2018-06-21 12:09:42 -07:00
committed by GitHub
parent 027b76651d
commit 6ec1098bb8
16629 changed files with 74837 additions and 4975021 deletions

View File

@@ -1 +0,0 @@
*.coverprofile

View File

@@ -1,70 +0,0 @@
[![GoDoc](https://godoc.org/github.com/cloudfoundry-incubator/candiedyaml?status.svg)](https://godoc.org/github.com/cloudfoundry-incubator/candiedyaml)
candiedyaml
===========
-----
DEPRECATION NOTICE
------------------
The `candiedyaml` library is no longer under active development and will soon
be moved to the [cloudfoundry-attic](https://github.com/cloudfoundry-attic)
GitHub organization. We recommend the use of an alternative library such as
[`gopkg.in/yaml.v2`](https://gopkg.in/yaml.v2) instead.
-----
YAML for Go
A YAML 1.1 parser with support for YAML 1.2 features
Usage
-----
```go
package myApp
import (
"github.com/cloudfoundry-incubator/candiedyaml"
"fmt"
"os"
)
func main() {
file, err := os.Open("path/to/some/file.yml")
if err != nil {
println("File does not exist:", err.Error())
os.Exit(1)
}
defer file.Close()
document := new(interface{})
decoder := candiedyaml.NewDecoder(file)
err = decoder.Decode(document)
if err != nil {
println("Failed to decode document:", err.Error())
}
println("parsed yml into interface:", fmt.Sprintf("%#v", document))
fileToWrite, err := os.Create("path/to/some/new/file.yml")
if err != nil {
println("Failed to open file for writing:", err.Error())
os.Exit(1)
}
defer fileToWrite.Close()
encoder := candiedyaml.NewEncoder(fileToWrite)
err = encoder.Encode(document)
if err != nil {
println("Failed to encode document:", err.Error())
os.Exit(1)
}
return
}
```

View File

@@ -1,27 +0,0 @@
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package candiedyaml
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestCandiedyaml(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Candiedyaml Suite")
}

View File

@@ -1,915 +0,0 @@
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package candiedyaml
import (
"math"
"os"
"strconv"
"strings"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Decode", func() {
It("Decodes a file", func() {
f, _ := os.Open("fixtures/specification/example2_1.yaml")
d := NewDecoder(f)
var v interface{}
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
})
Context("strings", func() {
It("Decodes an empty string", func() {
d := NewDecoder(strings.NewReader(`""
`))
var v string
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(""))
})
It("Decodes an empty string to an interface", func() {
d := NewDecoder(strings.NewReader(`""
`))
var v interface{}
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(""))
})
It("Decodes a map containing empty strings to an interface", func() {
d := NewDecoder(strings.NewReader(`"" : ""
`))
var v interface{}
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[interface{}]interface{}{"": ""}))
})
It("Decodes strings starting with a colon", func() {
d := NewDecoder(strings.NewReader(`:colon
`))
var v interface{}
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(":colon"))
})
})
Context("Sequence", func() {
It("Decodes to interface{}s", func() {
f, _ := os.Open("fixtures/specification/example2_1.yaml")
d := NewDecoder(f)
var v interface{}
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect((v).([]interface{})).To(Equal([]interface{}{"Mark McGwire", "Sammy Sosa", "Ken Griffey"}))
})
It("Decodes to []string", func() {
f, _ := os.Open("fixtures/specification/example2_1.yaml")
d := NewDecoder(f)
v := make([]string, 0, 3)
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal([]string{"Mark McGwire", "Sammy Sosa", "Ken Griffey"}))
})
It("Decodes a sequence of maps", func() {
f, _ := os.Open("fixtures/specification/example2_12.yaml")
d := NewDecoder(f)
v := make([]map[string]interface{}, 1)
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal([]map[string]interface{}{
{"item": "Super Hoop", "quantity": int64(1)},
{"item": "Basketball", "quantity": int64(4)},
{"item": "Big Shoes", "quantity": int64(1)},
}))
})
Describe("As structs", func() {
It("Simple struct", func() {
f, _ := os.Open("fixtures/specification/example2_4.yaml")
d := NewDecoder(f)
type batter struct {
Name string
HR int64
AVG float64
}
v := make([]batter, 0, 1)
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal([]batter{
batter{Name: "Mark McGwire", HR: 65, AVG: 0.278},
batter{Name: "Sammy Sosa", HR: 63, AVG: 0.288},
}))
})
It("Tagged struct", func() {
f, _ := os.Open("fixtures/specification/example2_4.yaml")
d := NewDecoder(f)
type batter struct {
N string `yaml:"name"`
H int64 `yaml:"hr"`
A float64 `yaml:"avg"`
}
v := make([]batter, 0, 1)
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal([]batter{
batter{N: "Mark McGwire", H: 65, A: 0.278},
batter{N: "Sammy Sosa", H: 63, A: 0.288},
}))
})
It("handles null values", func() {
type S struct {
Default interface{}
}
d := NewDecoder(strings.NewReader(`
---
default:
`))
var s S
err := d.Decode(&s)
Expect(err).NotTo(HaveOccurred())
Expect(s).To(Equal(S{Default: nil}))
})
It("ignores missing tags", func() {
f, _ := os.Open("fixtures/specification/example2_4.yaml")
d := NewDecoder(f)
type batter struct {
N string `yaml:"name"`
HR int64
A float64
}
v := make([]batter, 0, 1)
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal([]batter{
batter{N: "Mark McGwire", HR: 65},
batter{N: "Sammy Sosa", HR: 63},
}))
})
})
It("Decodes a sequence of sequences", func() {
f, _ := os.Open("fixtures/specification/example2_5.yaml")
d := NewDecoder(f)
v := make([][]interface{}, 1)
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal([][]interface{}{
{"name", "hr", "avg"},
{"Mark McGwire", int64(65), float64(0.278)},
{"Sammy Sosa", int64(63), float64(0.288)},
}))
})
})
Context("Maps", func() {
It("Decodes to interface{}s", func() {
f, _ := os.Open("fixtures/specification/example2_2.yaml")
d := NewDecoder(f)
var v interface{}
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect((v).(map[interface{}]interface{})).To(Equal(map[interface{}]interface{}{
"hr": int64(65),
"avg": float64(0.278),
"rbi": int64(147),
}))
})
It("Decodes to a struct", func() {
f, _ := os.Open("fixtures/specification/example2_2.yaml")
d := NewDecoder(f)
type batter struct {
HR int64
AVG float64
RBI int64
}
v := batter{}
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(batter{HR: 65, AVG: 0.278, RBI: 147}))
})
It("Decodes to a map of string arrays", func() {
f, _ := os.Open("fixtures/specification/example2_9.yaml")
d := NewDecoder(f)
v := make(map[string][]string)
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string][]string{"hr": []string{"Mark McGwire", "Sammy Sosa"}, "rbi": []string{"Sammy Sosa", "Ken Griffey"}}))
})
})
Context("Sequence of Maps", func() {
It("Decodes to interface{}s", func() {
f, _ := os.Open("fixtures/specification/example2_4.yaml")
d := NewDecoder(f)
var v interface{}
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect((v).([]interface{})).To(Equal([]interface{}{
map[interface{}]interface{}{"name": "Mark McGwire", "hr": int64(65), "avg": float64(0.278)},
map[interface{}]interface{}{"name": "Sammy Sosa", "hr": int64(63), "avg": float64(0.288)},
}))
})
})
It("Decodes ascii art", func() {
f, _ := os.Open("fixtures/specification/example2_13.yaml")
d := NewDecoder(f)
v := ""
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(`\//||\/||
// || ||__
`))
})
It("Decodes folded strings", func() {
f, _ := os.Open("fixtures/specification/example2_15.yaml")
d := NewDecoder(f)
v := ""
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal("Sammy Sosa completed another fine season with great stats.\n\n 63 Home Runs\n 0.288 Batting Average\n\nWhat a year!\n"))
})
It("Decodes literal and folded strings with indents", func() {
f, _ := os.Open("fixtures/specification/example2_16.yaml")
d := NewDecoder(f)
v := make(map[string]string)
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string]string{
"name": "Mark McGwire",
"accomplishment": `Mark set a major league home run record in 1998.
`,
"stats": `65 Home Runs
0.278 Batting Average
`,
}))
})
It("Decodes single quoted", func() {
f, _ := os.Open("fixtures/specification/example2_17_quoted.yaml")
d := NewDecoder(f)
v := make(map[string]string)
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string]string{
"quoted": ` # not a 'comment'.`,
}))
})
Context("ints", func() {
It("Decodes into an interface{}", func() {
f, _ := os.Open("fixtures/specification/example2_19.yaml")
d := NewDecoder(f)
v := make(map[string]interface{})
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string]interface{}{
"canonical": int64(12345),
"decimal": int64(12345),
"octal": int64(12),
"hexadecimal": int64(12),
}))
})
It("Decodes into int64", func() {
f, _ := os.Open("fixtures/specification/example2_19.yaml")
d := NewDecoder(f)
v := make(map[string]int64)
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string]int64{
"canonical": int64(12345),
"decimal": int64(12345),
"octal": int64(12),
"hexadecimal": int64(12),
}))
})
Context("boundary values", func() {
intoInt64 := func(val int64) {
It("Decodes into an int64 value", func() {
var v int64
d := NewDecoder(strings.NewReader(strconv.FormatInt(val, 10)))
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(val))
})
}
intoInt := func(val int) {
It("Decodes into an int value", func() {
var v int
d := NewDecoder(strings.NewReader(strconv.FormatInt(int64(val), 10)))
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(val))
})
}
intoInterface := func(val int64) {
It("Decodes into an interface{}", func() {
var v interface{}
d := NewDecoder(strings.NewReader(strconv.FormatInt(val, 10)))
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(val))
})
}
intoInt64(math.MaxInt64)
intoInterface(math.MaxInt64)
intoInt64(math.MinInt64)
intoInterface(math.MinInt64)
intoInt(math.MaxInt32)
intoInt(math.MinInt32)
})
})
It("Decodes a variety of floats", func() {
f, _ := os.Open("fixtures/specification/example2_20.yaml")
d := NewDecoder(f)
v := make(map[string]float64)
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(math.IsNaN(v["not a number"])).To(BeTrue())
delete(v, "not a number")
Expect(v).To(Equal(map[string]float64{
"canonical": float64(1230.15),
"exponential": float64(1230.15),
"fixed": float64(1230.15),
"negative infinity": math.Inf(-1),
}))
})
It("Decodes booleans, nil and strings", func() {
f, _ := os.Open("fixtures/specification/example2_21.yaml")
d := NewDecoder(f)
v := make(map[string]interface{})
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string]interface{}{
"": interface{}(nil),
"true": true,
"false": false,
"string": "12345",
}))
})
It("Decodes a null ptr", func() {
d := NewDecoder(strings.NewReader(`null
`))
var v *bool
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(BeNil())
})
It("Decodes dates/time", func() {
f, _ := os.Open("fixtures/specification/example2_22.yaml")
d := NewDecoder(f)
v := make(map[string]time.Time)
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string]time.Time{
"canonical": time.Date(2001, time.December, 15, 2, 59, 43, int(1*time.Millisecond), time.UTC),
"iso8601": time.Date(2001, time.December, 14, 21, 59, 43, int(10*time.Millisecond), time.FixedZone("", -5*3600)),
"spaced": time.Date(2001, time.December, 14, 21, 59, 43, int(10*time.Millisecond), time.FixedZone("", -5*3600)),
"date": time.Date(2002, time.December, 14, 0, 0, 0, 0, time.UTC),
}))
})
Context("Tags", func() {
It("Respects tags", func() {
f, _ := os.Open("fixtures/specification/example2_23_non_date.yaml")
d := NewDecoder(f)
v := make(map[string]string)
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string]string{
"not-date": "2002-04-28",
}))
})
It("handles non-specific tags", func() {
d := NewDecoder(strings.NewReader(`
---
not_parsed: ! 123
`))
v := make(map[string]int)
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string]int{"not_parsed": 123}))
})
It("handles non-specific tags", func() {
d := NewDecoder(strings.NewReader(`
---
? a complex key
: ! "123"
`))
v := make(map[string]string)
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string]string{"a complex key": "123"}))
})
})
Context("Decodes binary/base64", func() {
It("to []byte", func() {
f, _ := os.Open("fixtures/specification/example2_23_picture.yaml")
d := NewDecoder(f)
v := make(map[string][]byte)
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string][]byte{
"picture": []byte{0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x0c, 0x00,
0x0c, 0x00, 0x84, 0x00, 0x00, 0xff, 0xff, 0xf7, 0xf5, 0xf5, 0xee,
0xe9, 0xe9, 0xe5, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0xe7, 0xe7,
0xe7, 0x5e, 0x5e, 0x5e, 0xf3, 0xf3, 0xed, 0x8e, 0x8e, 0x8e, 0xe0,
0xe0, 0xe0, 0x9f, 0x9f, 0x9f, 0x93, 0x93, 0x93, 0xa7, 0xa7, 0xa7,
0x9e, 0x9e, 0x9e, 0x69, 0x5e, 0x10, 0x27, 0x20, 0x82, 0x0a, 0x01,
0x00, 0x3b},
}))
})
It("to string", func() {
d := NewDecoder(strings.NewReader("!binary YWJjZGVmZw=="))
var v string
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal("abcdefg"))
})
It("to string via alternate form", func() {
d := NewDecoder(strings.NewReader("!!binary YWJjZGVmZw=="))
var v string
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal("abcdefg"))
})
It("to interface", func() {
d := NewDecoder(strings.NewReader("!binary YWJjZGVmZw=="))
var v interface{}
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal([]byte("abcdefg")))
})
})
Context("Aliases", func() {
Context("to known types", func() {
It("aliases scalars", func() {
f, _ := os.Open("fixtures/specification/example2_10.yaml")
d := NewDecoder(f)
v := make(map[string][]string)
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string][]string{
"hr": {"Mark McGwire", "Sammy Sosa"},
"rbi": {"Sammy Sosa", "Ken Griffey"},
}))
})
It("aliases sequences", func() {
d := NewDecoder(strings.NewReader(`
---
hr: &ss
- MG
- SS
rbi: *ss
`))
v := make(map[string][]string)
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string][]string{
"hr": {"MG", "SS"},
"rbi": {"MG", "SS"},
}))
})
It("aliases maps", func() {
d := NewDecoder(strings.NewReader(`
---
hr: &ss
MG : SS
rbi: *ss
`))
v := make(map[string]map[string]string)
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string]map[string]string{
"hr": {"MG": "SS"},
"rbi": {"MG": "SS"},
}))
})
})
It("aliases to different types", func() {
type S struct {
A map[string]int
C map[string]string
}
d := NewDecoder(strings.NewReader(`
---
a: &map
b : 1
c: *map
`))
var s S
err := d.Decode(&s)
Expect(err).NotTo(HaveOccurred())
Expect(s).To(Equal(S{
A: map[string]int{"b": 1},
C: map[string]string{"b": "1"},
}))
})
It("fails if an anchor is undefined", func() {
d := NewDecoder(strings.NewReader(`
---
a: *missing
`))
m := make(map[string]string)
err := d.Decode(&m)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(MatchRegexp("missing anchor.*line.*column.*"))
})
Context("to Interface", func() {
It("aliases scalars", func() {
f, _ := os.Open("fixtures/specification/example2_10.yaml")
d := NewDecoder(f)
v := make(map[string]interface{})
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string]interface{}{
"hr": []interface{}{"Mark McGwire", "Sammy Sosa"},
"rbi": []interface{}{"Sammy Sosa", "Ken Griffey"},
}))
})
It("aliases sequences", func() {
d := NewDecoder(strings.NewReader(`
---
hr: &ss
- MG
- SS
rbi: *ss
`))
v := make(map[string]interface{})
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string]interface{}{
"hr": []interface{}{"MG", "SS"},
"rbi": []interface{}{"MG", "SS"},
}))
})
It("aliases maps", func() {
d := NewDecoder(strings.NewReader(`
---
hr: &ss
MG : SS
rbi: *ss
`))
v := make(map[string]interface{})
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string]interface{}{
"hr": map[interface{}]interface{}{"MG": "SS"},
"rbi": map[interface{}]interface{}{"MG": "SS"},
}))
})
It("supports duplicate aliases", func() {
d := NewDecoder(strings.NewReader(`
---
a: &a
b: 1
x: *a
y: *a
`))
v := make(map[string]interface{})
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string]interface{}{
"a": map[interface{}]interface{}{"b": int64(1)},
"x": map[interface{}]interface{}{"b": int64(1)},
"y": map[interface{}]interface{}{"b": int64(1)},
}))
})
It("supports overriden anchors", func() {
d := NewDecoder(strings.NewReader(`
---
First occurrence: &anchor Foo
Second occurrence: *anchor
Override anchor: &anchor Bar
Reuse anchor: *anchor
`))
v := make(map[string]interface{})
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string]interface{}{
"First occurrence": "Foo",
"Second occurrence": "Foo",
"Override anchor": "Bar",
"Reuse anchor": "Bar",
}))
})
It("fails if an anchor is undefined", func() {
d := NewDecoder(strings.NewReader(`
---
a: *missing
`))
var i interface{}
err := d.Decode(&i)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(MatchRegexp("missing anchor.*line.*column.*"))
})
})
It("supports composing aliases", func() {
d := NewDecoder(strings.NewReader(`
---
a: &a b
x: &b
d: *a
z: *b
`))
v := make(map[string]interface{})
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string]interface{}{
"a": "b",
"x": map[interface{}]interface{}{"d": "b"},
"z": map[interface{}]interface{}{"d": "b"},
}))
})
It("redefinition while composing aliases", func() {
d := NewDecoder(strings.NewReader(`
---
a: &a b
x: &c
d : &a 1
y: *a
`))
v := make(map[string]interface{})
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(Equal(map[string]interface{}{
"a": "b",
"x": map[interface{}]interface{}{"d": int64(1)},
"y": int64(1),
}))
})
It("can parse nested anchors", func() {
d := NewDecoder(strings.NewReader(`
---
a:
aa: &x
aaa: 1
ab:
aba: &y
abaa:
abaaa: *x
b:
- ba:
baa: *y
`))
v := make(map[string]interface{})
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
})
})
Context("When decoding fails", func() {
It("returns an error", func() {
f, _ := os.Open("fixtures/specification/example_empty.yaml")
d := NewDecoder(f)
var v interface{}
err := d.Decode(&v)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("Expected document start at line 0, column 0"))
})
})
Context("Unmarshaler support", func() {
Context("Receiver is a value", func() {
It("the Marshaler interface is not used", func() {
d := NewDecoder(strings.NewReader("abc\n"))
v := hasMarshaler{}
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v.Value).To(BeNil())
})
})
Context("Receiver is a pointer", func() {
It("uses the Marshaler interface when a pointer", func() {
d := NewDecoder(strings.NewReader("abc\n"))
v := hasPtrMarshaler{}
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
})
It("marshals a scalar", func() {
d := NewDecoder(strings.NewReader("abc\n"))
v := hasPtrMarshaler{}
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v.Tag).To(Equal(yaml_STR_TAG))
Expect(v.Value).To(Equal("abc"))
})
It("marshals a sequence", func() {
d := NewDecoder(strings.NewReader("[abc, def]\n"))
v := hasPtrMarshaler{}
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v.Tag).To(Equal(yaml_SEQ_TAG))
Expect(v.Value).To(Equal([]interface{}{"abc", "def"}))
})
It("marshals a map", func() {
d := NewDecoder(strings.NewReader("{ a: bc}\n"))
v := hasPtrMarshaler{}
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v.Tag).To(Equal(yaml_MAP_TAG))
Expect(v.Value).To(Equal(map[interface{}]interface{}{"a": "bc"}))
})
})
})
Context("Marshals into a Number", func() {
It("when the number is an int", func() {
d := NewDecoder(strings.NewReader("123\n"))
d.UseNumber()
var v Number
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v.String()).To(Equal("123"))
})
It("when the number is an float", func() {
d := NewDecoder(strings.NewReader("1.23\n"))
d.UseNumber()
var v Number
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v.String()).To(Equal("1.23"))
})
It("it fails when its a non-Number", func() {
d := NewDecoder(strings.NewReader("on\n"))
d.UseNumber()
var v Number
err := d.Decode(&v)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(MatchRegexp("Not a number: 'on' at line 0, column 0"))
})
It("returns a Number", func() {
d := NewDecoder(strings.NewReader("123\n"))
d.UseNumber()
var v interface{}
err := d.Decode(&v)
Expect(err).NotTo(HaveOccurred())
Expect(v).To(BeAssignableToTypeOf(Number("")))
n := v.(Number)
Expect(n.String()).To(Equal("123"))
})
})
Context("When there are special characters", func() {
It("returns an error", func() {
d := NewDecoder(strings.NewReader(`
---
applications:
- name: m
services:
- !@#
`))
var v interface{}
err := d.Decode(&v)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(MatchRegexp("yaml.*did not find.*line.*column.*"))
})
})
})

View File

@@ -1,642 +0,0 @@
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package candiedyaml
import (
"bytes"
"errors"
"math"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Encode", func() {
var buf *bytes.Buffer
var enc *Encoder
BeforeEach(func() {
buf = &bytes.Buffer{}
enc = NewEncoder(buf)
})
Context("Scalars", func() {
It("handles strings", func() {
err := enc.Encode("abc")
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`abc
`))
})
It("handles really short strings", func() {
err := enc.Encode(".")
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`.
`))
})
It("encodes strings with multilines", func() {
err := enc.Encode("a\nc")
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`|-
a
c
`))
})
It("handles strings that match known scalars", func() {
err := enc.Encode("true")
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`"true"
`))
})
It("handles strings that contain colons followed by whitespace", func() {
err := enc.Encode("contains: colon")
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`'contains: colon'
`))
})
Context("handles ints", func() {
It("handles ints", func() {
err := enc.Encode(13)
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal("13\n"))
})
It("handles uints", func() {
err := enc.Encode(uint64(1))
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal("1\n"))
})
})
Context("handles floats", func() {
It("handles float32", func() {
err := enc.Encode(float32(1.234))
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal("1.234\n"))
})
It("handles float64", func() {
err := enc.Encode(float64(1.2e23))
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal("1.2e+23\n"))
})
It("handles NaN", func() {
err := enc.Encode(math.NaN())
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(".nan\n"))
})
It("handles infinity", func() {
err := enc.Encode(math.Inf(-1))
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal("-.inf\n"))
})
})
It("handles bools", func() {
err := enc.Encode(true)
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal("true\n"))
})
It("handles time.Time", func() {
t := time.Now()
err := enc.Encode(t)
Expect(err).NotTo(HaveOccurred())
bytes, _ := t.MarshalText()
Expect(buf.String()).To(Equal(string(bytes) + "\n"))
})
Context("Null", func() {
It("fails on nil", func() {
err := enc.Encode(nil)
Expect(err).To(HaveOccurred())
})
})
It("handles []byte", func() {
err := enc.Encode([]byte{'a', 'b', 'c'})
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal("!!binary YWJj\n"))
})
Context("Ptrs", func() {
It("handles ptr of a type", func() {
p := new(int)
*p = 10
err := enc.Encode(p)
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal("10\n"))
})
It("handles nil ptr", func() {
var p *int
err := enc.Encode(p)
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal("null\n"))
})
})
Context("Structs", func() {
It("handles simple structs", func() {
type batter struct {
Name string
HR int64
AVG float64
}
batters := []batter{
batter{Name: "Mark McGwire", HR: 65, AVG: 0.278},
batter{Name: "Sammy Sosa", HR: 63, AVG: 0.288},
}
err := enc.Encode(batters)
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`- Name: Mark McGwire
HR: 65
AVG: 0.278
- Name: Sammy Sosa
HR: 63
AVG: 0.288
`))
})
It("handles tagged structs", func() {
type batter struct {
Name string `yaml:"name"`
HR int64
AVG float64 `yaml:"avg"`
}
batters := []batter{
batter{Name: "Mark McGwire", HR: 65, AVG: 0.278},
batter{Name: "Sammy Sosa", HR: 63, AVG: 0.288},
}
err := enc.Encode(batters)
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`- name: Mark McGwire
HR: 65
avg: 0.278
- name: Sammy Sosa
HR: 63
avg: 0.288
`))
})
It("handles nested structs", func() {
type nestedConfig struct {
AString string `yaml:"str"`
Integer int `yaml:"int"`
}
type config struct {
TopString string
Nested nestedConfig
}
cfg := config{
TopString: "def",
Nested: nestedConfig{
AString: "abc",
Integer: 123,
},
}
err := enc.Encode(cfg)
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`TopString: def
Nested:
str: abc
int: 123
`))
})
It("handles inline structs", func() {
type NestedConfig struct {
AString string `yaml:"str"`
Integer int `yaml:"int"`
}
type config struct {
TopString string
NestedConfig
}
cfg := config{
TopString: "def",
NestedConfig: NestedConfig{
AString: "abc",
Integer: 123,
},
}
err := enc.Encode(cfg)
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`TopString: def
str: abc
int: 123
`))
})
It("handles inline structs with conflicts", func() {
type NestedConfig struct {
AString string `yaml:"str"`
Integer int `yaml:"int"`
}
type config struct {
AString string `yaml:"str"`
NestedConfig
}
cfg := config{
AString: "def",
NestedConfig: NestedConfig{
AString: "abc",
Integer: 123,
},
}
err := enc.Encode(cfg)
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`str: def
int: 123
`))
})
})
})
Context("Sequence", func() {
It("handles slices", func() {
val := []string{"a", "b", "c"}
err := enc.Encode(val)
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`- a
- b
- c
`))
})
})
Context("Maps", func() {
It("Encodes simple maps", func() {
err := enc.Encode(&map[string]string{
"name": "Mark McGwire",
"hr": "65",
"avg": "0.278",
})
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`avg: "0.278"
hr: "65"
name: Mark McGwire
`))
})
It("sorts by key when strings otherwise by kind", func() {
err := enc.Encode(&map[interface{}]string{
1.2: "float",
8: "integer",
"name": "Mark McGwire",
"hr": "65",
"avg": "0.278",
})
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`8: integer
1.2: float
avg: "0.278"
hr: "65"
name: Mark McGwire
`))
})
It("encodes mix types", func() {
err := enc.Encode(&map[string]interface{}{
"name": "Mark McGwire",
"hr": 65,
"avg": 0.278,
})
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`avg: 0.278
hr: 65
name: Mark McGwire
`))
})
})
Context("Sequence of Maps", func() {
It("encodes", func() {
err := enc.Encode([]map[string]interface{}{
{"name": "Mark McGwire",
"hr": 65,
"avg": 0.278,
},
{"name": "Sammy Sosa",
"hr": 63,
"avg": 0.288,
},
})
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`- avg: 0.278
hr: 65
name: Mark McGwire
- avg: 0.288
hr: 63
name: Sammy Sosa
`))
})
})
Context("Maps of Sequence", func() {
It("encodes", func() {
err := enc.Encode(map[string][]interface{}{
"name": []interface{}{"Mark McGwire", "Sammy Sosa"},
"hr": []interface{}{65, 63},
"avg": []interface{}{0.278, 0.288},
})
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`avg:
- 0.278
- 0.288
hr:
- 65
- 63
name:
- Mark McGwire
- Sammy Sosa
`))
})
})
Context("Flow", func() {
It("flows structs", func() {
type i struct {
A string
}
type o struct {
I i `yaml:"i,flow"`
}
err := enc.Encode(o{
I: i{A: "abc"},
})
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`i: {A: abc}
`))
})
It("flows sequences", func() {
type i struct {
A string
}
type o struct {
I []i `yaml:"i,flow"`
}
err := enc.Encode(o{
I: []i{{A: "abc"}},
})
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`i: [{A: abc}]
`))
})
})
Context("Omit empty", func() {
It("omits nil ptrs", func() {
type i struct {
A *string `yaml:"a,omitempty"`
}
type o struct {
I []i `yaml:"i,flow"`
}
err := enc.Encode(o{
I: []i{{A: nil}},
})
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`i: [{}]
`))
})
})
Context("Skip field", func() {
It("does not include the field", func() {
type a struct {
B string `yaml:"-"`
C string
}
err := enc.Encode(a{B: "b", C: "c"})
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`C: c
`))
})
})
Context("Marshaler support", func() {
Context("Receiver is a value", func() {
It("uses the Marshaler interface when a value", func() {
err := enc.Encode(hasMarshaler{Value: 123})
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal("123\n"))
})
It("uses the Marshaler interface when a pointer", func() {
err := enc.Encode(&hasMarshaler{Value: "abc"})
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`abc
`))
})
Context("when it fails", func() {
It("returns an error", func() {
err := enc.Encode(&hasMarshaler{Value: "abc", Error: errors.New("fail")})
Expect(err).To(MatchError("fail"))
})
})
})
Context("Receiver is a pointer", func() {
It("uses the Marshaler interface when a pointer", func() {
err := enc.Encode(&hasPtrMarshaler{Value: map[string]string{"a": "b"}})
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`a: b
`))
})
It("skips the Marshaler when its a value", func() {
err := enc.Encode(hasPtrMarshaler{Value: map[string]string{"a": "b"}})
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`Tag: ""
Value:
a: b
Error: null
`))
})
Context("the receiver is nil", func() {
var ptr *hasPtrMarshaler
Context("when it fails", func() {
It("returns an error", func() {
err := enc.Encode(&hasPtrMarshaler{Value: "abc", Error: errors.New("fail")})
Expect(err).To(MatchError("fail"))
})
})
It("returns a null", func() {
err := enc.Encode(ptr)
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`null
`))
})
It("returns a null value for ptr types", func() {
err := enc.Encode(map[string]*hasPtrMarshaler{"a": ptr})
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`a: null
`))
})
It("panics when used as a nil interface", func() {
Expect(func() { enc.Encode(map[string]Marshaler{"a": ptr}) }).To(Panic())
})
})
Context("the receiver has a nil value", func() {
ptr := &hasPtrMarshaler{Value: nil}
It("returns null", func() {
err := enc.Encode(ptr)
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`null
`))
})
Context("in a map", func() {
It("returns a null value for ptr types", func() {
err := enc.Encode(map[string]*hasPtrMarshaler{"a": ptr})
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`a: null
`))
})
It("returns a null value for interface types", func() {
err := enc.Encode(map[string]Marshaler{"a": ptr})
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`a: null
`))
})
})
Context("in a slice", func() {
It("returns a null value for ptr types", func() {
err := enc.Encode([]*hasPtrMarshaler{ptr})
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`- null
`))
})
It("returns a null value for interface types", func() {
err := enc.Encode([]Marshaler{ptr})
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal(`- null
`))
})
})
})
})
})
Context("Number type", func() {
It("encodes as a number", func() {
n := Number("12345")
err := enc.Encode(n)
Expect(err).NotTo(HaveOccurred())
Expect(buf.String()).To(Equal("12345\n"))
})
})
})
type hasMarshaler struct {
Value interface{}
Error error
}
func (m hasMarshaler) MarshalYAML() (string, interface{}, error) {
return "", m.Value, m.Error
}
func (m hasMarshaler) UnmarshalYAML(tag string, value interface{}) error {
m.Value = value
return nil
}
type hasPtrMarshaler struct {
Tag string
Value interface{}
Error error
}
func (m *hasPtrMarshaler) MarshalYAML() (string, interface{}, error) {
return "", m.Value, m.Error
}
func (m *hasPtrMarshaler) UnmarshalYAML(tag string, value interface{}) error {
m.Tag = tag
m.Value = value
return nil
}

View File

@@ -1,3 +0,0 @@
- Mark McGwire
- Sammy Sosa
- Ken Griffey

View File

@@ -1,8 +0,0 @@
---
hr:
- Mark McGwire
# Following node labeled SS
- &SS Sammy Sosa
rbi:
- *SS # Subsequent occurrence
- Ken Griffey

View File

@@ -1,9 +0,0 @@
? - Detroit Tigers
- Chicago cubs
:
- 2001-07-23
? [ New York Yankees,
Atlanta Braves ]
: [ 2001-07-02, 2001-08-12,
2001-08-14 ]

View File

@@ -1,8 +0,0 @@
---
# products purchased
- item : Super Hoop
quantity: 1
- item : Basketball
quantity: 4
- item : Big Shoes
quantity: 1

View File

@@ -1,4 +0,0 @@
# ASCII Art
--- |
\//||\/||
// || ||__

View File

@@ -1,4 +0,0 @@
---
Mark McGwire's
year was crippled
by a knee injury.

View File

@@ -1,8 +0,0 @@
>
Sammy Sosa completed another
fine season with great stats.
63 Home Runs
0.288 Batting Average
What a year!

View File

@@ -1,7 +0,0 @@
>
Sammy Sosa completed another fine season with great stats.
63 Home Runs
0.288 Batting Average
What a year!

View File

@@ -1,7 +0,0 @@
name: Mark McGwire
accomplishment: >
Mark set a major league
home run record in 1998.
stats: |
65 Home Runs
0.278 Batting Average

View File

@@ -1,7 +0,0 @@
unicode: "Sosa did fine.\u263A"
control: "\b1998\t1999\t2000\n"
hexesc: "\x0D\x0A is \r\n"
single: '"Howdy!" he cried.'
quoted: ' # not a ''comment''.'
tie-fighter: '|\-*-/|'

View File

@@ -1,2 +0,0 @@
control: "\b1998\t1999\t2000\n"

View File

@@ -1,2 +0,0 @@
hexesc: "\x0D\x0A is \r\n"

View File

@@ -1,2 +0,0 @@
quoted: ' # not a ''comment''.'

View File

@@ -1 +0,0 @@
single: '"Howdy!" he cried.'

View File

@@ -1 +0,0 @@
tie-fighter: '|\-*-/|'

View File

@@ -1,2 +0,0 @@
unicode: "Sosa did fine.\u263A"

View File

@@ -1,6 +0,0 @@
plain:
This unquoted scalar
spans many lines.
quoted: "So does this
quoted scalar.\n"

View File

@@ -1,4 +0,0 @@
canonical: 12345
decimal: +12_345
octal: 014
hexadecimal: 0xC

View File

@@ -1,3 +0,0 @@
hr: 65 # Home runs
avg: 0.278 # Batting average
rbi: 147 # Runs Batted In

View File

@@ -1,5 +0,0 @@
canonical: 1.23015e+3
exponential: 12.3015e+02
fixed: 1_230.15
negative infinity: -.inf
not a number: .NaN

View File

@@ -1,4 +0,0 @@
null: ~
true: yes
false: no
string: '12345'

View File

@@ -1,4 +0,0 @@
canonical: 2001-12-15T02:59:43.1Z
iso8601: 2001-12-14t21:59:43.10-05:00
spaced: 2001-12-14 21:59:43.10 -5
date: 2002-12-14

View File

@@ -1,14 +0,0 @@
---
not-date: !!str 2002-04-28
picture: !!binary "\
R0lGODlhDAAMAIQAAP//9/X\
17unp5WZmZgAAAOfn515eXv\
Pz7Y6OjuDg4J+fn5OTk6enp\
56enmleECcgggoBADs="
application specific tag: !something |
The semantics of the tag
above may be different for
different documents.

View File

@@ -1,5 +0,0 @@
---
application specific tag: !something |
The semantics of the tag
above may be different for
different documents.

View File

@@ -1,3 +0,0 @@
---
not-date: !!str 2002-04-28

View File

@@ -1,9 +0,0 @@
---
picture: !!binary "\
R0lGODlhDAAMAIQAAP//9/X\
17unp5WZmZgAAAOfn515eXv\
Pz7Y6OjuDg4J+fn5OTk6enp\
56enmleECcgggoBADs="

View File

@@ -1,14 +0,0 @@
%TAG ! tag:clarkevans.com,2002:
--- !shape
# Use the ! handle for presenting
# tag:clarkevans.com,2002:circle
- !circle
center: &ORIGIN {x: 73, y: 129}
radius: 7
- !line
start: *ORIGIN
finish: { x: 89, y: 102 }
- !label
start: *ORIGIN
color: 0xFFEEBB
text: Pretty vector drawing.

View File

@@ -1,11 +0,0 @@
!shape
- !circle
center: &id001 {x: 73, y: 129}
radius: 7
- !line
finish: {x: 89, y: 102}
start: *id001
- !label
color: 0xFFEEBB
start: *id001
text: Pretty vector drawing.

View File

@@ -1,7 +0,0 @@
# sets are represented as a
# mapping where each key is
# associated with the empty string
--- !!set
? Mark McGwire
? Sammy Sosa
? Ken Griff

View File

@@ -1,7 +0,0 @@
# ordered maps are represented as
# a sequence of mappings, with
# each mapping having one key
--- !!omap
- Mark McGwire: 65
- Sammy Sosa: 63
- Ken Griffy: 58

View File

@@ -1,29 +0,0 @@
--- !<tag:clarkevans.com,2002:invoice>
invoice: 34843
date : 2001-01-23
billTo: &id001
given : Chris
family : Dumars
address:
lines: |
458 Walkman Dr.
Suite #292
city : Royal Oak
state : MI
postal : 48046
shipTo: *id001
product:
- sku : BL394D
quantity : 4
description : Basketball
price : 450.00
- sku : BL4438H
quantity : 1
description : Super Hoop
price : 2392.00
tax : 251.42
total: 4443.52
comments:
Late afternoon is best.
Backup contact is Nancy
Billsmer @ 338-4338.

View File

@@ -1,20 +0,0 @@
!!org.yaml.snakeyaml.Invoice
billTo: &id001
address:
city: Royal Oak
lines: |
458 Walkman Dr.
Suite #292
postal: '48046'
state: MI
family: Dumars
given: Chris
comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.
date: '2001-01-23'
invoice: 34843
product:
- {description: Basketball, price: 450.0, quantity: 4, sku: BL394D}
- {description: Super Hoop, price: 2392.0, quantity: 1, sku: BL4438H}
shipTo: *id001
tax: 251.42
total: 4443.52

View File

@@ -1,29 +0,0 @@
---
Time: 2001-11-23 15:01:42 -5
User: ed
Warning:
This is an error message
for the log file
---
Time: 2001-11-23 15:02:31 -5
User: ed
Warning:
A slightly different error
message.
---
Date: 2001-11-23 15:03:17 -5
User: ed
Fatal:
Unknown variable "bar"
Stack:
- file: TopClass.py
line: 23
code: |
x = MoreObject("345\n")
- file: MoreClass.py
line: 58
code: |-
foo = bar

View File

@@ -1,8 +0,0 @@
american:
- Boston Red Sox
- Detroit Tigers
- New York Yankees
national:
- New York Mets
- Chicago Cubs
- Atlanta Braves

View File

@@ -1,8 +0,0 @@
-
name: Mark McGwire
hr: 65
avg: 0.278
-
name: Sammy Sosa
hr: 63
avg: 0.288

View File

@@ -1,3 +0,0 @@
- [name , hr, avg ]
- [Mark McGwire, 65, 0.278]
- [Sammy Sosa , 63, 0.288]

View File

@@ -1,5 +0,0 @@
Mark McGwire: {hr: 65, avg: 0.278}
Sammy Sosa: {
hr: 63,
avg: 0.288
}

View File

@@ -1,10 +0,0 @@
# Ranking of 1998 home runs
---
- Mark McGwire
- Sammy Sosa
- Ken Griffey
# Team ranking
---
- Chicago Cubs
- St Louis Cardinals

View File

@@ -1,10 +0,0 @@
---
time: 20:03:20
player: Sammy Sosa
action: strike (miss)
...
---
time: 20:03:47
player: Sammy Sosa
action: grand slam
...

View File

@@ -1,8 +0,0 @@
---
hr: # 1998 hr ranking
- Mark McGwire
- Sammy Sosa
rbi:
# 1998 rbi ranking
- Sammy Sosa
- Ken Griffey

View File

@@ -1,6 +0,0 @@
# Unordered set of key: value pairs.
Block style: !!map
Clark : Evans
Brian : Ingerson
Oren : Ben-Kiki
Flow style: !!map { Clark: Evans, Brian: Ingerson, Oren: Ben-Kiki }

View File

@@ -1,6 +0,0 @@
# Unordered set of key: value pairs.
Block style: !<tag:yaml.org,2002:map>
Clark : Evans
Brian : Ingerson
Oren : Ben-Kiki
Flow style: { Clark: Evans, Brian: Ingerson, Oren: Ben-Kiki }

View File

@@ -1,27 +0,0 @@
---
- &CENTER { x: 1, y: 2 }
- &LEFT { x: 0, y: 2 }
- &BIG { r: 10 }
- &SMALL { r: 1 }
# All the following maps are equal:
- # Explicit keys
x: 1
y: 2
r: 10
label: center/big
- # Merge one map
<< : *CENTER
r: 10
label: center/big
- # Merge multiple maps
<< : [ *CENTER, *BIG ]
label: center/big
- # Override
<< : [ *BIG, *LEFT, *SMALL ]
x: 1
label: center/big

View File

@@ -1,8 +0,0 @@
# Explicitly typed ordered map (dictionary).
Bestiary: !!omap
- aardvark: African pig-like ant eater. Ugly.
- anteater: South-American ant eater. Two species.
- anaconda: South-American constrictor snake. Scaly.
# Etc.
# Flow style
Numbers: !!omap [ one: 1, two: 2, three : 3 ]

View File

@@ -1,7 +0,0 @@
# Explicitly typed pairs.
Block tasks: !!pairs
- meeting: with team.
- meeting: with boss.
- break: lunch.
- meeting: with client.
Flow tasks: !!pairs [ meeting: with team, meeting: with boss ]

View File

@@ -1,14 +0,0 @@
# Ordered sequence of nodes
Block style: !!seq
- Mercury # Rotates - no light/dark sides.
- Venus # Deadliest. Aptly named.
- Earth # Mostly dirt.
- Mars # Seems empty.
- Jupiter # The king.
- Saturn # Pretty.
- Uranus # Where the sun hardly shines.
- Neptune # Boring. No rings.
- Pluto # You call this a planet?
Flow style: !!seq [ Mercury, Venus, Earth, Mars, # Rocks
Jupiter, Saturn, Uranus, Neptune, # Gas
Pluto ] # Overrated

View File

@@ -1,7 +0,0 @@
# Explicitly typed set.
baseball players: !!set
? Mark McGwire
? Sammy Sosa
? Ken Griffey
# Flow style
baseball teams: !!set { Boston Red Sox, Detroit Tigers, New York Yankees }

View File

@@ -1,4 +0,0 @@
--- # New schema
link with:
- = : library1.dll
version: 1.2

View File

@@ -1,10 +0,0 @@
--- # Old schema
link with:
- library1.dll
- library2.dll
--- # New schema
link with:
- = : library1.dll
version: 1.2
- = : library2.dll
version: 2.3

View File

@@ -1,19 +0,0 @@
Copyright (c) 2006 Kirill Simonov
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,81 +0,0 @@
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package candiedyaml
import (
"io/ioutil"
"os"
"path/filepath"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var parses = func(filename string) {
It("parses "+filename, func() {
file, err := os.Open(filename)
Expect(err).To(BeNil())
parser := yaml_parser_t{}
yaml_parser_initialize(&parser)
yaml_parser_set_input_reader(&parser, file)
failed := false
event := yaml_event_t{}
for {
if !yaml_parser_parse(&parser, &event) {
failed = true
println("---", parser.error, parser.problem, parser.context, "line", parser.problem_mark.line, "col", parser.problem_mark.column)
break
}
if event.event_type == yaml_STREAM_END_EVENT {
break
}
}
file.Close()
// msg := "SUCCESS"
// if failed {
// msg = "FAILED"
// if parser.error != yaml_NO_ERROR {
// m := parser.problem_mark
// fmt.Printf("ERROR: (%s) %s @ line: %d col: %d\n",
// parser.context, parser.problem, m.line, m.column)
// }
// }
Expect(failed).To(BeFalse())
})
}
var parseYamls = func(dirname string) {
fileInfos, err := ioutil.ReadDir(dirname)
if err != nil {
panic(err.Error())
}
for _, fileInfo := range fileInfos {
if !fileInfo.IsDir() {
parses(filepath.Join(dirname, fileInfo.Name()))
}
}
}
var _ = Describe("Parser", func() {
parseYamls("fixtures/specification")
parseYamls("fixtures/specification/types")
})

View File

@@ -1,291 +0,0 @@
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package candiedyaml
import (
// "fmt"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
/*
* Test cases are stolen from
* http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
*/
type test_case struct {
title string
test string
result bool
}
var _ = Describe("Reader", func() {
LONG := 100000
Context("UTF8 Sequences", func() {
utf8_sequences := []test_case{
/* {"title", "test 1|test 2|...|test N!", (0 or 1)}, */
{"a simple test", "'test' is '\xd0\xbf\xd1\x80\xd0\xbe\xd0\xb2\xd0\xb5\xd1\x80\xd0\xba\xd0\xb0' in Russian!", true},
{"an empty line", "!", true},
{"u-0 is a control character", "\x00!", false},
{"u-80 is a control character", "\xc2\x80!", false},
{"u-800 is valid", "\xe0\xa0\x80!", true},
{"u-10000 is valid", "\xf0\x90\x80\x80!", true},
{"5 bytes sequences are not allowed", "\xf8\x88\x80\x80\x80!", false},
{"6 bytes sequences are not allowed", "\xfc\x84\x80\x80\x80\x80!", false},
{"u-7f is a control character", "\x7f!", false},
{"u-7FF is valid", "\xdf\xbf!", true},
{"u-FFFF is a control character", "\xef\xbf\xbf!", false},
{"u-1FFFFF is too large", "\xf7\xbf\xbf\xbf!", false},
{"u-3FFFFFF is 5 bytes", "\xfb\xbf\xbf\xbf\xbf!", false},
{"u-7FFFFFFF is 6 bytes", "\xfd\xbf\xbf\xbf\xbf\xbf!", false},
{"u-D7FF", "\xed\x9f\xbf!", true},
{"u-E000", "\xee\x80\x80!", true},
{"u-FFFD", "\xef\xbf\xbd!", true},
{"u-10FFFF", "\xf4\x8f\xbf\xbf!", true},
{"u-110000", "\xf4\x90\x80\x80!", false},
{"first continuation byte", "\x80!", false},
{"last continuation byte", "\xbf!", false},
{"2 continuation bytes", "\x80\xbf!", false},
{"3 continuation bytes", "\x80\xbf\x80!", false},
{"4 continuation bytes", "\x80\xbf\x80\xbf!", false},
{"5 continuation bytes", "\x80\xbf\x80\xbf\x80!", false},
{"6 continuation bytes", "\x80\xbf\x80\xbf\x80\xbf!", false},
{"7 continuation bytes", "\x80\xbf\x80\xbf\x80\xbf\x80!", false},
{"sequence of all 64 possible continuation bytes",
"\x80|\x81|\x82|\x83|\x84|\x85|\x86|\x87|\x88|\x89|\x8a|\x8b|\x8c|\x8d|\x8e|\x8f|" +
"\x90|\x91|\x92|\x93|\x94|\x95|\x96|\x97|\x98|\x99|\x9a|\x9b|\x9c|\x9d|\x9e|\x9f|" +
"\xa0|\xa1|\xa2|\xa3|\xa4|\xa5|\xa6|\xa7|\xa8|\xa9|\xaa|\xab|\xac|\xad|\xae|\xaf|" +
"\xb0|\xb1|\xb2|\xb3|\xb4|\xb5|\xb6|\xb7|\xb8|\xb9|\xba|\xbb|\xbc|\xbd|\xbe|\xbf!", false},
{"32 first bytes of 2-byte sequences {0xc0-0xdf}",
"\xc0 |\xc1 |\xc2 |\xc3 |\xc4 |\xc5 |\xc6 |\xc7 |\xc8 |\xc9 |\xca |\xcb |\xcc |\xcd |\xce |\xcf |" +
"\xd0 |\xd1 |\xd2 |\xd3 |\xd4 |\xd5 |\xd6 |\xd7 |\xd8 |\xd9 |\xda |\xdb |\xdc |\xdd |\xde |\xdf !", false},
{"16 first bytes of 3-byte sequences {0xe0-0xef}",
"\xe0 |\xe1 |\xe2 |\xe3 |\xe4 |\xe5 |\xe6 |\xe7 |\xe8 |\xe9 |\xea |\xeb |\xec |\xed |\xee |\xef !", false},
{"8 first bytes of 4-byte sequences {0xf0-0xf7}", "\xf0 |\xf1 |\xf2 |\xf3 |\xf4 |\xf5 |\xf6 |\xf7 !", false},
{"4 first bytes of 5-byte sequences {0xf8-0xfb}", "\xf8 |\xf9 |\xfa |\xfb !", false},
{"2 first bytes of 6-byte sequences {0xfc-0xfd}", "\xfc |\xfd !", false},
{"sequences with last byte missing {u-0}",
"\xc0|\xe0\x80|\xf0\x80\x80|\xf8\x80\x80\x80|\xfc\x80\x80\x80\x80!", false},
{"sequences with last byte missing {u-...FF}",
"\xdf|\xef\xbf|\xf7\xbf\xbf|\xfb\xbf\xbf\xbf|\xfd\xbf\xbf\xbf\xbf!", false},
{"impossible bytes", "\xfe|\xff|\xfe\xfe\xff\xff!", false},
{"overlong sequences {u-2f}",
"\xc0\xaf|\xe0\x80\xaf|\xf0\x80\x80\xaf|\xf8\x80\x80\x80\xaf|\xfc\x80\x80\x80\x80\xaf!", false},
{"maximum overlong sequences",
"\xc1\xbf|\xe0\x9f\xbf|\xf0\x8f\xbf\xbf|\xf8\x87\xbf\xbf\xbf|\xfc\x83\xbf\xbf\xbf\xbf!", false},
{"overlong representation of the NUL character",
"\xc0\x80|\xe0\x80\x80|\xf0\x80\x80\x80|\xf8\x80\x80\x80\x80|\xfc\x80\x80\x80\x80\x80!", false},
{"single UTF-16 surrogates",
"\xed\xa0\x80|\xed\xad\xbf|\xed\xae\x80|\xed\xaf\xbf|\xed\xb0\x80|\xed\xbe\x80|\xed\xbf\xbf!", false},
{"paired UTF-16 surrogates",
"\xed\xa0\x80\xed\xb0\x80|\xed\xa0\x80\xed\xbf\xbf|\xed\xad\xbf\xed\xb0\x80|" +
"\xed\xad\xbf\xed\xbf\xbf|\xed\xae\x80\xed\xb0\x80|\xed\xae\x80\xed\xbf\xbf|" +
"\xed\xaf\xbf\xed\xb0\x80|\xed\xaf\xbf\xed\xbf\xbf!", false},
{"other illegal code positions", "\xef\xbf\xbe|\xef\xbf\xbf!", false},
}
check_sequence := func(tc test_case) {
It(tc.title, func() {
start := 0
end := start
bytes := []byte(tc.test)
for {
for bytes[end] != '|' && bytes[end] != '!' {
end++
}
parser := yaml_parser_t{}
yaml_parser_initialize(&parser)
yaml_parser_set_input_string(&parser, bytes)
result := yaml_parser_update_buffer(&parser, end-start)
Expect(result).To(Equal(tc.result))
// outcome := '+'
// if result != tc.result {
// outcome = '-'
// }
// fmt.Printf("\t\t %c %s", outcome, tc.title)
// if parser.error == yaml_NO_ERROR {
// fmt.Printf("(no error)\n")
// } else if parser.error == yaml_READER_ERROR {
// if parser.problem_value != -1 {
// fmt.Printf("(reader error: %s: #%X at %d)\n",
// parser.problem, parser.problem_value, parser.problem_offset)
// } else {
// fmt.Printf("(reader error: %s: at %d)\n",
// parser.problem, parser.problem_offset)
// }
// }
if bytes[end] == '!' {
break
}
end++
start = end
yaml_parser_delete(&parser)
}
})
}
for _, test := range utf8_sequences {
check_sequence(test)
}
})
Context("BOMs", func() {
boms := []test_case{
/* {"title", "test!", lenth}, */
{"no bom (utf-8)", "Hi is \xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82!", true},
{"bom (utf-8)", "\xef\xbb\xbfHi is \xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82!", true},
{"bom (utf-16-le)", "\xff\xfeH\x00i\x00 \x00i\x00s\x00 \x00\x1f\x04@\x04" + "8\x04" + "2\x04" + "5\x04" + "B\x04!", true},
{"bom (utf-16-be)", "\xfe\xff\x00H\x00i\x00 \x00i\x00s\x00 \x04\x1f\x04@\x04" + "8\x04" + "2\x04" + "5\x04" + "B!", true},
}
check_bom := func(tc test_case) {
It(tc.title, func() {
start := 0
end := start
bytes := []byte(tc.test)
for bytes[end] != '!' {
end++
}
parser := yaml_parser_t{}
yaml_parser_initialize(&parser)
yaml_parser_set_input_string(&parser, bytes[:end-start])
result := yaml_parser_update_buffer(&parser, end-start)
Expect(result).To(Equal(tc.result))
yaml_parser_delete(&parser)
})
}
for _, test := range boms {
check_bom(test)
}
})
Context("Long UTF8", func() {
It("parses properly", func() {
buffer := make([]byte, 0, 3+LONG*2)
buffer = append(buffer, '\xef', '\xbb', '\xbf')
for j := 0; j < LONG; j++ {
if j%2 == 1 {
buffer = append(buffer, '\xd0', '\x90')
} else {
buffer = append(buffer, '\xd0', '\xaf')
}
}
parser := yaml_parser_t{}
yaml_parser_initialize(&parser)
yaml_parser_set_input_string(&parser, buffer)
for k := 0; k < LONG; k++ {
if parser.unread == 0 {
updated := yaml_parser_update_buffer(&parser, 1)
Expect(updated).To(BeTrue())
// printf("\treader error: %s at %d\n", parser.problem, parser.problem_offset);
}
Expect(parser.unread).NotTo(Equal(0))
// printf("\tnot enough characters at %d\n", k);
var ch0, ch1 byte
if k%2 == 1 {
ch0 = '\xd0'
ch1 = '\x90'
} else {
ch0 = '\xd0'
ch1 = '\xaf'
}
Expect(parser.buffer[parser.buffer_pos]).To(Equal(ch0))
Expect(parser.buffer[parser.buffer_pos+1]).To(Equal(ch1))
// printf("\tincorrect UTF-8 sequence: %X %X instead of %X %X\n",
// (int)parser.buffer.pointer[0], (int)parser.buffer.pointer[1],
// (int)ch0, (int)ch1);
parser.buffer_pos += 2
parser.unread -= 1
}
updated := yaml_parser_update_buffer(&parser, 1)
Expect(updated).To(BeTrue())
// printf("\treader error: %s at %d\n", parser.problem, parser.problem_offset);
yaml_parser_delete(&parser)
})
})
Context("Long UTF16", func() {
It("parses properly", func() {
buffer := make([]byte, 0, 2+LONG*2)
buffer = append(buffer, '\xff', '\xfe')
for j := 0; j < LONG; j++ {
if j%2 == 1 {
buffer = append(buffer, '\x10', '\x04')
} else {
buffer = append(buffer, '/', '\x04')
}
}
parser := yaml_parser_t{}
yaml_parser_initialize(&parser)
yaml_parser_set_input_string(&parser, buffer)
for k := 0; k < LONG; k++ {
if parser.unread == 0 {
updated := yaml_parser_update_buffer(&parser, 1)
Expect(updated).To(BeTrue())
// printf("\treader error: %s at %d\n", parser.problem, parser.problem_offset);
}
Expect(parser.unread).NotTo(Equal(0))
// printf("\tnot enough characters at %d\n", k);
var ch0, ch1 byte
if k%2 == 1 {
ch0 = '\xd0'
ch1 = '\x90'
} else {
ch0 = '\xd0'
ch1 = '\xaf'
}
Expect(parser.buffer[parser.buffer_pos]).To(Equal(ch0))
Expect(parser.buffer[parser.buffer_pos+1]).To(Equal(ch1))
// printf("\tincorrect UTF-8 sequence: %X %X instead of %X %X\n",
// (int)parser.buffer.pointer[0], (int)parser.buffer.pointer[1],
// (int)ch0, (int)ch1);
parser.buffer_pos += 2
parser.unread -= 1
}
updated := yaml_parser_update_buffer(&parser, 1)
Expect(updated).To(BeTrue())
// printf("\treader error: %s at %d\n", parser.problem, parser.problem_offset);
yaml_parser_delete(&parser)
})
})
})

View File

@@ -1,665 +0,0 @@
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package candiedyaml
import (
"math"
"reflect"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Resolver", func() {
var event yaml_event_t
var nulls = []string{"~", "null", "Null", "NULL"}
BeforeEach(func() {
event = yaml_event_t{}
})
Context("Resolve", func() {
Context("Implicit events", func() {
checkNulls := func(f func()) {
for _, null := range nulls {
event = yaml_event_t{implicit: true}
event.value = []byte(null)
f()
}
}
BeforeEach(func() {
event.implicit = true
})
Context("String", func() {
It("resolves a string", func() {
aString := ""
v := reflect.ValueOf(&aString)
event.value = []byte("abc")
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_STR_TAG))
Expect(aString).To(Equal("abc"))
})
It("resolves the empty string", func() {
aString := "abc"
v := reflect.ValueOf(&aString)
event.value = []byte("")
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_STR_TAG))
Expect(aString).To(Equal(""))
})
It("resolves null", func() {
checkNulls(func() {
aString := "abc"
v := reflect.ValueOf(&aString)
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_NULL_TAG))
Expect(aString).To(Equal(""))
})
})
It("resolves null pointers", func() {
checkNulls(func() {
aString := "abc"
pString := &aString
v := reflect.ValueOf(&pString)
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_NULL_TAG))
Expect(pString).To(BeNil())
})
})
})
Context("Booleans", func() {
match_bool := func(val string, expected bool) {
b := !expected
v := reflect.ValueOf(&b)
event.value = []byte(val)
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_BOOL_TAG))
Expect(b).To(Equal(expected))
}
It("resolves on", func() {
match_bool("on", true)
match_bool("ON", true)
})
It("resolves off", func() {
match_bool("off", false)
match_bool("OFF", false)
})
It("resolves true", func() {
match_bool("true", true)
match_bool("TRUE", true)
})
It("resolves false", func() {
match_bool("false", false)
match_bool("FALSE", false)
})
It("resolves yes", func() {
match_bool("yes", true)
match_bool("YES", true)
})
It("resolves no", func() {
match_bool("no", false)
match_bool("NO", false)
})
It("reports an error otherwise", func() {
b := true
v := reflect.ValueOf(&b)
event.value = []byte("fail")
_, err := resolve(event, v.Elem(), false)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("Invalid boolean: 'fail' at line 0, column 0"))
})
It("resolves null", func() {
checkNulls(func() {
b := true
v := reflect.ValueOf(&b)
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_NULL_TAG))
Expect(b).To(BeFalse())
})
})
It("resolves null pointers", func() {
checkNulls(func() {
b := true
pb := &b
v := reflect.ValueOf(&pb)
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_NULL_TAG))
Expect(pb).To(BeNil())
})
})
})
Context("Ints", func() {
It("simple ints", func() {
i := 0
v := reflect.ValueOf(&i)
event.value = []byte("1234")
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_INT_TAG))
Expect(i).To(Equal(1234))
})
It("positive ints", func() {
i := int16(0)
v := reflect.ValueOf(&i)
event.value = []byte("+678")
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_INT_TAG))
Expect(i).To(Equal(int16(678)))
})
It("negative ints", func() {
i := int32(0)
v := reflect.ValueOf(&i)
event.value = []byte("-2345")
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_INT_TAG))
Expect(i).To(Equal(int32(-2345)))
})
It("base 8", func() {
i := 0
v := reflect.ValueOf(&i)
event.value = []byte("0o12")
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_INT_TAG))
Expect(i).To(Equal(10))
})
It("base 16", func() {
i := 0
v := reflect.ValueOf(&i)
event.value = []byte("0xff")
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_INT_TAG))
Expect(i).To(Equal(255))
})
It("fails on overflow", func() {
i := int8(0)
v := reflect.ValueOf(&i)
event.value = []byte("2345")
_, err := resolve(event, v.Elem(), false)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("Invalid integer: '2345' at line 0, column 0"))
})
It("fails on invalid int", func() {
i := 0
v := reflect.ValueOf(&i)
event.value = []byte("234f")
_, err := resolve(event, v.Elem(), false)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("Invalid integer: '234f' at line 0, column 0"))
})
It("resolves null", func() {
checkNulls(func() {
i := 1
v := reflect.ValueOf(&i)
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_NULL_TAG))
Expect(i).To(Equal(0))
})
})
It("resolves null pointers", func() {
checkNulls(func() {
i := 1
pi := &i
v := reflect.ValueOf(&pi)
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_NULL_TAG))
Expect(pi).To(BeNil())
})
})
It("returns a Number", func() {
var i Number
v := reflect.ValueOf(&i)
tag, err := resolve_int("12345", v.Elem(), true, event)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_INT_TAG))
Expect(i).To(Equal(Number("12345")))
Expect(i.Int64()).To(Equal(int64(12345)))
event.value = []byte("1234")
tag, err = resolve(event, v.Elem(), true)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_INT_TAG))
Expect(i).To(Equal(Number("1234")))
})
})
Context("UInts", func() {
It("resolves simple uints", func() {
i := uint(0)
v := reflect.ValueOf(&i)
event.value = []byte("1234")
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_INT_TAG))
Expect(i).To(Equal(uint(1234)))
})
It("resolves positive uints", func() {
i := uint16(0)
v := reflect.ValueOf(&i)
event.value = []byte("+678")
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_INT_TAG))
Expect(i).To(Equal(uint16(678)))
})
It("base 8", func() {
i := uint(0)
v := reflect.ValueOf(&i)
event.value = []byte("0o12")
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_INT_TAG))
Expect(i).To(Equal(uint(10)))
})
It("base 16", func() {
i := uint(0)
v := reflect.ValueOf(&i)
event.value = []byte("0xff")
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_INT_TAG))
Expect(i).To(Equal(uint(255)))
})
It("fails with negative ints", func() {
i := uint(0)
v := reflect.ValueOf(&i)
event.value = []byte("-2345")
_, err := resolve(event, v.Elem(), false)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("Unsigned int with negative value: '-2345' at line 0, column 0"))
})
It("fails on overflow", func() {
i := uint8(0)
v := reflect.ValueOf(&i)
event.value = []byte("2345")
_, err := resolve(event, v.Elem(), false)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("Invalid unsigned integer: '2345' at line 0, column 0"))
})
It("resolves null", func() {
checkNulls(func() {
i := uint(1)
v := reflect.ValueOf(&i)
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_NULL_TAG))
Expect(i).To(Equal(uint(0)))
})
})
It("resolves null pointers", func() {
checkNulls(func() {
i := uint(1)
pi := &i
v := reflect.ValueOf(&pi)
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_NULL_TAG))
Expect(pi).To(BeNil())
})
})
It("returns a Number", func() {
var i Number
v := reflect.ValueOf(&i)
tag, err := resolve_uint("12345", v.Elem(), true, event)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_INT_TAG))
Expect(i).To(Equal(Number("12345")))
event.value = []byte("1234")
tag, err = resolve(event, v.Elem(), true)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_INT_TAG))
Expect(i).To(Equal(Number("1234")))
})
})
Context("Floats", func() {
It("float32", func() {
f := float32(0)
v := reflect.ValueOf(&f)
event.value = []byte("2345.01")
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_FLOAT_TAG))
Expect(f).To(Equal(float32(2345.01)))
})
It("float64", func() {
f := float64(0)
v := reflect.ValueOf(&f)
event.value = []byte("-456456.01")
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_FLOAT_TAG))
Expect(f).To(Equal(float64(-456456.01)))
})
It("+inf", func() {
f := float64(0)
v := reflect.ValueOf(&f)
event.value = []byte("+.inf")
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_FLOAT_TAG))
Expect(f).To(Equal(math.Inf(1)))
})
It("-inf", func() {
f := float32(0)
v := reflect.ValueOf(&f)
event.value = []byte("-.inf")
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_FLOAT_TAG))
Expect(f).To(Equal(float32(math.Inf(-1))))
})
It("nan", func() {
f := float64(0)
v := reflect.ValueOf(&f)
event.value = []byte(".NaN")
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_FLOAT_TAG))
Expect(math.IsNaN(f)).To(BeTrue())
})
It("fails on overflow", func() {
i := float32(0)
v := reflect.ValueOf(&i)
event.value = []byte("123e10000")
_, err := resolve(event, v.Elem(), false)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("Invalid float: '123e10000' at line 0, column 0"))
})
It("fails on invalid float", func() {
i := float32(0)
v := reflect.ValueOf(&i)
event.value = []byte("123e1a")
_, err := resolve(event, v.Elem(), false)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("Invalid float: '123e1a' at line 0, column 0"))
})
It("resolves null", func() {
checkNulls(func() {
f := float64(1)
v := reflect.ValueOf(&f)
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_NULL_TAG))
Expect(f).To(Equal(0.0))
})
})
It("resolves null pointers", func() {
checkNulls(func() {
f := float64(1)
pf := &f
v := reflect.ValueOf(&pf)
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_NULL_TAG))
Expect(pf).To(BeNil())
})
})
It("returns a Number", func() {
var i Number
v := reflect.ValueOf(&i)
tag, err := resolve_float("12.345", v.Elem(), true, event)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_FLOAT_TAG))
Expect(i).To(Equal(Number("12.345")))
Expect(i.Float64()).To(Equal(12.345))
event.value = []byte("1.234")
tag, err = resolve(event, v.Elem(), true)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_FLOAT_TAG))
Expect(i).To(Equal(Number("1.234")))
})
})
Context("Timestamps", func() {
parse_date := func(val string, date time.Time) {
d := time.Now()
v := reflect.ValueOf(&d)
event.value = []byte(val)
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(""))
Expect(d).To(Equal(date))
}
It("date", func() {
parse_date("2002-12-14", time.Date(2002, time.December, 14, 0, 0, 0, 0, time.UTC))
})
It("canonical", func() {
parse_date("2001-12-15T02:59:43.1Z", time.Date(2001, time.December, 15, 2, 59, 43, int(1*time.Millisecond), time.UTC))
})
It("iso8601", func() {
parse_date("2001-12-14t21:59:43.10-05:00", time.Date(2001, time.December, 14, 21, 59, 43, int(10*time.Millisecond), time.FixedZone("", -5*3600)))
})
It("space separated", func() {
parse_date("2001-12-14 21:59:43.10 -5", time.Date(2001, time.December, 14, 21, 59, 43, int(10*time.Millisecond), time.FixedZone("", -5*3600)))
})
It("no time zone", func() {
parse_date("2001-12-15 2:59:43.10", time.Date(2001, time.December, 15, 2, 59, 43, int(10*time.Millisecond), time.UTC))
})
It("resolves null", func() {
checkNulls(func() {
d := time.Now()
v := reflect.ValueOf(&d)
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_NULL_TAG))
Expect(d).To(Equal(time.Time{}))
})
})
It("resolves null pointers", func() {
checkNulls(func() {
d := time.Now()
pd := &d
v := reflect.ValueOf(&pd)
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_NULL_TAG))
Expect(pd).To(BeNil())
})
})
})
Context("Binary tag", func() {
It("string", func() {
checkNulls(func() {
event.value = []byte("YWJjZGVmZw==")
event.tag = []byte("!binary")
aString := ""
v := reflect.ValueOf(&aString)
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_STR_TAG))
Expect(aString).To(Equal("abcdefg"))
})
})
It("[]byte", func() {
checkNulls(func() {
event.value = []byte("YWJjZGVmZw==")
event.tag = []byte("!binary")
bytes := []byte(nil)
v := reflect.ValueOf(&bytes)
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_STR_TAG))
Expect(bytes).To(Equal([]byte("abcdefg")))
})
})
It("returns a []byte when provided no hints", func() {
checkNulls(func() {
event.value = []byte("YWJjZGVmZw==")
event.tag = []byte("!binary")
var intf interface{}
v := reflect.ValueOf(&intf)
tag, err := resolve(event, v.Elem(), false)
Expect(err).NotTo(HaveOccurred())
Expect(tag).To(Equal(yaml_STR_TAG))
Expect(intf).To(Equal([]byte("abcdefg")))
})
})
})
It("fails to resolve a pointer", func() {
aString := ""
pString := &aString
v := reflect.ValueOf(&pString)
event.value = []byte("abc")
_, err := resolve(event, v.Elem(), false)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal("Unknown resolution for 'abc' using <*string Value> at line 0, column 0"))
})
})
Context("Not an implicit event && no tag", func() {
It("bool returns a string", func() {
event.value = []byte("on")
tag, result := resolveInterface(event, false)
Expect(result).To(Equal("on"))
Expect(tag).To(Equal(""))
})
It("number returns a string", func() {
event.value = []byte("1234")
tag, result := resolveInterface(event, false)
Expect(result).To(Equal("1234"))
Expect(tag).To(Equal(""))
})
It("returns the empty string", func() {
event.value = []byte("")
// event.implicit = true
tag, result := resolveInterface(event, false)
Expect(result).To(Equal(""))
Expect(tag).To(Equal(""))
})
})
})
})

View File

@@ -1,80 +0,0 @@
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package candiedyaml
import (
"io/ioutil"
"os"
"path/filepath"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var scan = func(filename string) {
It("scan "+filename, func() {
file, err := os.Open(filename)
Expect(err).To(BeNil())
parser := yaml_parser_t{}
yaml_parser_initialize(&parser)
yaml_parser_set_input_reader(&parser, file)
failed := false
token := yaml_token_t{}
for {
if !yaml_parser_scan(&parser, &token) {
failed = true
break
}
if token.token_type == yaml_STREAM_END_TOKEN {
break
}
}
file.Close()
// msg := "SUCCESS"
// if failed {
// msg = "FAILED"
// if parser.error != yaml_NO_ERROR {
// m := parser.problem_mark
// fmt.Printf("ERROR: (%s) %s @ line: %d col: %d\n",
// parser.context, parser.problem, m.line, m.column)
// }
// }
Expect(failed).To(BeFalse())
})
}
var scanYamls = func(dirname string) {
fileInfos, err := ioutil.ReadDir(dirname)
if err != nil {
panic(err.Error())
}
for _, fileInfo := range fileInfos {
if !fileInfo.IsDir() {
scan(filepath.Join(dirname, fileInfo.Name()))
}
}
}
var _ = Describe("Scanner", func() {
scanYamls("fixtures/specification")
scanYamls("fixtures/specification/types")
})