Commit 86276497 authored by lukas.burgey's avatar lukas.burgey

Fix handling of interface slices

parent 229d752a
......@@ -195,27 +195,29 @@ func UnmarshalOutput(inputBytes []byte, o *Output) (err error) {
// check answer type
switch t := answer.(type) {
case bool:
break
case string:
break
case []string:
break
case int:
break
case []int:
case bool, string, int:
break
// converting floats to ints here, as floats are _not_ intended here
case float64:
o.QuestionnaireAnswers[qName] = int(answer.(float64))
break
case []float64:
floats := answer.([]float64)
ints := make([]int, len(floats))
for i, v := range floats {
ints[i] = int(v)
case []interface{}:
list := answer.([]interface{})
if len(list) > 0 {
// determine type of list
switch list[0].(type) {
case string:
continue
case float64:
intList := make([]int, len(list))
for i, v := range list {
intList[i] = int(v.(float64))
}
o.QuestionnaireAnswers[qName] = intList
default:
err = fmt.Errorf("QuestionnaireAnswers contains invalid answer: %v (%T)", answer, t)
}
}
o.QuestionnaireAnswers[qName] = ints
break
default:
err = fmt.Errorf("QuestionnaireAnswers contains invalid answer: %v (%T)", answer, t)
......
package scripts
import (
"encoding/json"
"fmt"
"testing"
)
func checkOutput(o *Output) (err error) {
if o.Msg == "" {
return fmt.Errorf("Output.Msg is empty")
}
return
}
func testOutput(rawOutput []byte, t *testing.T) {
var err error
output := new(Output)
err = json.Unmarshal(rawOutput, output)
if err != nil {
t.Errorf("Unmarshal failed: %s", err)
}
err = checkOutput(output)
err = UnmarshalOutput(rawOutput, output)
if err != nil {
t.Errorf("checkOutput failed: %s", err)
t.Errorf("Unmarshal failed: %s for output:\n%s", err, rawOutput)
}
}
func TestArbitraryQuestionnaire(t *testing.T) {
rawOutputs := [][]byte{
[]byte(`{
"message": "foo",
"questionnaire": {
"A string question": "answer"
}
}`),
[]byte(`{
"message": "foo",
"questionnaire": {
"An integer question": 0
}
}`),
[]byte(`{
"message": "foo",
"questionnaire": {
"A boolean question": false
}
}`),
[]byte(`{
func TestQuestionnaireAnswers(t *testing.T) {
baseOutput := `{
"message": "foo",
"state": "questionnaire",
"questionnaire": {
"A selector question": ["option a", "option b"]
"qname": "foo"
},
"questionnaire_answers": {
"qname": %s
}
}`),
}`
rawOutputs := []string{
`"answer"`,
"18",
"false",
`["option a", "option b"]`,
"[8, 19]",
}
for _, rawOutput := range rawOutputs {
testOutput(rawOutput, t)
for _, qa := range rawOutputs {
testOutput([]byte(fmt.Sprintf(baseOutput, qa)), t)
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment