github.com/verygoodsoftwarenotvirus/cartogopher@v0.0.0-20160213112503-f5fe2b6d4bd1/reader_test.go (about) 1 package cartogopher 2 3 import ( 4 "os" 5 "testing" 6 ) 7 8 // Testing creation of the header to index map 9 func TestHeaderMapCreation(t *testing.T) { 10 // open our test file 11 inputCSV, err := os.Open("test_csvs/test.csv") 12 if err != nil { 13 t.Errorf("Error returned while opening file: %v", err) 14 } 15 16 // create our new Cartogopher reader 17 reader, err := NewReader(inputCSV) 18 if err != nil { 19 t.Errorf("Error returned while creating new reader: %v", err) 20 } 21 22 result := reader.HeaderIndexMap 23 expectedResult := map[string]int{ 24 "first": 0, 25 "second": 1, 26 "third": 2, 27 } 28 29 // Test that the value was actually created. 30 if result == nil { 31 t.Error("Test CSV header map returned nil\n", expectedResult) 32 } 33 34 // Test that every value matches up with the expected result. 35 for key, value := range expectedResult { 36 if _, ok := result[key]; !ok { 37 t.Errorf("The following key is not located in the resulting header map: %v\n", key) 38 } else if result[key] != value { 39 t.Errorf("The generated header map has incorrect values for this key: %v\n", key) 40 } 41 } 42 } 43 44 // Testing the entire contents fo a file 45 func TestFileReading(t *testing.T) { 46 // open our test CSV 47 inputCSV, err := os.Open("test_csvs/test.csv") 48 if err != nil { 49 t.Errorf("Error returned while opening file: %v", err) 50 } 51 52 // create our new Cartogopher reader 53 reader, err := NewReader(inputCSV) 54 if err != nil { 55 t.Errorf("Error returned while creating new reader: %v", err) 56 } 57 58 // mapped contents of our demo CSV 59 expectedCSVMapRows := []map[string]string{ 60 { 61 "first": "one", 62 "second": "two", 63 "third": "three", 64 }, 65 { 66 "first": "a", 67 "second": "b", 68 "third": "c", 69 }, 70 { 71 "first": "Athos", 72 "second": "Aramis", 73 "third": "Porthos", 74 }, 75 } 76 77 // read all the lines in the file, as you would do with encoding/csv 78 producedCSVMapRows, err := reader.ReadAll() 79 if err != nil { 80 t.Errorf("Error returned while reading all rows: %v", err) 81 } 82 83 // assert euqality of results with expectations 84 for index, expectedRow := range expectedCSVMapRows { 85 for header, value := range expectedRow { 86 if producedCSVMapRows[index][header] != value { 87 t.Errorf("Mismatch in expected value:\n\t'%v': %v\nvs. produced value: %v", header, value, producedCSVMapRows[index][header]) 88 } 89 } 90 } 91 } 92 93 // Benchmarks for the file path approach. 94 func BenchmarkSmallFileHandling(b *testing.B) { 95 inputCSV, err := os.Open("test_csvs/test.csv") 96 if err != nil { 97 b.Errorf("Error returned while opening file: %v", err) 98 } 99 NewReader(inputCSV) 100 }