From a6e23938ebd39ea5bac0e25fbaf302efeb63df55 Mon Sep 17 00:00:00 2001 From: Cassowary Rusnov Date: Wed, 11 Jan 2023 20:28:19 -0800 Subject: [PATCH] Add tests to jsontable. - Test major functionality of jsontable - Fix bug discovered in testing. --- pkg/jsontable/jsontable.go | 2 +- pkg/jsontable/jsontable_test.go | 85 +++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 pkg/jsontable/jsontable_test.go diff --git a/pkg/jsontable/jsontable.go b/pkg/jsontable/jsontable.go index 350c8bc7..bc6cfdb6 100644 --- a/pkg/jsontable/jsontable.go +++ b/pkg/jsontable/jsontable.go @@ -109,7 +109,7 @@ func (t *JSONTable) _JSONRenderInner() { writeChar(t.out, '{') for keyidx, key := range t.keys { value := "nil" - if keyidx <= len(row) { + if keyidx < len(row) { value = row[keyidx] } if keyidx != 0 { diff --git a/pkg/jsontable/jsontable_test.go b/pkg/jsontable/jsontable_test.go new file mode 100644 index 00000000..159ffb69 --- /dev/null +++ b/pkg/jsontable/jsontable_test.go @@ -0,0 +1,85 @@ +package jsontable + +import ( + "testing" + + "bytes" + "encoding/json" + + "github.com/olekukonko/tablewriter" +) + + +var TestLine = []string{"1", "2"} +var TestGroup = [][]string {{"1", "2", "3"}, {"a", "teohunteohu", "c", "d"}, {"☺", "☹"}} +var TestKeys = []string{"key0", "key1", "key2"} + +/// test creation +func TestNewTable(t *testing.T) { + var b bytes.Buffer + tbl := NewJSONTable(&b) + if tbl.NumLines() != 0 { + t.Fatalf("Something went weird when making table (should have 0 lines)") + } +} + +/// test adding things +func TestTableAdd(t *testing.T) { + var b bytes.Buffer + tbl := NewJSONTable(&b) + + tbl.Append(TestLine) + if tbl.NumLines() != 1 { + t.Fatalf("Appending a line does not result in a length of 1.") + } + + tbl.AppendBulk(TestGroup) + numlines := tbl.NumLines() + if numlines != (len(TestGroup) + 1) { + t.Fatalf("Appending two lines does not result in a length of 4 (length is %d).", numlines) + } +} + +/// test JSON output is parsable +func TestJsonParsable(t *testing.T) { + var b bytes.Buffer + tbl := NewJSONTable(&b) + + tbl.AppendBulk(TestGroup) + tbl.SetHeader(TestKeys) + + tbl.JSONRender() + + var son []map[string]interface{} + + err := json.Unmarshal(b.Bytes(), &son) + + if err != nil { + t.Fatalf("Did not produce parsable JSON: %s", err.Error()) + } +} + +/// test identical commands to a tablewriter and jsontable produce the same rendered output +func TestTableWriter(t *testing.T) { + var bjson bytes.Buffer + var btable bytes.Buffer + + tbl := NewJSONTable(&bjson) + + tbl.AppendBulk(TestGroup) + tbl.SetHeader(TestKeys) + tbl.Render() + + wtbl := tablewriter.NewWriter(&btable) + + wtbl.AppendBulk(TestGroup) + wtbl.SetHeader(TestKeys) + wtbl.Render() + + if bytes.Compare(bjson.Bytes(), btable.Bytes()) != 0 { + t.Fatalf("JSON table and TableWriter produce non-identical outputs.\n%s\n%s", bjson.Bytes(), btable.Bytes()) + } +} + + +/// FIXME test different output formats when captions etc. are added