Skip to content

Instantly share code, notes, and snippets.

@lusis
Created January 9, 2018 06:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lusis/9aba3b4f0c85307ef3cd802e6a1bcf9c to your computer and use it in GitHub Desktop.
Save lusis/9aba3b4f0c85307ef3cd802e6a1bcf9c to your computer and use it in GitHub Desktop.
fml golang json.Unmarshal
package main
import (
"encoding/json"
"testing"
"github.com/alecthomas/assert"
"github.com/davecgh/go-spew/spew"
)
var dataOne = `{"foo":"bar", "description":"dataOne"}`
var dataTwo = `{"qux":"baz", "description":"dataTwo", "anint":1, "snarf":true}`
type dataOneType struct {
Foo string `json:"foo"`
Description string `json:"description"`
}
type dataTwoType struct {
Qux string `json:"qux"`
Description string `json:"description"`
AnInt int `json:"anint"`
Snarf bool `json:"snarf"`
}
func TestHappy(t *testing.T) {
d1 := &dataOneType{}
d2 := &dataTwoType{}
errd1 := json.Unmarshal([]byte(dataOne), d1)
assert.NoError(t, errd1)
spew.Dump(d1)
errd2 := json.Unmarshal([]byte(dataTwo), d2)
spew.Dump(d2)
assert.NoError(t, errd2)
}
func TestWTF(t *testing.T) {
d1 := &dataOneType{}
d2 := &dataTwoType{}
errd1 := json.Unmarshal([]byte(dataOne), d2)
spew.Dump(d2)
assert.Error(t, errd1)
errd2 := json.Unmarshal([]byte(dataTwo), d1)
spew.Dump(d1)
assert.Error(t, errd2)
}
== RUN TestHappy
(*main.dataOneType)(0xc420106460)({
Foo: (string) (len=3) "bar",
Description: (string) (len=7) "dataOne"
})
(*main.dataTwoType)(0xc420081200)({
Qux: (string) (len=3) "baz",
Description: (string) (len=7) "dataTwo",
AnInt: (int) 1,
Snarf: (bool) true
})
--- PASS: TestHappy (0.00s)
=== RUN TestWTF
(*main.dataTwoType)(0xc420081500)({
Qux: (string) "",
Description: (string) (len=7) "dataOne",
AnInt: (int) 0,
Snarf: (bool) false
})
--- FAIL: TestWTF (0.00s)
Error Trace: t_test.go:44
Error: Expected value not to be nil.
Messages: An error is expected but got nil.
FAIL
exit status 1
FAIL github.com/lusis/go-rundeck 0.003s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment