Skip to content

Commit

Permalink
add NewDataSetType
Browse files Browse the repository at this point in the history
  • Loading branch information
Joshua Rubin committed Mar 29, 2016
1 parent debe0f1 commit b1169ce
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
19 changes: 17 additions & 2 deletions go-msg/dataset.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@ func (e errInvalidDataSetType) Error() string {

// Various errors
var (
ErrNilDataSet = fmt.Errorf("dataset was nil")
ErrInvalidField = fmt.Errorf("dataset type does not exist in dataset definition")
ErrNilDataSet = fmt.Errorf("dataset was nil")
ErrInvalidField = fmt.Errorf("dataset type does not exist in dataset definition")
ErrInvalidDataSetType = fmt.Errorf("invalid dataset type")
)

// FieldByType returns one of the field values of a DataSet based on a
Expand Down Expand Up @@ -53,3 +54,17 @@ func (m *DataSet) FieldByType(dsType DataSetType) (interface{}, error) {
// (case-insensitive) field name
return nil, ErrInvalidField
}

// NewDataSetType returns the cooresponding DataSetType given a string. It is
// case insensitive.
func NewDataSetType(name string) (DataSetType, error) {
name = strings.ToLower(name)

for dst, dstName := range DataSetType_name {
if name == strings.ToLower(dstName) {
return DataSetType(dst), nil
}
}

return DataSetType(-1), ErrInvalidDataSetType
}
33 changes: 33 additions & 0 deletions go-msg/dataset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package msg

import (
"fmt"
"strings"
"testing"
)

Expand Down Expand Up @@ -133,3 +134,35 @@ func ExampleDataSet_FieldByType() {
fmt.Printf("c == ds.Categorization => %v\n", c == ds.Categorization)
// Output: c == ds.Categorization => true
}

func testDataSetType(t *testing.T, dstValue int32, dstName string) {
dst, err := NewDataSetType(strings.ToLower(dstName))
if err != nil {
t.Error("unexpected error")
}

if DataSetType(dstValue) != dst {
t.Error("unexpected dataset type value")
}
}

func TestNewDataSetType(t *testing.T) {
for dstValue, dstName := range DataSetType_name {
testDataSetType(t, dstValue, dstName)
testDataSetType(t, dstValue, strings.ToLower(dstName))
testDataSetType(t, dstValue, strings.ToUpper(dstName))
}

dst, err := NewDataSetType("invalid dataset type name")
if err == nil {
t.Error("NewDataSetType should have returned an error")
}

if err != ErrInvalidDataSetType {
t.Error("NewDataSetType returned the wrong error")
}

if dst != DataSetType(-1) {
t.Error("NewDataSetType returned wrong response")
}
}

0 comments on commit b1169ce

Please sign in to comment.