How to use NoError method of test Package

Best Go-testdeep code snippet using test.NoError

excelize_test.go

Source:excelize_test.go Github

copy

Full Screen

...20)21func TestOpenFile(t *testing.T) {22 // Test update a XLSX file.23 f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))24 assert.NoError(t, err)25 // Test get all the rows in a not exists worksheet.26 _, err = f.GetRows("Sheet4")27 assert.EqualError(t, err, "sheet Sheet4 is not exist")28 // Test get all the rows in a worksheet.29 rows, err := f.GetRows("Sheet2")30 assert.NoError(t, err)31 for _, row := range rows {32 for _, cell := range row {33 t.Log(cell, "\t")34 }35 t.Log("\r\n")36 }37 assert.NoError(t, f.UpdateLinkedValue())38 assert.NoError(t, f.SetCellDefault("Sheet2", "A1", strconv.FormatFloat(float64(100.1588), 'f', -1, 32)))39 assert.NoError(t, f.SetCellDefault("Sheet2", "A1", strconv.FormatFloat(float64(-100.1588), 'f', -1, 64)))40 // Test set cell value with illegal row number.41 assert.EqualError(t, f.SetCellDefault("Sheet2", "A", strconv.FormatFloat(float64(-100.1588), 'f', -1, 64)),42 `cannot convert cell "A" to coordinates: invalid cell name "A"`)43 assert.NoError(t, f.SetCellInt("Sheet2", "A1", 100))44 // Test set cell integer value with illegal row number.45 assert.EqualError(t, f.SetCellInt("Sheet2", "A", 100), `cannot convert cell "A" to coordinates: invalid cell name "A"`)46 assert.NoError(t, f.SetCellStr("Sheet2", "C11", "Knowns"))47 // Test max characters in a cell.48 assert.NoError(t, f.SetCellStr("Sheet2", "D11", strings.Repeat("c", 32769)))49 f.NewSheet(":\\/?*[]Maximum 31 characters allowed in sheet title.")50 // Test set worksheet name with illegal name.51 f.SetSheetName("Maximum 31 characters allowed i", "[Rename]:\\/?* Maximum 31 characters allowed in sheet title.")52 assert.EqualError(t, f.SetCellInt("Sheet3", "A23", 10), "sheet Sheet3 is not exist")53 assert.EqualError(t, f.SetCellStr("Sheet3", "b230", "10"), "sheet Sheet3 is not exist")54 assert.EqualError(t, f.SetCellStr("Sheet10", "b230", "10"), "sheet Sheet10 is not exist")55 // Test set cell string value with illegal row number.56 assert.EqualError(t, f.SetCellStr("Sheet1", "A", "10"), `cannot convert cell "A" to coordinates: invalid cell name "A"`)57 f.SetActiveSheet(2)58 // Test get cell formula with given rows number.59 _, err = f.GetCellFormula("Sheet1", "B19")60 assert.NoError(t, err)61 // Test get cell formula with illegal worksheet name.62 _, err = f.GetCellFormula("Sheet2", "B20")63 assert.NoError(t, err)64 _, err = f.GetCellFormula("Sheet1", "B20")65 assert.NoError(t, err)66 // Test get cell formula with illegal rows number.67 _, err = f.GetCellFormula("Sheet1", "B")68 assert.EqualError(t, err, `cannot convert cell "B" to coordinates: invalid cell name "B"`)69 // Test get shared cell formula70 _, err = f.GetCellFormula("Sheet2", "H11")71 assert.NoError(t, err)72 _, err = f.GetCellFormula("Sheet2", "I11")73 assert.NoError(t, err)74 getSharedForumula(&xlsxWorksheet{}, "")75 // Test read cell value with given illegal rows number.76 _, err = f.GetCellValue("Sheet2", "a-1")77 assert.EqualError(t, err, `cannot convert cell "A-1" to coordinates: invalid cell name "A-1"`)78 _, err = f.GetCellValue("Sheet2", "A")79 assert.EqualError(t, err, `cannot convert cell "A" to coordinates: invalid cell name "A"`)80 // Test read cell value with given lowercase column number.81 _, err = f.GetCellValue("Sheet2", "a5")82 assert.NoError(t, err)83 _, err = f.GetCellValue("Sheet2", "C11")84 assert.NoError(t, err)85 _, err = f.GetCellValue("Sheet2", "D11")86 assert.NoError(t, err)87 _, err = f.GetCellValue("Sheet2", "D12")88 assert.NoError(t, err)89 // Test SetCellValue function.90 assert.NoError(t, f.SetCellValue("Sheet2", "F1", " Hello"))91 assert.NoError(t, f.SetCellValue("Sheet2", "G1", []byte("World")))92 assert.NoError(t, f.SetCellValue("Sheet2", "F2", 42))93 assert.NoError(t, f.SetCellValue("Sheet2", "F3", int8(1<<8/2-1)))94 assert.NoError(t, f.SetCellValue("Sheet2", "F4", int16(1<<16/2-1)))95 assert.NoError(t, f.SetCellValue("Sheet2", "F5", int32(1<<32/2-1)))96 assert.NoError(t, f.SetCellValue("Sheet2", "F6", int64(1<<32/2-1)))97 assert.NoError(t, f.SetCellValue("Sheet2", "F7", float32(42.65418)))98 assert.NoError(t, f.SetCellValue("Sheet2", "F8", float64(-42.65418)))99 assert.NoError(t, f.SetCellValue("Sheet2", "F9", float32(42)))100 assert.NoError(t, f.SetCellValue("Sheet2", "F10", float64(42)))101 assert.NoError(t, f.SetCellValue("Sheet2", "F11", uint(1<<32-1)))102 assert.NoError(t, f.SetCellValue("Sheet2", "F12", uint8(1<<8-1)))103 assert.NoError(t, f.SetCellValue("Sheet2", "F13", uint16(1<<16-1)))104 assert.NoError(t, f.SetCellValue("Sheet2", "F14", uint32(1<<32-1)))105 assert.NoError(t, f.SetCellValue("Sheet2", "F15", uint64(1<<32-1)))106 assert.NoError(t, f.SetCellValue("Sheet2", "F16", true))107 assert.NoError(t, f.SetCellValue("Sheet2", "F17", complex64(5+10i)))108 // Test on not exists worksheet.109 assert.EqualError(t, f.SetCellDefault("SheetN", "A1", ""), "sheet SheetN is not exist")110 assert.EqualError(t, f.SetCellFloat("SheetN", "A1", 42.65418, 2, 32), "sheet SheetN is not exist")111 assert.EqualError(t, f.SetCellBool("SheetN", "A1", true), "sheet SheetN is not exist")112 assert.EqualError(t, f.SetCellFormula("SheetN", "A1", ""), "sheet SheetN is not exist")113 assert.EqualError(t, f.SetCellHyperLink("SheetN", "A1", "Sheet1!A40", "Location"), "sheet SheetN is not exist")114 // Test boolean write115 booltest := []struct {116 value bool117 expected string118 }{119 {false, "0"},120 {true, "1"},121 }122 for _, test := range booltest {123 assert.NoError(t, f.SetCellValue("Sheet2", "F16", test.value))124 val, err := f.GetCellValue("Sheet2", "F16")125 assert.NoError(t, err)126 assert.Equal(t, test.expected, val)127 }128 assert.NoError(t, f.SetCellValue("Sheet2", "G2", nil))129 assert.EqualError(t, f.SetCellValue("Sheet2", "G4", time.Now()), "only UTC time expected")130 assert.NoError(t, f.SetCellValue("Sheet2", "G4", time.Now().UTC()))131 // 02:46:40132 assert.NoError(t, f.SetCellValue("Sheet2", "G5", time.Duration(1e13)))133 // Test completion column.134 assert.NoError(t, f.SetCellValue("Sheet2", "M2", nil))135 // Test read cell value with given axis large than exists row.136 _, err = f.GetCellValue("Sheet2", "E231")137 assert.NoError(t, err)138 // Test get active worksheet of XLSX and get worksheet name of XLSX by given worksheet index.139 f.GetSheetName(f.GetActiveSheetIndex())140 // Test get worksheet index of XLSX by given worksheet name.141 f.GetSheetIndex("Sheet1")142 // Test get worksheet name of XLSX by given invalid worksheet index.143 f.GetSheetName(4)144 // Test get worksheet map of workbook.145 f.GetSheetMap()146 for i := 1; i <= 300; i++ {147 assert.NoError(t, f.SetCellStr("Sheet2", "c"+strconv.Itoa(i), strconv.Itoa(i)))148 }149 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestOpenFile.xlsx")))150}151func TestSaveFile(t *testing.T) {152 f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))153 if !assert.NoError(t, err) {154 t.FailNow()155 }156 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSaveFile.xlsx")))157 f, err = OpenFile(filepath.Join("test", "TestSaveFile.xlsx"))158 if !assert.NoError(t, err) {159 t.FailNow()160 }161 assert.NoError(t, f.Save())162}163func TestSaveAsWrongPath(t *testing.T) {164 f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))165 if assert.NoError(t, err) {166 // Test write file to not exist directory.167 err = f.SaveAs("")168 if assert.Error(t, err) {169 assert.True(t, os.IsNotExist(err), "Error: %v: Expected os.IsNotExists(err) == true", err)170 }171 }172}173func TestCharsetTranscoder(t *testing.T) {174 f := NewFile()175 f.CharsetTranscoder(*new(charsetTranscoderFn))176}177func TestOpenReader(t *testing.T) {178 _, err := OpenReader(strings.NewReader(""))179 assert.EqualError(t, err, "zip: not a valid zip file")180 _, err = OpenReader(bytes.NewReader([]byte{181 0x3c, 0x00, 0x00, 0x00, 0x4d, 0x00, 0x69, 0x00, 0x63, 0x00, 0x72, 0x00, 0x6f, 0x00, 0x73, 0x00,182 0x6f, 0x00, 0x66, 0x00, 0x74, 0x00, 0x2e, 0x00, 0x43, 0x00, 0x6f, 0x00, 0x6e, 0x00, 0x74, 0x00,183 0x61, 0x00, 0x69, 0x00, 0x6e, 0x00, 0x65, 0x00, 0x72, 0x00, 0x2e, 0x00, 0x44, 0x00, 0x61, 0x00,184 0x74, 0x00, 0x61, 0x00, 0x53, 0x00, 0x70, 0x00, 0x61, 0x00, 0x63, 0x00, 0x65, 0x00, 0x73, 0x00,185 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,186 }))187 assert.EqualError(t, err, "not support encrypted file currently")188 // Test unexpected EOF.189 var b bytes.Buffer190 w := gzip.NewWriter(&b)191 defer w.Close()192 w.Flush()193 r, _ := gzip.NewReader(&b)194 defer r.Close()195 _, err = OpenReader(r)196 assert.EqualError(t, err, "unexpected EOF")197}198func TestBrokenFile(t *testing.T) {199 // Test write file with broken file struct.200 f := File{}201 t.Run("SaveWithoutName", func(t *testing.T) {202 assert.EqualError(t, f.Save(), "no path defined for file, consider File.WriteTo or File.Write")203 })204 t.Run("SaveAsEmptyStruct", func(t *testing.T) {205 // Test write file with broken file struct with given path.206 assert.NoError(t, f.SaveAs(filepath.Join("test", "BrokenFile.SaveAsEmptyStruct.xlsx")))207 })208 t.Run("OpenBadWorkbook", func(t *testing.T) {209 // Test set active sheet without BookViews and Sheets maps in xl/workbook.xml.210 f3, err := OpenFile(filepath.Join("test", "BadWorkbook.xlsx"))211 f3.GetActiveSheetIndex()212 f3.SetActiveSheet(2)213 assert.NoError(t, err)214 })215 t.Run("OpenNotExistsFile", func(t *testing.T) {216 // Test open a XLSX file with given illegal path.217 _, err := OpenFile(filepath.Join("test", "NotExistsFile.xlsx"))218 if assert.Error(t, err) {219 assert.True(t, os.IsNotExist(err), "Expected os.IsNotExists(err) == true")220 }221 })222}223func TestNewFile(t *testing.T) {224 // Test create a XLSX file.225 f := NewFile()226 f.NewSheet("Sheet1")227 f.NewSheet("XLSXSheet2")228 f.NewSheet("XLSXSheet3")229 assert.NoError(t, f.SetCellInt("XLSXSheet2", "A23", 56))230 assert.NoError(t, f.SetCellStr("Sheet1", "B20", "42"))231 f.SetActiveSheet(0)232 // Test add picture to sheet with scaling and positioning.233 err := f.AddPicture("Sheet1", "H2", filepath.Join("test", "images", "excel.gif"),234 `{"x_scale": 0.5, "y_scale": 0.5, "positioning": "absolute"}`)235 if !assert.NoError(t, err) {236 t.FailNow()237 }238 // Test add picture to worksheet without formatset.239 err = f.AddPicture("Sheet1", "C2", filepath.Join("test", "images", "excel.png"), "")240 if !assert.NoError(t, err) {241 t.FailNow()242 }243 // Test add picture to worksheet with invalid formatset.244 err = f.AddPicture("Sheet1", "C2", filepath.Join("test", "images", "excel.png"), `{`)245 if !assert.Error(t, err) {246 t.FailNow()247 }248 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestNewFile.xlsx")))249}250func TestAddDrawingVML(t *testing.T) {251 // Test addDrawingVML with illegal cell coordinates.252 f := NewFile()253 assert.EqualError(t, f.addDrawingVML(0, "", "*", 0, 0), `cannot convert cell "*" to coordinates: invalid cell name "*"`)254}255func TestSetCellHyperLink(t *testing.T) {256 f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))257 if err != nil {258 t.Log(err)259 }260 // Test set cell hyperlink in a work sheet already have hyperlinks.261 assert.NoError(t, f.SetCellHyperLink("Sheet1", "B19", "https://github.com/360EntSecGroup-Skylar/excelize", "External"))262 // Test add first hyperlink in a work sheet.263 assert.NoError(t, f.SetCellHyperLink("Sheet2", "C1", "https://github.com/360EntSecGroup-Skylar/excelize", "External"))264 // Test add Location hyperlink in a work sheet.265 assert.NoError(t, f.SetCellHyperLink("Sheet2", "D6", "Sheet1!D8", "Location"))266 assert.EqualError(t, f.SetCellHyperLink("Sheet2", "C3", "Sheet1!D8", ""), `invalid link type ""`)267 assert.EqualError(t, f.SetCellHyperLink("Sheet2", "", "Sheet1!D60", "Location"), `invalid cell name ""`)268 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellHyperLink.xlsx")))269 f = NewFile()270 _, err = f.workSheetReader("Sheet1")271 assert.NoError(t, err)272 f.Sheet["xl/worksheets/sheet1.xml"].Hyperlinks = &xlsxHyperlinks{Hyperlink: make([]xlsxHyperlink, 65530)}273 assert.EqualError(t, f.SetCellHyperLink("Sheet1", "A65531", "https://github.com/360EntSecGroup-Skylar/excelize", "External"), "over maximum limit hyperlinks in a worksheet")274 f = NewFile()275 _, err = f.workSheetReader("Sheet1")276 assert.NoError(t, err)277 f.Sheet["xl/worksheets/sheet1.xml"].MergeCells = &xlsxMergeCells{Cells: []*xlsxMergeCell{{Ref: "A:A"}}}278 err = f.SetCellHyperLink("Sheet1", "A1", "https://github.com/360EntSecGroup-Skylar/excelize", "External")279 assert.EqualError(t, err, `cannot convert cell "A" to coordinates: invalid cell name "A"`)280}281func TestGetCellHyperLink(t *testing.T) {282 f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))283 if !assert.NoError(t, err) {284 t.FailNow()285 }286 _, _, err = f.GetCellHyperLink("Sheet1", "")287 assert.EqualError(t, err, `invalid cell name ""`)288 link, target, err := f.GetCellHyperLink("Sheet1", "A22")289 assert.NoError(t, err)290 t.Log(link, target)291 link, target, err = f.GetCellHyperLink("Sheet2", "D6")292 assert.NoError(t, err)293 t.Log(link, target)294 link, target, err = f.GetCellHyperLink("Sheet3", "H3")295 assert.EqualError(t, err, "sheet Sheet3 is not exist")296 t.Log(link, target)297 f = NewFile()298 _, err = f.workSheetReader("Sheet1")299 assert.NoError(t, err)300 f.Sheet["xl/worksheets/sheet1.xml"].Hyperlinks = &xlsxHyperlinks{301 Hyperlink: []xlsxHyperlink{{Ref: "A1"}},302 }303 link, target, err = f.GetCellHyperLink("Sheet1", "A1")304 assert.NoError(t, err)305 assert.Equal(t, link, true)306 assert.Equal(t, target, "")307 f.Sheet["xl/worksheets/sheet1.xml"].MergeCells = &xlsxMergeCells{Cells: []*xlsxMergeCell{{Ref: "A:A"}}}308 link, target, err = f.GetCellHyperLink("Sheet1", "A1")309 assert.EqualError(t, err, `cannot convert cell "A" to coordinates: invalid cell name "A"`)310 assert.Equal(t, link, false)311 assert.Equal(t, target, "")312}313func TestSetCellFormula(t *testing.T) {314 f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))315 if !assert.NoError(t, err) {316 t.FailNow()317 }318 assert.NoError(t, f.SetCellFormula("Sheet1", "B19", "SUM(Sheet2!D2,Sheet2!D11)"))319 assert.NoError(t, f.SetCellFormula("Sheet1", "C19", "SUM(Sheet2!D2,Sheet2!D9)"))320 // Test set cell formula with illegal rows number.321 assert.EqualError(t, f.SetCellFormula("Sheet1", "C", "SUM(Sheet2!D2,Sheet2!D9)"), `cannot convert cell "C" to coordinates: invalid cell name "C"`)322 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellFormula1.xlsx")))323 f, err = OpenFile(filepath.Join("test", "CalcChain.xlsx"))324 if !assert.NoError(t, err) {325 t.FailNow()326 }327 // Test remove cell formula.328 assert.NoError(t, f.SetCellFormula("Sheet1", "A1", ""))329 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellFormula2.xlsx")))330 // Test remove all cell formula.331 assert.NoError(t, f.SetCellFormula("Sheet1", "B1", ""))332 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellFormula3.xlsx")))333}334func TestSetSheetBackground(t *testing.T) {335 f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))336 if !assert.NoError(t, err) {337 t.FailNow()338 }339 err = f.SetSheetBackground("Sheet2", filepath.Join("test", "images", "background.jpg"))340 if !assert.NoError(t, err) {341 t.FailNow()342 }343 err = f.SetSheetBackground("Sheet2", filepath.Join("test", "images", "background.jpg"))344 if !assert.NoError(t, err) {345 t.FailNow()346 }347 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetSheetBackground.xlsx")))348}349func TestSetSheetBackgroundErrors(t *testing.T) {350 f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))351 if !assert.NoError(t, err) {352 t.FailNow()353 }354 err = f.SetSheetBackground("Sheet2", filepath.Join("test", "not_exists", "not_exists.png"))355 if assert.Error(t, err) {356 assert.True(t, os.IsNotExist(err), "Expected os.IsNotExists(err) == true")357 }358 err = f.SetSheetBackground("Sheet2", filepath.Join("test", "Book1.xlsx"))359 assert.EqualError(t, err, "unsupported image extension")360}361// TestWriteArrayFormula tests the extended options of SetCellFormula by writing an array function362// to a workbook. In the resulting file, the lines 2 and 3 as well as 4 and 5 should have matching363// contents.364func TestWriteArrayFormula(t *testing.T) {365 cell := func(col, row int) string {366 c, err := CoordinatesToCellName(col, row)367 if err != nil {368 t.Fatal(err)369 }370 return c371 }372 f := NewFile()373 sample := []string{"Sample 1", "Sample 2", "Sample 3"}374 values := []int{1855, 1709, 1462, 1115, 1524, 625, 773, 126, 1027, 1696, 1078, 1917, 1109, 1753, 1884, 659, 994, 1911, 1925, 899, 196, 244, 1488, 1056, 1986, 66, 784, 725, 767, 1722, 1541, 1026, 1455, 264, 1538, 877, 1581, 1098, 383, 762, 237, 493, 29, 1923, 474, 430, 585, 688, 308, 200, 1259, 622, 798, 1048, 996, 601, 582, 332, 377, 805, 250, 1860, 1360, 840, 911, 1346, 1651, 1651, 665, 584, 1057, 1145, 925, 1752, 202, 149, 1917, 1398, 1894, 818, 714, 624, 1085, 1566, 635, 78, 313, 1686, 1820, 494, 614, 1913, 271, 1016, 338, 1301, 489, 1733, 1483, 1141}375 assoc := []int{2, 0, 0, 0, 0, 1, 1, 0, 0, 1, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 2, 0, 2, 1, 2, 2, 2, 1, 0, 1, 0, 1, 1, 2, 0, 2, 1, 0, 2, 1, 0, 1, 0, 0, 2, 0, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 1, 2, 2, 1, 1, 1, 0, 1, 0, 2, 0, 0, 1, 2, 1, 0, 1, 0, 0, 2, 1, 1, 2, 0, 2, 1, 0, 2, 2, 2, 1, 0, 0, 1, 1, 1, 2, 0, 2, 0, 1, 1}376 if len(values) != len(assoc) {377 t.Fatal("values and assoc must be of same length")378 }379 // Average calculates the average of the n-th sample (0 <= n < len(sample)).380 average := func(n int) int {381 sum := 0382 count := 0383 for i := 0; i != len(values); i++ {384 if assoc[i] == n {385 sum += values[i]386 count++387 }388 }389 return int(math.Round(float64(sum) / float64(count)))390 }391 // Stdev calculates the standard deviation of the n-th sample (0 <= n < len(sample)).392 stdev := func(n int) int {393 avg := average(n)394 sum := 0395 count := 0396 for i := 0; i != len(values); i++ {397 if assoc[i] == n {398 sum += (values[i] - avg) * (values[i] - avg)399 count++400 }401 }402 return int(math.Round(math.Sqrt(float64(sum) / float64(count))))403 }404 // Line 2 contains the results of AVERAGEIF405 assert.NoError(t, f.SetCellStr("Sheet1", "A2", "Average"))406 // Line 3 contains the average that was calculated in Go407 assert.NoError(t, f.SetCellStr("Sheet1", "A3", "Average (calculated)"))408 // Line 4 contains the results of the array function that calculates the standard deviation409 assert.NoError(t, f.SetCellStr("Sheet1", "A4", "Std. deviation"))410 // Line 5 contains the standard deviations calculated in Go411 assert.NoError(t, f.SetCellStr("Sheet1", "A5", "Std. deviation (calculated)"))412 assert.NoError(t, f.SetCellStr("Sheet1", "B1", sample[0]))413 assert.NoError(t, f.SetCellStr("Sheet1", "C1", sample[1]))414 assert.NoError(t, f.SetCellStr("Sheet1", "D1", sample[2]))415 firstResLine := 8416 assert.NoError(t, f.SetCellStr("Sheet1", cell(1, firstResLine-1), "Result Values"))417 assert.NoError(t, f.SetCellStr("Sheet1", cell(2, firstResLine-1), "Sample"))418 for i := 0; i != len(values); i++ {419 valCell := cell(1, i+firstResLine)420 assocCell := cell(2, i+firstResLine)421 assert.NoError(t, f.SetCellInt("Sheet1", valCell, values[i]))422 assert.NoError(t, f.SetCellStr("Sheet1", assocCell, sample[assoc[i]]))423 }424 valRange := fmt.Sprintf("$A$%d:$A$%d", firstResLine, len(values)+firstResLine-1)425 assocRange := fmt.Sprintf("$B$%d:$B$%d", firstResLine, len(values)+firstResLine-1)426 for i := 0; i != len(sample); i++ {427 nameCell := cell(i+2, 1)428 avgCell := cell(i+2, 2)429 calcAvgCell := cell(i+2, 3)430 stdevCell := cell(i+2, 4)431 calcStdevCell := cell(i+2, 5)432 assert.NoError(t, f.SetCellInt("Sheet1", calcAvgCell, average(i)))433 assert.NoError(t, f.SetCellInt("Sheet1", calcStdevCell, stdev(i)))434 // Average can be done with AVERAGEIF435 assert.NoError(t, f.SetCellFormula("Sheet1", avgCell, fmt.Sprintf("ROUND(AVERAGEIF(%s,%s,%s),0)", assocRange, nameCell, valRange)))436 ref := stdevCell + ":" + stdevCell437 t := STCellFormulaTypeArray438 // Use an array formula for standard deviation439 f.SetCellFormula("Sheet1", stdevCell, fmt.Sprintf("ROUND(STDEVP(IF(%s=%s,%s)),0)", assocRange, nameCell, valRange),440 FormulaOpts{}, FormulaOpts{Type: &t}, FormulaOpts{Ref: &ref})441 }442 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestWriteArrayFormula.xlsx")))443}444func TestSetCellStyleAlignment(t *testing.T) {445 f, err := prepareTestBook1()446 if !assert.NoError(t, err) {447 t.FailNow()448 }449 var style int450 style, err = f.NewStyle(`{"alignment":{"horizontal":"center","ident":1,"justify_last_line":true,"reading_order":0,"relative_indent":1,"shrink_to_fit":true,"text_rotation":45,"vertical":"top","wrap_text":true}}`)451 if !assert.NoError(t, err) {452 t.FailNow()453 }454 assert.NoError(t, f.SetCellStyle("Sheet1", "A22", "A22", style))455 // Test set cell style with given illegal rows number.456 assert.EqualError(t, f.SetCellStyle("Sheet1", "A", "A22", style), `cannot convert cell "A" to coordinates: invalid cell name "A"`)457 assert.EqualError(t, f.SetCellStyle("Sheet1", "A22", "A", style), `cannot convert cell "A" to coordinates: invalid cell name "A"`)458 // Test get cell style with given illegal rows number.459 index, err := f.GetCellStyle("Sheet1", "A")460 assert.Equal(t, 0, index)461 assert.EqualError(t, err, `cannot convert cell "A" to coordinates: invalid cell name "A"`)462 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleAlignment.xlsx")))463}464func TestSetCellStyleBorder(t *testing.T) {465 f, err := prepareTestBook1()466 if !assert.NoError(t, err) {467 t.FailNow()468 }469 var style int470 // Test set border on overlapping area with vertical variants shading styles gradient fill.471 style, err = f.NewStyle(`{"border":[{"type":"left","color":"0000FF","style":2},{"type":"top","color":"00FF00","style":12},{"type":"bottom","color":"FFFF00","style":5},{"type":"right","color":"FF0000","style":6},{"type":"diagonalDown","color":"A020F0","style":9},{"type":"diagonalUp","color":"A020F0","style":8}]}`)472 if !assert.NoError(t, err) {473 t.FailNow()474 }475 assert.NoError(t, f.SetCellStyle("Sheet1", "J21", "L25", style))476 style, err = f.NewStyle(`{"border":[{"type":"left","color":"0000FF","style":2},{"type":"top","color":"00FF00","style":3},{"type":"bottom","color":"FFFF00","style":4},{"type":"right","color":"FF0000","style":5},{"type":"diagonalDown","color":"A020F0","style":6},{"type":"diagonalUp","color":"A020F0","style":7}],"fill":{"type":"gradient","color":["#FFFFFF","#E0EBF5"],"shading":1}}`)477 if !assert.NoError(t, err) {478 t.FailNow()479 }480 assert.NoError(t, f.SetCellStyle("Sheet1", "M28", "K24", style))481 style, err = f.NewStyle(`{"border":[{"type":"left","color":"0000FF","style":2},{"type":"top","color":"00FF00","style":3},{"type":"bottom","color":"FFFF00","style":4},{"type":"right","color":"FF0000","style":5},{"type":"diagonalDown","color":"A020F0","style":6},{"type":"diagonalUp","color":"A020F0","style":7}],"fill":{"type":"gradient","color":["#FFFFFF","#E0EBF5"],"shading":4}}`)482 if !assert.NoError(t, err) {483 t.FailNow()484 }485 assert.NoError(t, f.SetCellStyle("Sheet1", "M28", "K24", style))486 // Test set border and solid style pattern fill for a single cell.487 style, err = f.NewStyle(&Style{488 Border: []Border{489 {490 Type: "left",491 Color: "0000FF",492 Style: 8,493 },494 {495 Type: "top",496 Color: "00FF00",497 Style: 9,498 },499 {500 Type: "bottom",501 Color: "FFFF00",502 Style: 10,503 },504 {505 Type: "right",506 Color: "FF0000",507 Style: 11,508 },509 {510 Type: "diagonalDown",511 Color: "A020F0",512 Style: 12,513 },514 {515 Type: "diagonalUp",516 Color: "A020F0",517 Style: 13,518 },519 },520 Fill: Fill{521 Type: "pattern",522 Color: []string{"#E0EBF5"},523 Pattern: 1,524 },525 })526 if !assert.NoError(t, err) {527 t.FailNow()528 }529 assert.NoError(t, f.SetCellStyle("Sheet1", "O22", "O22", style))530 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleBorder.xlsx")))531}532func TestSetCellStyleBorderErrors(t *testing.T) {533 f, err := prepareTestBook1()534 if !assert.NoError(t, err) {535 t.FailNow()536 }537 // Set border with invalid style parameter.538 _, err = f.NewStyle("")539 if !assert.EqualError(t, err, "unexpected end of JSON input") {540 t.FailNow()541 }542 // Set border with invalid style index number.543 _, err = f.NewStyle(`{"border":[{"type":"left","color":"0000FF","style":-1},{"type":"top","color":"00FF00","style":14},{"type":"bottom","color":"FFFF00","style":5},{"type":"right","color":"FF0000","style":6},{"type":"diagonalDown","color":"A020F0","style":9},{"type":"diagonalUp","color":"A020F0","style":8}]}`)544 if !assert.NoError(t, err) {545 t.FailNow()546 }547}548func TestSetCellStyleNumberFormat(t *testing.T) {549 f, err := prepareTestBook1()550 if !assert.NoError(t, err) {551 t.FailNow()552 }553 // Test only set fill and number format for a cell.554 col := []string{"L", "M", "N", "O", "P"}555 data := []int{0, 1, 2, 3, 4, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49}556 value := []string{"37947.7500001", "-37947.7500001", "0.007", "2.1", "String"}557 for i, v := range value {558 for k, d := range data {559 c := col[i] + strconv.Itoa(k+1)560 var val float64561 val, err = strconv.ParseFloat(v, 64)562 if err != nil {563 assert.NoError(t, f.SetCellValue("Sheet2", c, v))564 } else {565 assert.NoError(t, f.SetCellValue("Sheet2", c, val))566 }567 style, err := f.NewStyle(`{"fill":{"type":"gradient","color":["#FFFFFF","#E0EBF5"],"shading":5},"number_format": ` + strconv.Itoa(d) + `}`)568 if !assert.NoError(t, err) {569 t.FailNow()570 }571 assert.NoError(t, f.SetCellStyle("Sheet2", c, c, style))572 t.Log(f.GetCellValue("Sheet2", c))573 }574 }575 var style int576 style, err = f.NewStyle(`{"number_format":-1}`)577 if !assert.NoError(t, err) {578 t.FailNow()579 }580 assert.NoError(t, f.SetCellStyle("Sheet2", "L33", "L33", style))581 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleNumberFormat.xlsx")))582}583func TestSetCellStyleCurrencyNumberFormat(t *testing.T) {584 t.Run("TestBook3", func(t *testing.T) {585 f, err := prepareTestBook3()586 if !assert.NoError(t, err) {587 t.FailNow()588 }589 assert.NoError(t, f.SetCellValue("Sheet1", "A1", 56))590 assert.NoError(t, f.SetCellValue("Sheet1", "A2", -32.3))591 var style int592 style, err = f.NewStyle(`{"number_format": 188, "decimal_places": -1}`)593 if !assert.NoError(t, err) {594 t.FailNow()595 }596 assert.NoError(t, f.SetCellStyle("Sheet1", "A1", "A1", style))597 style, err = f.NewStyle(`{"number_format": 188, "decimal_places": 31, "negred": true}`)598 if !assert.NoError(t, err) {599 t.FailNow()600 }601 assert.NoError(t, f.SetCellStyle("Sheet1", "A2", "A2", style))602 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleCurrencyNumberFormat.TestBook3.xlsx")))603 })604 t.Run("TestBook4", func(t *testing.T) {605 f, err := prepareTestBook4()606 if !assert.NoError(t, err) {607 t.FailNow()608 }609 assert.NoError(t, f.SetCellValue("Sheet1", "A1", 42920.5))610 assert.NoError(t, f.SetCellValue("Sheet1", "A2", 42920.5))611 _, err = f.NewStyle(`{"number_format": 26, "lang": "zh-tw"}`)612 if !assert.NoError(t, err) {613 t.FailNow()614 }615 style, err := f.NewStyle(`{"number_format": 27}`)616 if !assert.NoError(t, err) {617 t.FailNow()618 }619 assert.NoError(t, f.SetCellStyle("Sheet1", "A1", "A1", style))620 style, err = f.NewStyle(`{"number_format": 31, "lang": "ko-kr"}`)621 if !assert.NoError(t, err) {622 t.FailNow()623 }624 assert.NoError(t, f.SetCellStyle("Sheet1", "A2", "A2", style))625 style, err = f.NewStyle(`{"number_format": 71, "lang": "th-th"}`)626 if !assert.NoError(t, err) {627 t.FailNow()628 }629 assert.NoError(t, f.SetCellStyle("Sheet1", "A2", "A2", style))630 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleCurrencyNumberFormat.TestBook4.xlsx")))631 })632}633func TestSetCellStyleCustomNumberFormat(t *testing.T) {634 f := NewFile()635 assert.NoError(t, f.SetCellValue("Sheet1", "A1", 42920.5))636 assert.NoError(t, f.SetCellValue("Sheet1", "A2", 42920.5))637 style, err := f.NewStyle(`{"custom_number_format": "[$-380A]dddd\\,\\ dd\" de \"mmmm\" de \"yyyy;@"}`)638 if err != nil {639 t.Log(err)640 }641 assert.NoError(t, f.SetCellStyle("Sheet1", "A1", "A1", style))642 style, err = f.NewStyle(`{"custom_number_format": "[$-380A]dddd\\,\\ dd\" de \"mmmm\" de \"yyyy;@"}`)643 if err != nil {644 t.Log(err)645 }646 assert.NoError(t, f.SetCellStyle("Sheet1", "A2", "A2", style))647 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleCustomNumberFormat.xlsx")))648}649func TestSetCellStyleFill(t *testing.T) {650 f, err := prepareTestBook1()651 if !assert.NoError(t, err) {652 t.FailNow()653 }654 var style int655 // Test set fill for cell with invalid parameter.656 style, err = f.NewStyle(`{"fill":{"type":"gradient","color":["#FFFFFF","#E0EBF5"],"shading":6}}`)657 if !assert.NoError(t, err) {658 t.FailNow()659 }660 assert.NoError(t, f.SetCellStyle("Sheet1", "O23", "O23", style))661 style, err = f.NewStyle(`{"fill":{"type":"gradient","color":["#FFFFFF"],"shading":1}}`)662 if !assert.NoError(t, err) {663 t.FailNow()664 }665 assert.NoError(t, f.SetCellStyle("Sheet1", "O23", "O23", style))666 style, err = f.NewStyle(`{"fill":{"type":"pattern","color":[],"pattern":1}}`)667 if !assert.NoError(t, err) {668 t.FailNow()669 }670 assert.NoError(t, f.SetCellStyle("Sheet1", "O23", "O23", style))671 style, err = f.NewStyle(`{"fill":{"type":"pattern","color":["#E0EBF5"],"pattern":19}}`)672 if !assert.NoError(t, err) {673 t.FailNow()674 }675 assert.NoError(t, f.SetCellStyle("Sheet1", "O23", "O23", style))676 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleFill.xlsx")))677}678func TestSetCellStyleFont(t *testing.T) {679 f, err := prepareTestBook1()680 if !assert.NoError(t, err) {681 t.FailNow()682 }683 var style int684 style, err = f.NewStyle(`{"font":{"bold":true,"italic":true,"family":"Times New Roman","size":36,"color":"#777777","underline":"single"}}`)685 if !assert.NoError(t, err) {686 t.FailNow()687 }688 assert.NoError(t, f.SetCellStyle("Sheet2", "A1", "A1", style))689 style, err = f.NewStyle(`{"font":{"italic":true,"underline":"double"}}`)690 if !assert.NoError(t, err) {691 t.FailNow()692 }693 assert.NoError(t, f.SetCellStyle("Sheet2", "A2", "A2", style))694 style, err = f.NewStyle(`{"font":{"bold":true}}`)695 if !assert.NoError(t, err) {696 t.FailNow()697 }698 assert.NoError(t, f.SetCellStyle("Sheet2", "A3", "A3", style))699 style, err = f.NewStyle(`{"font":{"bold":true,"family":"","size":0,"color":"","underline":""}}`)700 if !assert.NoError(t, err) {701 t.FailNow()702 }703 assert.NoError(t, f.SetCellStyle("Sheet2", "A4", "A4", style))704 style, err = f.NewStyle(`{"font":{"color":"#777777","strike":true}}`)705 if !assert.NoError(t, err) {706 t.FailNow()707 }708 assert.NoError(t, f.SetCellStyle("Sheet2", "A5", "A5", style))709 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleFont.xlsx")))710}711func TestSetCellStyleProtection(t *testing.T) {712 f, err := prepareTestBook1()713 if !assert.NoError(t, err) {714 t.FailNow()715 }716 var style int717 style, err = f.NewStyle(`{"protection":{"hidden":true, "locked":true}}`)718 if !assert.NoError(t, err) {719 t.FailNow()720 }721 assert.NoError(t, f.SetCellStyle("Sheet2", "A6", "A6", style))722 err = f.SaveAs(filepath.Join("test", "TestSetCellStyleProtection.xlsx"))723 if !assert.NoError(t, err) {724 t.FailNow()725 }726}727func TestSetDeleteSheet(t *testing.T) {728 t.Run("TestBook3", func(t *testing.T) {729 f, err := prepareTestBook3()730 if !assert.NoError(t, err) {731 t.FailNow()732 }733 f.DeleteSheet("XLSXSheet3")734 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetDeleteSheet.TestBook3.xlsx")))735 })736 t.Run("TestBook4", func(t *testing.T) {737 f, err := prepareTestBook4()738 if !assert.NoError(t, err) {739 t.FailNow()740 }741 f.DeleteSheet("Sheet1")742 assert.EqualError(t, f.AddComment("Sheet1", "A1", ""), "unexpected end of JSON input")743 assert.NoError(t, f.AddComment("Sheet1", "A1", `{"author":"Excelize: ","text":"This is a comment."}`))744 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetDeleteSheet.TestBook4.xlsx")))745 })746}747func TestSheetVisibility(t *testing.T) {748 f, err := prepareTestBook1()749 if !assert.NoError(t, err) {750 t.FailNow()751 }752 assert.NoError(t, f.SetSheetVisible("Sheet2", false))753 assert.NoError(t, f.SetSheetVisible("Sheet1", false))754 assert.NoError(t, f.SetSheetVisible("Sheet1", true))755 assert.Equal(t, true, f.GetSheetVisible("Sheet1"))756 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSheetVisibility.xlsx")))757}758func TestCopySheet(t *testing.T) {759 f, err := prepareTestBook1()760 if !assert.NoError(t, err) {761 t.FailNow()762 }763 idx := f.NewSheet("CopySheet")764 assert.NoError(t, f.CopySheet(1, idx))765 assert.NoError(t, f.SetCellValue("CopySheet", "F1", "Hello"))766 val, err := f.GetCellValue("Sheet1", "F1")767 assert.NoError(t, err)768 assert.NotEqual(t, "Hello", val)769 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestCopySheet.xlsx")))770}771func TestCopySheetError(t *testing.T) {772 f, err := prepareTestBook1()773 if !assert.NoError(t, err) {774 t.FailNow()775 }776 assert.EqualError(t, f.copySheet(0, -1), "sheet is not exist")777 if !assert.EqualError(t, f.CopySheet(0, -1), "invalid worksheet index") {778 t.FailNow()779 }780 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestCopySheetError.xlsx")))781}782func TestGetSheetComments(t *testing.T) {783 f := NewFile()784 assert.Equal(t, "", f.getSheetComments("sheet0"))785}786func TestSetActiveSheet(t *testing.T) {787 f := NewFile()788 f.WorkBook.BookViews = nil789 f.SetActiveSheet(1)790 f.WorkBook.BookViews = &xlsxBookViews{WorkBookView: []xlsxWorkBookView{}}791 f.Sheet["xl/worksheets/sheet1.xml"].SheetViews = &xlsxSheetViews{SheetView: []xlsxSheetView{}}792 f.SetActiveSheet(1)793 f.Sheet["xl/worksheets/sheet1.xml"].SheetViews = nil794 f.SetActiveSheet(1)795}796func TestSetSheetVisible(t *testing.T) {797 f := NewFile()798 f.WorkBook.Sheets.Sheet[0].Name = "SheetN"799 assert.EqualError(t, f.SetSheetVisible("Sheet1", false), "sheet SheetN is not exist")800}801func TestGetActiveSheetIndex(t *testing.T) {802 f := NewFile()803 f.WorkBook.BookViews = nil804 assert.Equal(t, 1, f.GetActiveSheetIndex())805}806func TestRelsWriter(t *testing.T) {807 f := NewFile()808 f.Relationships["xl/worksheets/sheet/rels/sheet1.xml.rel"] = &xlsxRelationships{}809 f.relsWriter()810}811func TestGetSheetView(t *testing.T) {812 f := NewFile()813 _, err := f.getSheetView("SheetN", 0)814 assert.EqualError(t, err, "sheet SheetN is not exist")815}816func TestConditionalFormat(t *testing.T) {817 f := NewFile()818 sheet1 := f.GetSheetName(1)819 fillCells(f, sheet1, 10, 15)820 var format1, format2, format3, format4 int821 var err error822 // Rose format for bad conditional.823 format1, err = f.NewConditionalStyle(`{"font":{"color":"#9A0511"},"fill":{"type":"pattern","color":["#FEC7CE"],"pattern":1}}`)824 if !assert.NoError(t, err) {825 t.FailNow()826 }827 // Light yellow format for neutral conditional.828 format2, err = f.NewConditionalStyle(`{"fill":{"type":"pattern","color":["#FEEAA0"],"pattern":1}}`)829 if !assert.NoError(t, err) {830 t.FailNow()831 }832 // Light green format for good conditional.833 format3, err = f.NewConditionalStyle(`{"font":{"color":"#09600B"},"fill":{"type":"pattern","color":["#C7EECF"],"pattern":1}}`)834 if !assert.NoError(t, err) {835 t.FailNow()836 }837 // conditional style with align and left border.838 format4, err = f.NewConditionalStyle(`{"alignment":{"wrap_text":true},"border":[{"type":"left","color":"#000000","style":1}]}`)839 if !assert.NoError(t, err) {840 t.FailNow()841 }842 // Color scales: 2 color.843 assert.NoError(t, f.SetConditionalFormat(sheet1, "A1:A10", `[{"type":"2_color_scale","criteria":"=","min_type":"min","max_type":"max","min_color":"#F8696B","max_color":"#63BE7B"}]`))844 // Color scales: 3 color.845 assert.NoError(t, f.SetConditionalFormat(sheet1, "B1:B10", `[{"type":"3_color_scale","criteria":"=","min_type":"min","mid_type":"percentile","max_type":"max","min_color":"#F8696B","mid_color":"#FFEB84","max_color":"#63BE7B"}]`))846 // Hightlight cells rules: between...847 assert.NoError(t, f.SetConditionalFormat(sheet1, "C1:C10", fmt.Sprintf(`[{"type":"cell","criteria":"between","format":%d,"minimum":"6","maximum":"8"}]`, format1)))848 // Hightlight cells rules: Greater Than...849 assert.NoError(t, f.SetConditionalFormat(sheet1, "D1:D10", fmt.Sprintf(`[{"type":"cell","criteria":">","format":%d,"value":"6"}]`, format3)))850 // Hightlight cells rules: Equal To...851 assert.NoError(t, f.SetConditionalFormat(sheet1, "E1:E10", fmt.Sprintf(`[{"type":"top","criteria":"=","format":%d}]`, format3)))852 // Hightlight cells rules: Not Equal To...853 assert.NoError(t, f.SetConditionalFormat(sheet1, "F1:F10", fmt.Sprintf(`[{"type":"unique","criteria":"=","format":%d}]`, format2)))854 // Hightlight cells rules: Duplicate Values...855 assert.NoError(t, f.SetConditionalFormat(sheet1, "G1:G10", fmt.Sprintf(`[{"type":"duplicate","criteria":"=","format":%d}]`, format2)))856 // Top/Bottom rules: Top 10%.857 assert.NoError(t, f.SetConditionalFormat(sheet1, "H1:H10", fmt.Sprintf(`[{"type":"top","criteria":"=","format":%d,"value":"6","percent":true}]`, format1)))858 // Top/Bottom rules: Above Average...859 assert.NoError(t, f.SetConditionalFormat(sheet1, "I1:I10", fmt.Sprintf(`[{"type":"average","criteria":"=","format":%d, "above_average": true}]`, format3)))860 // Top/Bottom rules: Below Average...861 assert.NoError(t, f.SetConditionalFormat(sheet1, "J1:J10", fmt.Sprintf(`[{"type":"average","criteria":"=","format":%d, "above_average": false}]`, format1)))862 // Data Bars: Gradient Fill.863 assert.NoError(t, f.SetConditionalFormat(sheet1, "K1:K10", `[{"type":"data_bar", "criteria":"=", "min_type":"min","max_type":"max","bar_color":"#638EC6"}]`))864 // Use a formula to determine which cells to format.865 assert.NoError(t, f.SetConditionalFormat(sheet1, "L1:L10", fmt.Sprintf(`[{"type":"formula", "criteria":"L2<3", "format":%d}]`, format1)))866 // Alignment/Border cells rules.867 assert.NoError(t, f.SetConditionalFormat(sheet1, "M1:M10", fmt.Sprintf(`[{"type":"cell","criteria":">","format":%d,"value":"0"}]`, format4)))868 // Test set invalid format set in conditional format.869 assert.EqualError(t, f.SetConditionalFormat(sheet1, "L1:L10", ""), "unexpected end of JSON input")870 // Set conditional format on not exists worksheet.871 assert.EqualError(t, f.SetConditionalFormat("SheetN", "L1:L10", "[]"), "sheet SheetN is not exist")872 err = f.SaveAs(filepath.Join("test", "TestConditionalFormat.xlsx"))873 if !assert.NoError(t, err) {874 t.FailNow()875 }876 // Set conditional format with illegal valid type.877 assert.NoError(t, f.SetConditionalFormat(sheet1, "K1:K10", `[{"type":"", "criteria":"=", "min_type":"min","max_type":"max","bar_color":"#638EC6"}]`))878 // Set conditional format with illegal criteria type.879 assert.NoError(t, f.SetConditionalFormat(sheet1, "K1:K10", `[{"type":"data_bar", "criteria":"", "min_type":"min","max_type":"max","bar_color":"#638EC6"}]`))880 // Set conditional format with file without dxfs element shold not return error.881 f, err = OpenFile(filepath.Join("test", "Book1.xlsx"))882 if !assert.NoError(t, err) {883 t.FailNow()884 }885 _, err = f.NewConditionalStyle(`{"font":{"color":"#9A0511"},"fill":{"type":"pattern","color":["#FEC7CE"],"pattern":1}}`)886 if !assert.NoError(t, err) {887 t.FailNow()888 }889}890func TestConditionalFormatError(t *testing.T) {891 f := NewFile()892 sheet1 := f.GetSheetName(1)893 fillCells(f, sheet1, 10, 15)894 // Set conditional format with illegal JSON string should return error.895 _, err := f.NewConditionalStyle("")896 if !assert.EqualError(t, err, "unexpected end of JSON input") {897 t.FailNow()898 }899}900func TestSharedStrings(t *testing.T) {901 f, err := OpenFile(filepath.Join("test", "SharedStrings.xlsx"))902 if !assert.NoError(t, err) {903 t.FailNow()904 }905 rows, err := f.GetRows("Sheet1")906 if !assert.NoError(t, err) {907 t.FailNow()908 }909 assert.Equal(t, "A", rows[0][0])910 rows, err = f.GetRows("Sheet2")911 if !assert.NoError(t, err) {912 t.FailNow()913 }914 assert.Equal(t, "Test Weight (Kgs)", rows[0][0])915}916func TestSetSheetRow(t *testing.T) {917 f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))918 if !assert.NoError(t, err) {919 t.FailNow()920 }921 assert.NoError(t, f.SetSheetRow("Sheet1", "B27", &[]interface{}{"cell", nil, int32(42), float64(42), time.Now().UTC()}))922 assert.EqualError(t, f.SetSheetRow("Sheet1", "", &[]interface{}{"cell", nil, 2}),923 `cannot convert cell "" to coordinates: invalid cell name ""`)924 assert.EqualError(t, f.SetSheetRow("Sheet1", "B27", []interface{}{}), `pointer to slice expected`)925 assert.EqualError(t, f.SetSheetRow("Sheet1", "B27", &f), `pointer to slice expected`)926 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetSheetRow.xlsx")))927}928func TestThemeColor(t *testing.T) {929 t.Log(ThemeColor("000000", -0.1))930 t.Log(ThemeColor("000000", 0))931 t.Log(ThemeColor("000000", 1))932}933func TestHSL(t *testing.T) {934 var hsl HSL935 t.Log(hsl.RGBA())936 t.Log(hslModel(hsl))937 t.Log(hslModel(color.Gray16{Y: uint16(1)}))938 t.Log(HSLToRGB(0, 1, 0.4))939 t.Log(HSLToRGB(0, 1, 0.6))940 t.Log(hueToRGB(0, 0, -1))941 t.Log(hueToRGB(0, 0, 2))942 t.Log(hueToRGB(0, 0, 1.0/7))943 t.Log(hueToRGB(0, 0, 0.4))944 t.Log(hueToRGB(0, 0, 2.0/4))945 t.Log(RGBToHSL(255, 255, 0))946 t.Log(RGBToHSL(0, 255, 255))947 t.Log(RGBToHSL(250, 100, 50))948 t.Log(RGBToHSL(50, 100, 250))949 t.Log(RGBToHSL(250, 50, 100))950}951func TestProtectSheet(t *testing.T) {952 f := NewFile()953 assert.NoError(t, f.ProtectSheet("Sheet1", nil))954 assert.NoError(t, f.ProtectSheet("Sheet1", &FormatSheetProtection{955 Password: "password",956 EditScenarios: false,957 }))958 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestProtectSheet.xlsx")))959 // Test protect not exists worksheet.960 assert.EqualError(t, f.ProtectSheet("SheetN", nil), "sheet SheetN is not exist")961}962func TestUnprotectSheet(t *testing.T) {963 f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))964 if !assert.NoError(t, err) {965 t.FailNow()966 }967 // Test unprotect not exists worksheet.968 assert.EqualError(t, f.UnprotectSheet("SheetN"), "sheet SheetN is not exist")969 assert.NoError(t, f.UnprotectSheet("Sheet1"))970 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestUnprotectSheet.xlsx")))971}972func TestSetDefaultTimeStyle(t *testing.T) {973 f := NewFile()974 // Test set default time style on not exists worksheet.975 assert.EqualError(t, f.setDefaultTimeStyle("SheetN", "", 0), "sheet SheetN is not exist")976}977func TestAddVBAProject(t *testing.T) {978 f := NewFile()979 assert.NoError(t, f.SetSheetPrOptions("Sheet1", CodeName("Sheet1")))980 assert.EqualError(t, f.AddVBAProject("macros.bin"), "stat macros.bin: no such file or directory")981 assert.EqualError(t, f.AddVBAProject(filepath.Join("test", "Book1.xlsx")), "unsupported VBA project extension")982 assert.NoError(t, f.AddVBAProject(filepath.Join("test", "vbaProject.bin")))983 // Test add VBA project twice.984 assert.NoError(t, f.AddVBAProject(filepath.Join("test", "vbaProject.bin")))985 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestAddVBAProject.xlsm")))986}987func TestContentTypesReader(t *testing.T) {988 // Test unsupport charset.989 f := NewFile()990 f.ContentTypes = nil991 f.XLSX["[Content_Types].xml"] = MacintoshCyrillicCharset992 f.contentTypesReader()993}994func TestWorkbookReader(t *testing.T) {995 // Test unsupport charset.996 f := NewFile()997 f.WorkBook = nil998 f.XLSX["xl/workbook.xml"] = MacintoshCyrillicCharset999 f.workbookReader()1000}1001func TestWorkSheetReader(t *testing.T) {1002 // Test unsupport charset.1003 f := NewFile()1004 delete(f.Sheet, "xl/worksheets/sheet1.xml")1005 f.XLSX["xl/worksheets/sheet1.xml"] = MacintoshCyrillicCharset1006 _, err := f.workSheetReader("Sheet1")1007 assert.EqualError(t, err, "xml decode error: XML syntax error on line 1: invalid UTF-8")1008 // Test on no checked worksheet.1009 f = NewFile()1010 delete(f.Sheet, "xl/worksheets/sheet1.xml")1011 f.XLSX["xl/worksheets/sheet1.xml"] = []byte(`<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData/></worksheet>`)1012 f.checked = nil1013 _, err = f.workSheetReader("Sheet1")1014 assert.NoError(t, err)1015}1016func TestRelsReader(t *testing.T) {1017 // Test unsupport charset.1018 f := NewFile()1019 rels := "xl/_rels/workbook.xml.rels"1020 f.Relationships[rels] = nil1021 f.XLSX[rels] = MacintoshCyrillicCharset1022 f.relsReader(rels)1023}1024func TestDeleteSheetFromWorkbookRels(t *testing.T) {1025 f := NewFile()1026 rels := "xl/_rels/workbook.xml.rels"1027 f.Relationships[rels] = nil1028 assert.Equal(t, f.deleteSheetFromWorkbookRels("rID"), "")...

Full Screen

Full Screen

rows_test.go

Source:rows_test.go Github

copy

Full Screen

...9)10func TestRows(t *testing.T) {11 const sheet2 = "Sheet2"12 f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))13 if !assert.NoError(t, err) {14 t.FailNow()15 }16 rows, err := f.Rows(sheet2)17 if !assert.NoError(t, err) {18 t.FailNow()19 }20 var collectedRows [][]string21 for rows.Next() {22 columns, err := rows.Columns()23 assert.NoError(t, err)24 collectedRows = append(collectedRows, trimSliceSpace(columns))25 }26 if !assert.NoError(t, rows.Error()) {27 t.FailNow()28 }29 returnedRows, err := f.GetRows(sheet2)30 assert.NoError(t, err)31 for i := range returnedRows {32 returnedRows[i] = trimSliceSpace(returnedRows[i])33 }34 if !assert.Equal(t, collectedRows, returnedRows) {35 t.FailNow()36 }37 f = NewFile()38 f.XLSX["xl/worksheets/sheet1.xml"] = []byte(`<worksheet><sheetData><row r="1"><c r="A1" t="s"><v>1</v></c></row><row r="A"><c r="2" t="str"><v>B</v></c></row></sheetData></worksheet>`)39 _, err = f.Rows("Sheet1")40 assert.EqualError(t, err, `strconv.Atoi: parsing "A": invalid syntax`)41}42func TestRowsIterator(t *testing.T) {43 const (44 sheet2 = "Sheet2"45 expectedNumRow = 1146 )47 f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))48 require.NoError(t, err)49 rows, err := f.Rows(sheet2)50 require.NoError(t, err)51 var rowCount int52 for rows.Next() {53 rowCount++54 require.True(t, rowCount <= expectedNumRow, "rowCount is greater than expected")55 }56 assert.Equal(t, expectedNumRow, rowCount)57 // Valued cell sparse distribution test58 f = NewFile()59 cells := []string{"C1", "E1", "A3", "B3", "C3", "D3", "E3"}60 for _, cell := range cells {61 assert.NoError(t, f.SetCellValue("Sheet1", cell, 1))62 }63 rows, err = f.Rows("Sheet1")64 require.NoError(t, err)65 rowCount = 066 for rows.Next() {67 rowCount++68 require.True(t, rowCount <= 3, "rowCount is greater than expected")69 }70 assert.Equal(t, 3, rowCount)71}72func TestRowsError(t *testing.T) {73 xlsx, err := OpenFile(filepath.Join("test", "Book1.xlsx"))74 if !assert.NoError(t, err) {75 t.FailNow()76 }77 _, err = xlsx.Rows("SheetN")78 assert.EqualError(t, err, "sheet SheetN is not exist")79}80func TestRowHeight(t *testing.T) {81 xlsx := NewFile()82 sheet1 := xlsx.GetSheetName(1)83 assert.EqualError(t, xlsx.SetRowHeight(sheet1, 0, defaultRowHeightPixels+1.0), "invalid row number 0")84 _, err := xlsx.GetRowHeight("Sheet1", 0)85 assert.EqualError(t, err, "invalid row number 0")86 assert.NoError(t, xlsx.SetRowHeight(sheet1, 1, 111.0))87 height, err := xlsx.GetRowHeight(sheet1, 1)88 assert.NoError(t, err)89 assert.Equal(t, 111.0, height)90 assert.NoError(t, xlsx.SetRowHeight(sheet1, 4, 444.0))91 height, err = xlsx.GetRowHeight(sheet1, 4)92 assert.NoError(t, err)93 assert.Equal(t, 444.0, height)94 // Test get row height that rows index over exists rows.95 height, err = xlsx.GetRowHeight(sheet1, 5)96 assert.NoError(t, err)97 assert.Equal(t, defaultRowHeightPixels, height)98 // Test get row height that rows heights haven't changed.99 height, err = xlsx.GetRowHeight(sheet1, 3)100 assert.NoError(t, err)101 assert.Equal(t, defaultRowHeightPixels, height)102 // Test set and get row height on not exists worksheet.103 assert.EqualError(t, xlsx.SetRowHeight("SheetN", 1, 111.0), "sheet SheetN is not exist")104 _, err = xlsx.GetRowHeight("SheetN", 3)105 assert.EqualError(t, err, "sheet SheetN is not exist")106 err = xlsx.SaveAs(filepath.Join("test", "TestRowHeight.xlsx"))107 if !assert.NoError(t, err) {108 t.FailNow()109 }110 convertColWidthToPixels(0)111}112func TestColumns(t *testing.T) {113 f := NewFile()114 rows, err := f.Rows("Sheet1")115 assert.NoError(t, err)116 rows.decoder = f.xmlNewDecoder(bytes.NewReader([]byte(`<worksheet><sheetData><row r="2"><c r="A1" t="s"><v>1</v></c></row></sheetData></worksheet>`)))117 _, err = rows.Columns()118 assert.NoError(t, err)119 rows.decoder = f.xmlNewDecoder(bytes.NewReader([]byte(`<worksheet><sheetData><row r="2"><c r="A1" t="s"><v>1</v></c></row></sheetData></worksheet>`)))120 rows.curRow = 1121 _, err = rows.Columns()122 assert.NoError(t, err)123 rows.decoder = f.xmlNewDecoder(bytes.NewReader([]byte(`<worksheet><sheetData><row r="A"><c r="A1" t="s"><v>1</v></c></row><row r="A"><c r="2" t="str"><v>B</v></c></row></sheetData></worksheet>`)))124 rows.stashRow, rows.curRow = 0, 1125 _, err = rows.Columns()126 assert.EqualError(t, err, `strconv.Atoi: parsing "A": invalid syntax`)127 rows.decoder = f.xmlNewDecoder(bytes.NewReader([]byte(`<worksheet><sheetData><row r="1"><c r="A1" t="s"><v>1</v></c></row><row r="A"><c r="2" t="str"><v>B</v></c></row></sheetData></worksheet>`)))128 _, err = rows.Columns()129 assert.NoError(t, err)130 rows.curRow = 3131 rows.decoder = f.xmlNewDecoder(bytes.NewReader([]byte(`<worksheet><sheetData><row r="1"><c r="A" t="s"><v>1</v></c></row></sheetData></worksheet>`)))132 _, err = rows.Columns()133 assert.EqualError(t, err, `cannot convert cell "A" to coordinates: invalid cell name "A"`)134 // Test token is nil135 rows.decoder = f.xmlNewDecoder(bytes.NewReader(nil))136 _, err = rows.Columns()137 assert.NoError(t, err)138}139func TestSharedStringsReader(t *testing.T) {140 f := NewFile()141 f.XLSX["xl/sharedStrings.xml"] = MacintoshCyrillicCharset142 f.sharedStringsReader()143}144func TestRowVisibility(t *testing.T) {145 f, err := prepareTestBook1()146 if !assert.NoError(t, err) {147 t.FailNow()148 }149 f.NewSheet("Sheet3")150 assert.NoError(t, f.SetRowVisible("Sheet3", 2, false))151 assert.NoError(t, f.SetRowVisible("Sheet3", 2, true))152 visiable, err := f.GetRowVisible("Sheet3", 2)153 assert.Equal(t, true, visiable)154 assert.NoError(t, err)155 visiable, err = f.GetRowVisible("Sheet3", 25)156 assert.Equal(t, false, visiable)157 assert.NoError(t, err)158 assert.EqualError(t, f.SetRowVisible("Sheet3", 0, true), "invalid row number 0")159 assert.EqualError(t, f.SetRowVisible("SheetN", 2, false), "sheet SheetN is not exist")160 visible, err := f.GetRowVisible("Sheet3", 0)161 assert.Equal(t, false, visible)162 assert.EqualError(t, err, "invalid row number 0")163 _, err = f.GetRowVisible("SheetN", 1)164 assert.EqualError(t, err, "sheet SheetN is not exist")165 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestRowVisibility.xlsx")))166}167func TestRemoveRow(t *testing.T) {168 f := NewFile()169 sheet1 := f.GetSheetName(1)170 r, err := f.workSheetReader(sheet1)171 assert.NoError(t, err)172 const (173 colCount = 10174 rowCount = 10175 )176 fillCells(f, sheet1, colCount, rowCount)177 assert.NoError(t, f.SetCellHyperLink(sheet1, "A5", "https://github.com/360EntSecGroup-Skylar/excelize", "External"))178 assert.EqualError(t, f.RemoveRow(sheet1, -1), "invalid row number -1")179 assert.EqualError(t, f.RemoveRow(sheet1, 0), "invalid row number 0")180 assert.NoError(t, f.RemoveRow(sheet1, 4))181 if !assert.Len(t, r.SheetData.Row, rowCount-1) {182 t.FailNow()183 }184 assert.NoError(t, f.MergeCell(sheet1, "B3", "B5"))185 assert.NoError(t, f.RemoveRow(sheet1, 2))186 if !assert.Len(t, r.SheetData.Row, rowCount-2) {187 t.FailNow()188 }189 assert.NoError(t, f.RemoveRow(sheet1, 4))190 if !assert.Len(t, r.SheetData.Row, rowCount-3) {191 t.FailNow()192 }193 err = f.AutoFilter(sheet1, "A2", "A2", `{"column":"A","expression":"x != blanks"}`)194 if !assert.NoError(t, err) {195 t.FailNow()196 }197 assert.NoError(t, f.RemoveRow(sheet1, 1))198 if !assert.Len(t, r.SheetData.Row, rowCount-4) {199 t.FailNow()200 }201 assert.NoError(t, f.RemoveRow(sheet1, 2))202 if !assert.Len(t, r.SheetData.Row, rowCount-5) {203 t.FailNow()204 }205 assert.NoError(t, f.RemoveRow(sheet1, 1))206 if !assert.Len(t, r.SheetData.Row, rowCount-6) {207 t.FailNow()208 }209 assert.NoError(t, f.RemoveRow(sheet1, 10))210 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestRemoveRow.xlsx")))211 // Test remove row on not exist worksheet212 assert.EqualError(t, f.RemoveRow("SheetN", 1), `sheet SheetN is not exist`)213}214func TestInsertRow(t *testing.T) {215 xlsx := NewFile()216 sheet1 := xlsx.GetSheetName(1)217 r, err := xlsx.workSheetReader(sheet1)218 assert.NoError(t, err)219 const (220 colCount = 10221 rowCount = 10222 )223 fillCells(xlsx, sheet1, colCount, rowCount)224 assert.NoError(t, xlsx.SetCellHyperLink(sheet1, "A5", "https://github.com/360EntSecGroup-Skylar/excelize", "External"))225 assert.EqualError(t, xlsx.InsertRow(sheet1, -1), "invalid row number -1")226 assert.EqualError(t, xlsx.InsertRow(sheet1, 0), "invalid row number 0")227 assert.NoError(t, xlsx.InsertRow(sheet1, 1))228 if !assert.Len(t, r.SheetData.Row, rowCount+1) {229 t.FailNow()230 }231 assert.NoError(t, xlsx.InsertRow(sheet1, 4))232 if !assert.Len(t, r.SheetData.Row, rowCount+2) {233 t.FailNow()234 }235 assert.NoError(t, xlsx.SaveAs(filepath.Join("test", "TestInsertRow.xlsx")))236}237// Testing internal sructure state after insert operations.238// It is important for insert workflow to be constant to avoid side effect with functions related to internal structure.239func TestInsertRowInEmptyFile(t *testing.T) {240 xlsx := NewFile()241 sheet1 := xlsx.GetSheetName(1)242 r, err := xlsx.workSheetReader(sheet1)243 assert.NoError(t, err)244 assert.NoError(t, xlsx.InsertRow(sheet1, 1))245 assert.Len(t, r.SheetData.Row, 0)246 assert.NoError(t, xlsx.InsertRow(sheet1, 2))247 assert.Len(t, r.SheetData.Row, 0)248 assert.NoError(t, xlsx.InsertRow(sheet1, 99))249 assert.Len(t, r.SheetData.Row, 0)250 assert.NoError(t, xlsx.SaveAs(filepath.Join("test", "TestInsertRowInEmptyFile.xlsx")))251}252func TestDuplicateRowFromSingleRow(t *testing.T) {253 const sheet = "Sheet1"254 outFile := filepath.Join("test", "TestDuplicateRow.%s.xlsx")255 cells := map[string]string{256 "A1": "A1 Value",257 "A2": "A2 Value",258 "A3": "A3 Value",259 "B1": "B1 Value",260 "B2": "B2 Value",261 "B3": "B3 Value",262 }263 t.Run("FromSingleRow", func(t *testing.T) {264 xlsx := NewFile()265 assert.NoError(t, xlsx.SetCellStr(sheet, "A1", cells["A1"]))266 assert.NoError(t, xlsx.SetCellStr(sheet, "B1", cells["B1"]))267 assert.NoError(t, xlsx.DuplicateRow(sheet, 1))268 if !assert.NoError(t, xlsx.SaveAs(fmt.Sprintf(outFile, "TestDuplicateRow.FromSingleRow_1"))) {269 t.FailNow()270 }271 expect := map[string]string{272 "A1": cells["A1"], "B1": cells["B1"],273 "A2": cells["A1"], "B2": cells["B1"],274 }275 for cell, val := range expect {276 v, err := xlsx.GetCellValue(sheet, cell)277 assert.NoError(t, err)278 if !assert.Equal(t, val, v, cell) {279 t.FailNow()280 }281 }282 assert.NoError(t, xlsx.DuplicateRow(sheet, 2))283 if !assert.NoError(t, xlsx.SaveAs(fmt.Sprintf(outFile, "TestDuplicateRow.FromSingleRow_2"))) {284 t.FailNow()285 }286 expect = map[string]string{287 "A1": cells["A1"], "B1": cells["B1"],288 "A2": cells["A1"], "B2": cells["B1"],289 "A3": cells["A1"], "B3": cells["B1"],290 }291 for cell, val := range expect {292 v, err := xlsx.GetCellValue(sheet, cell)293 assert.NoError(t, err)294 if !assert.Equal(t, val, v, cell) {295 t.FailNow()296 }297 }298 })299}300func TestDuplicateRowUpdateDuplicatedRows(t *testing.T) {301 const sheet = "Sheet1"302 outFile := filepath.Join("test", "TestDuplicateRow.%s.xlsx")303 cells := map[string]string{304 "A1": "A1 Value",305 "A2": "A2 Value",306 "A3": "A3 Value",307 "B1": "B1 Value",308 "B2": "B2 Value",309 "B3": "B3 Value",310 }311 t.Run("UpdateDuplicatedRows", func(t *testing.T) {312 xlsx := NewFile()313 assert.NoError(t, xlsx.SetCellStr(sheet, "A1", cells["A1"]))314 assert.NoError(t, xlsx.SetCellStr(sheet, "B1", cells["B1"]))315 assert.NoError(t, xlsx.DuplicateRow(sheet, 1))316 assert.NoError(t, xlsx.SetCellStr(sheet, "A2", cells["A2"]))317 assert.NoError(t, xlsx.SetCellStr(sheet, "B2", cells["B2"]))318 if !assert.NoError(t, xlsx.SaveAs(fmt.Sprintf(outFile, "TestDuplicateRow.UpdateDuplicatedRows"))) {319 t.FailNow()320 }321 expect := map[string]string{322 "A1": cells["A1"], "B1": cells["B1"],323 "A2": cells["A2"], "B2": cells["B2"],324 }325 for cell, val := range expect {326 v, err := xlsx.GetCellValue(sheet, cell)327 assert.NoError(t, err)328 if !assert.Equal(t, val, v, cell) {329 t.FailNow()330 }331 }332 })333}334func TestDuplicateRowFirstOfMultipleRows(t *testing.T) {335 const sheet = "Sheet1"336 outFile := filepath.Join("test", "TestDuplicateRow.%s.xlsx")337 cells := map[string]string{338 "A1": "A1 Value",339 "A2": "A2 Value",340 "A3": "A3 Value",341 "B1": "B1 Value",342 "B2": "B2 Value",343 "B3": "B3 Value",344 }345 newFileWithDefaults := func() *File {346 f := NewFile()347 for cell, val := range cells {348 assert.NoError(t, f.SetCellStr(sheet, cell, val))349 }350 return f351 }352 t.Run("FirstOfMultipleRows", func(t *testing.T) {353 xlsx := newFileWithDefaults()354 assert.NoError(t, xlsx.DuplicateRow(sheet, 1))355 if !assert.NoError(t, xlsx.SaveAs(fmt.Sprintf(outFile, "TestDuplicateRow.FirstOfMultipleRows"))) {356 t.FailNow()357 }358 expect := map[string]string{359 "A1": cells["A1"], "B1": cells["B1"],360 "A2": cells["A1"], "B2": cells["B1"],361 "A3": cells["A2"], "B3": cells["B2"],362 "A4": cells["A3"], "B4": cells["B3"],363 }364 for cell, val := range expect {365 v, err := xlsx.GetCellValue(sheet, cell)366 assert.NoError(t, err)367 if !assert.Equal(t, val, v, cell) {368 t.FailNow()369 }370 }371 })372}373func TestDuplicateRowZeroWithNoRows(t *testing.T) {374 const sheet = "Sheet1"375 outFile := filepath.Join("test", "TestDuplicateRow.%s.xlsx")376 t.Run("ZeroWithNoRows", func(t *testing.T) {377 xlsx := NewFile()378 assert.EqualError(t, xlsx.DuplicateRow(sheet, 0), "invalid row number 0")379 if !assert.NoError(t, xlsx.SaveAs(fmt.Sprintf(outFile, "TestDuplicateRow.ZeroWithNoRows"))) {380 t.FailNow()381 }382 val, err := xlsx.GetCellValue(sheet, "A1")383 assert.NoError(t, err)384 assert.Equal(t, "", val)385 val, err = xlsx.GetCellValue(sheet, "B1")386 assert.NoError(t, err)387 assert.Equal(t, "", val)388 val, err = xlsx.GetCellValue(sheet, "A2")389 assert.NoError(t, err)390 assert.Equal(t, "", val)391 val, err = xlsx.GetCellValue(sheet, "B2")392 assert.NoError(t, err)393 assert.Equal(t, "", val)394 assert.NoError(t, err)395 expect := map[string]string{396 "A1": "", "B1": "",397 "A2": "", "B2": "",398 }399 for cell, val := range expect {400 v, err := xlsx.GetCellValue(sheet, cell)401 assert.NoError(t, err)402 if !assert.Equal(t, val, v, cell) {403 t.FailNow()404 }405 }406 })407}408func TestDuplicateRowMiddleRowOfEmptyFile(t *testing.T) {409 const sheet = "Sheet1"410 outFile := filepath.Join("test", "TestDuplicateRow.%s.xlsx")411 t.Run("MiddleRowOfEmptyFile", func(t *testing.T) {412 xlsx := NewFile()413 assert.NoError(t, xlsx.DuplicateRow(sheet, 99))414 if !assert.NoError(t, xlsx.SaveAs(fmt.Sprintf(outFile, "TestDuplicateRow.MiddleRowOfEmptyFile"))) {415 t.FailNow()416 }417 expect := map[string]string{418 "A98": "",419 "A99": "",420 "A100": "",421 }422 for cell, val := range expect {423 v, err := xlsx.GetCellValue(sheet, cell)424 assert.NoError(t, err)425 if !assert.Equal(t, val, v, cell) {426 t.FailNow()427 }428 }429 })430}431func TestDuplicateRowWithLargeOffsetToMiddleOfData(t *testing.T) {432 const sheet = "Sheet1"433 outFile := filepath.Join("test", "TestDuplicateRow.%s.xlsx")434 cells := map[string]string{435 "A1": "A1 Value",436 "A2": "A2 Value",437 "A3": "A3 Value",438 "B1": "B1 Value",439 "B2": "B2 Value",440 "B3": "B3 Value",441 }442 newFileWithDefaults := func() *File {443 f := NewFile()444 for cell, val := range cells {445 assert.NoError(t, f.SetCellStr(sheet, cell, val))446 }447 return f448 }449 t.Run("WithLargeOffsetToMiddleOfData", func(t *testing.T) {450 xlsx := newFileWithDefaults()451 assert.NoError(t, xlsx.DuplicateRowTo(sheet, 1, 3))452 if !assert.NoError(t, xlsx.SaveAs(fmt.Sprintf(outFile, "TestDuplicateRow.WithLargeOffsetToMiddleOfData"))) {453 t.FailNow()454 }455 expect := map[string]string{456 "A1": cells["A1"], "B1": cells["B1"],457 "A2": cells["A2"], "B2": cells["B2"],458 "A3": cells["A1"], "B3": cells["B1"],459 "A4": cells["A3"], "B4": cells["B3"],460 }461 for cell, val := range expect {462 v, err := xlsx.GetCellValue(sheet, cell)463 assert.NoError(t, err)464 if !assert.Equal(t, val, v, cell) {465 t.FailNow()466 }467 }468 })469}470func TestDuplicateRowWithLargeOffsetToEmptyRows(t *testing.T) {471 const sheet = "Sheet1"472 outFile := filepath.Join("test", "TestDuplicateRow.%s.xlsx")473 cells := map[string]string{474 "A1": "A1 Value",475 "A2": "A2 Value",476 "A3": "A3 Value",477 "B1": "B1 Value",478 "B2": "B2 Value",479 "B3": "B3 Value",480 }481 newFileWithDefaults := func() *File {482 f := NewFile()483 for cell, val := range cells {484 assert.NoError(t, f.SetCellStr(sheet, cell, val))485 }486 return f487 }488 t.Run("WithLargeOffsetToEmptyRows", func(t *testing.T) {489 xlsx := newFileWithDefaults()490 assert.NoError(t, xlsx.DuplicateRowTo(sheet, 1, 7))491 if !assert.NoError(t, xlsx.SaveAs(fmt.Sprintf(outFile, "TestDuplicateRow.WithLargeOffsetToEmptyRows"))) {492 t.FailNow()493 }494 expect := map[string]string{495 "A1": cells["A1"], "B1": cells["B1"],496 "A2": cells["A2"], "B2": cells["B2"],497 "A3": cells["A3"], "B3": cells["B3"],498 "A7": cells["A1"], "B7": cells["B1"],499 }500 for cell, val := range expect {501 v, err := xlsx.GetCellValue(sheet, cell)502 assert.NoError(t, err)503 if !assert.Equal(t, val, v, cell) {504 t.FailNow()505 }506 }507 })508}509func TestDuplicateRowInsertBefore(t *testing.T) {510 const sheet = "Sheet1"511 outFile := filepath.Join("test", "TestDuplicateRow.%s.xlsx")512 cells := map[string]string{513 "A1": "A1 Value",514 "A2": "A2 Value",515 "A3": "A3 Value",516 "B1": "B1 Value",517 "B2": "B2 Value",518 "B3": "B3 Value",519 }520 newFileWithDefaults := func() *File {521 f := NewFile()522 for cell, val := range cells {523 assert.NoError(t, f.SetCellStr(sheet, cell, val))524 }525 return f526 }527 t.Run("InsertBefore", func(t *testing.T) {528 xlsx := newFileWithDefaults()529 assert.NoError(t, xlsx.DuplicateRowTo(sheet, 2, 1))530 if !assert.NoError(t, xlsx.SaveAs(fmt.Sprintf(outFile, "TestDuplicateRow.InsertBefore"))) {531 t.FailNow()532 }533 expect := map[string]string{534 "A1": cells["A2"], "B1": cells["B2"],535 "A2": cells["A1"], "B2": cells["B1"],536 "A3": cells["A2"], "B3": cells["B2"],537 "A4": cells["A3"], "B4": cells["B3"],538 }539 for cell, val := range expect {540 v, err := xlsx.GetCellValue(sheet, cell)541 assert.NoError(t, err)542 if !assert.Equal(t, val, v, cell) {543 t.FailNow()544 }545 }546 })547}548func TestDuplicateRowInsertBeforeWithLargeOffset(t *testing.T) {549 const sheet = "Sheet1"550 outFile := filepath.Join("test", "TestDuplicateRow.%s.xlsx")551 cells := map[string]string{552 "A1": "A1 Value",553 "A2": "A2 Value",554 "A3": "A3 Value",555 "B1": "B1 Value",556 "B2": "B2 Value",557 "B3": "B3 Value",558 }559 newFileWithDefaults := func() *File {560 f := NewFile()561 for cell, val := range cells {562 assert.NoError(t, f.SetCellStr(sheet, cell, val))563 }564 return f565 }566 t.Run("InsertBeforeWithLargeOffset", func(t *testing.T) {567 xlsx := newFileWithDefaults()568 assert.NoError(t, xlsx.DuplicateRowTo(sheet, 3, 1))569 if !assert.NoError(t, xlsx.SaveAs(fmt.Sprintf(outFile, "TestDuplicateRow.InsertBeforeWithLargeOffset"))) {570 t.FailNow()571 }572 expect := map[string]string{573 "A1": cells["A3"], "B1": cells["B3"],574 "A2": cells["A1"], "B2": cells["B1"],575 "A3": cells["A2"], "B3": cells["B2"],576 "A4": cells["A3"], "B4": cells["B3"],577 }578 for cell, val := range expect {579 v, err := xlsx.GetCellValue(sheet, cell)580 assert.NoError(t, err)581 if !assert.Equal(t, val, v) {582 t.FailNow()583 }584 }585 })586}587func TestDuplicateRowInsertBeforeWithMergeCells(t *testing.T) {588 const sheet = "Sheet1"589 outFile := filepath.Join("test", "TestDuplicateRow.%s.xlsx")590 cells := map[string]string{591 "A1": "A1 Value",592 "A2": "A2 Value",593 "A3": "A3 Value",594 "B1": "B1 Value",595 "B2": "B2 Value",596 "B3": "B3 Value",597 }598 newFileWithDefaults := func() *File {599 f := NewFile()600 for cell, val := range cells {601 assert.NoError(t, f.SetCellStr(sheet, cell, val))602 }603 assert.NoError(t, f.MergeCell(sheet, "B2", "C2"))604 assert.NoError(t, f.MergeCell(sheet, "C6", "C8"))605 return f606 }607 t.Run("InsertBeforeWithLargeOffset", func(t *testing.T) {608 xlsx := newFileWithDefaults()609 assert.NoError(t, xlsx.DuplicateRowTo(sheet, 2, 1))610 assert.NoError(t, xlsx.DuplicateRowTo(sheet, 1, 8))611 if !assert.NoError(t, xlsx.SaveAs(fmt.Sprintf(outFile, "TestDuplicateRow.InsertBeforeWithMergeCells"))) {612 t.FailNow()613 }614 expect := []MergeCell{615 {"B3:C3", "B2 Value"},616 {"C7:C10", ""},617 {"B1:C1", "B2 Value"},618 }619 mergeCells, err := xlsx.GetMergeCells(sheet)620 assert.NoError(t, err)621 for idx, val := range expect {622 if !assert.Equal(t, val, mergeCells[idx]) {623 t.FailNow()624 }625 }626 })627}628func TestDuplicateRowInvalidRownum(t *testing.T) {629 const sheet = "Sheet1"630 outFile := filepath.Join("test", "TestDuplicateRowInvalidRownum.%s.xlsx")631 cells := map[string]string{632 "A1": "A1 Value",633 "A2": "A2 Value",634 "A3": "A3 Value",635 "B1": "B1 Value",636 "B2": "B2 Value",637 "B3": "B3 Value",638 }639 invalidIndexes := []int{-100, -2, -1, 0}640 for _, row := range invalidIndexes {641 name := fmt.Sprintf("%d", row)642 t.Run(name, func(t *testing.T) {643 xlsx := NewFile()644 for col, val := range cells {645 assert.NoError(t, xlsx.SetCellStr(sheet, col, val))646 }647 assert.EqualError(t, xlsx.DuplicateRow(sheet, row), fmt.Sprintf("invalid row number %d", row))648 for col, val := range cells {649 v, err := xlsx.GetCellValue(sheet, col)650 assert.NoError(t, err)651 if !assert.Equal(t, val, v) {652 t.FailNow()653 }654 }655 assert.NoError(t, xlsx.SaveAs(fmt.Sprintf(outFile, name)))656 })657 }658 for _, row1 := range invalidIndexes {659 for _, row2 := range invalidIndexes {660 name := fmt.Sprintf("[%d,%d]", row1, row2)661 t.Run(name, func(t *testing.T) {662 xlsx := NewFile()663 for col, val := range cells {664 assert.NoError(t, xlsx.SetCellStr(sheet, col, val))665 }666 assert.EqualError(t, xlsx.DuplicateRowTo(sheet, row1, row2), fmt.Sprintf("invalid row number %d", row1))667 for col, val := range cells {668 v, err := xlsx.GetCellValue(sheet, col)669 assert.NoError(t, err)670 if !assert.Equal(t, val, v) {671 t.FailNow()672 }673 }674 assert.NoError(t, xlsx.SaveAs(fmt.Sprintf(outFile, name)))675 })676 }677 }678}679func TestDuplicateRowTo(t *testing.T) {680 f := File{}681 assert.EqualError(t, f.DuplicateRowTo("SheetN", 1, 2), "sheet SheetN is not exist")682}683func TestDuplicateMergeCells(t *testing.T) {684 f := File{}685 xlsx := &xlsxWorksheet{MergeCells: &xlsxMergeCells{686 Cells: []*xlsxMergeCell{{Ref: "A1:-"}},687 }}688 assert.EqualError(t, f.duplicateMergeCells("Sheet1", xlsx, 0, 0), `cannot convert cell "-" to coordinates: invalid cell name "-"`)689 xlsx.MergeCells.Cells[0].Ref = "A1:B1"690 assert.EqualError(t, f.duplicateMergeCells("SheetN", xlsx, 1, 2), "sheet SheetN is not exist")691}692func TestGetValueFrom(t *testing.T) {693 c := &xlsxC{T: "inlineStr"}694 f := NewFile()695 d := &xlsxSST{}696 val, err := c.getValueFrom(f, d)697 assert.NoError(t, err)698 assert.Equal(t, "", val)699}700func TestErrSheetNotExistError(t *testing.T) {701 err := ErrSheetNotExist{SheetName: "Sheet1"}702 assert.EqualValues(t, err.Error(), "sheet Sheet1 is not exist")703}704func BenchmarkRows(b *testing.B) {705 f, _ := OpenFile(filepath.Join("test", "Book1.xlsx"))706 for i := 0; i < b.N; i++ {707 rows, _ := f.Rows("Sheet2")708 for rows.Next() {709 row, _ := rows.Columns()710 for i := range row {711 if i >= 0 {...

Full Screen

Full Screen

col_test.go

Source:col_test.go Github

copy

Full Screen

...6)7func TestColumnVisibility(t *testing.T) {8 t.Run("TestBook1", func(t *testing.T) {9 f, err := prepareTestBook1()10 assert.NoError(t, err)11 // Hide/display a column with SetColVisible12 assert.NoError(t, f.SetColVisible("Sheet1", "F", false))13 assert.NoError(t, f.SetColVisible("Sheet1", "F", true))14 visible, err := f.GetColVisible("Sheet1", "F")15 assert.Equal(t, true, visible)16 assert.NoError(t, err)17 // Test hiding a few columns SetColVisible(...false)...18 assert.NoError(t, f.SetColVisible("Sheet1", "F:V", false))19 visible, err = f.GetColVisible("Sheet1", "F")20 assert.Equal(t, false, visible)21 assert.NoError(t, err)22 visible, err = f.GetColVisible("Sheet1", "U")23 assert.Equal(t, false, visible)24 assert.NoError(t, err)25 visible, err = f.GetColVisible("Sheet1", "V")26 assert.Equal(t, false, visible)27 assert.NoError(t, err)28 // ...and displaying them back SetColVisible(...true)29 assert.NoError(t, f.SetColVisible("Sheet1", "V:F", true))30 visible, err = f.GetColVisible("Sheet1", "F")31 assert.Equal(t, true, visible)32 assert.NoError(t, err)33 visible, err = f.GetColVisible("Sheet1", "U")34 assert.Equal(t, true, visible)35 assert.NoError(t, err)36 visible, err = f.GetColVisible("Sheet1", "G")37 assert.Equal(t, true, visible)38 assert.NoError(t, err)39 // Test get column visible on an inexistent worksheet.40 _, err = f.GetColVisible("SheetN", "F")41 assert.EqualError(t, err, "sheet SheetN is not exist")42 // Test get column visible with illegal cell coordinates.43 _, err = f.GetColVisible("Sheet1", "*")44 assert.EqualError(t, err, `invalid column name "*"`)45 assert.EqualError(t, f.SetColVisible("Sheet1", "*", false), `invalid column name "*"`)46 f.NewSheet("Sheet3")47 assert.NoError(t, f.SetColVisible("Sheet3", "E", false))48 assert.EqualError(t, f.SetColVisible("Sheet1", "A:-1", true), "invalid column name \"-1\"")49 assert.EqualError(t, f.SetColVisible("SheetN", "E", false), "sheet SheetN is not exist")50 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestColumnVisibility.xlsx")))51 })52 t.Run("TestBook3", func(t *testing.T) {53 f, err := prepareTestBook3()54 assert.NoError(t, err)55 visible, err := f.GetColVisible("Sheet1", "B")56 assert.Equal(t, true, visible)57 assert.NoError(t, err)58 })59}60func TestOutlineLevel(t *testing.T) {61 f := NewFile()62 level, err := f.GetColOutlineLevel("Sheet1", "D")63 assert.Equal(t, uint8(0), level)64 assert.NoError(t, err)65 f.NewSheet("Sheet2")66 assert.NoError(t, f.SetColOutlineLevel("Sheet1", "D", 4))67 level, err = f.GetColOutlineLevel("Sheet1", "D")68 assert.Equal(t, uint8(4), level)69 assert.NoError(t, err)70 level, err = f.GetColOutlineLevel("Shee2", "A")71 assert.Equal(t, uint8(0), level)72 assert.EqualError(t, err, "sheet Shee2 is not exist")73 assert.NoError(t, f.SetColWidth("Sheet2", "A", "D", 13))74 assert.NoError(t, f.SetColOutlineLevel("Sheet2", "B", 2))75 assert.NoError(t, f.SetRowOutlineLevel("Sheet1", 2, 7))76 assert.EqualError(t, f.SetColOutlineLevel("Sheet1", "D", 8), "invalid outline level")77 assert.EqualError(t, f.SetRowOutlineLevel("Sheet1", 2, 8), "invalid outline level")78 // Test set row outline level on not exists worksheet.79 assert.EqualError(t, f.SetRowOutlineLevel("SheetN", 1, 4), "sheet SheetN is not exist")80 // Test get row outline level on not exists worksheet.81 _, err = f.GetRowOutlineLevel("SheetN", 1)82 assert.EqualError(t, err, "sheet SheetN is not exist")83 // Test set and get column outline level with illegal cell coordinates.84 assert.EqualError(t, f.SetColOutlineLevel("Sheet1", "*", 1), `invalid column name "*"`)85 _, err = f.GetColOutlineLevel("Sheet1", "*")86 assert.EqualError(t, err, `invalid column name "*"`)87 // Test set column outline level on not exists worksheet.88 assert.EqualError(t, f.SetColOutlineLevel("SheetN", "E", 2), "sheet SheetN is not exist")89 assert.EqualError(t, f.SetRowOutlineLevel("Sheet1", 0, 1), "invalid row number 0")90 level, err = f.GetRowOutlineLevel("Sheet1", 2)91 assert.NoError(t, err)92 assert.Equal(t, uint8(7), level)93 _, err = f.GetRowOutlineLevel("Sheet1", 0)94 assert.EqualError(t, err, `invalid row number 0`)95 level, err = f.GetRowOutlineLevel("Sheet1", 10)96 assert.NoError(t, err)97 assert.Equal(t, uint8(0), level)98 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestOutlineLevel.xlsx")))99 f, err = OpenFile(filepath.Join("test", "Book1.xlsx"))100 assert.NoError(t, err)101 assert.NoError(t, f.SetColOutlineLevel("Sheet2", "B", 2))102}103func TestSetColStyle(t *testing.T) {104 f := NewFile()105 style, err := f.NewStyle(`{"fill":{"type":"pattern","color":["#94d3a2"],"pattern":1}}`)106 assert.NoError(t, err)107 // Test set column style on not exists worksheet.108 assert.EqualError(t, f.SetColStyle("SheetN", "E", style), "sheet SheetN is not exist")109 // Test set column style with illegal cell coordinates.110 assert.EqualError(t, f.SetColStyle("Sheet1", "*", style), `invalid column name "*"`)111 assert.EqualError(t, f.SetColStyle("Sheet1", "A:*", style), `invalid column name "*"`)112 assert.NoError(t, f.SetColStyle("Sheet1", "B", style))113 // Test set column style with already exists column with style.114 assert.NoError(t, f.SetColStyle("Sheet1", "B", style))115 assert.NoError(t, f.SetColStyle("Sheet1", "D:C", style))116 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetColStyle.xlsx")))117}118func TestColWidth(t *testing.T) {119 f := NewFile()120 assert.NoError(t, f.SetColWidth("Sheet1", "B", "A", 12))121 assert.NoError(t, f.SetColWidth("Sheet1", "A", "B", 12))122 width, err := f.GetColWidth("Sheet1", "A")123 assert.Equal(t, float64(12), width)124 assert.NoError(t, err)125 width, err = f.GetColWidth("Sheet1", "C")126 assert.Equal(t, float64(64), width)127 assert.NoError(t, err)128 // Test set and get column width with illegal cell coordinates.129 width, err = f.GetColWidth("Sheet1", "*")130 assert.Equal(t, float64(64), width)131 assert.EqualError(t, err, `invalid column name "*"`)132 assert.EqualError(t, f.SetColWidth("Sheet1", "*", "B", 1), `invalid column name "*"`)133 assert.EqualError(t, f.SetColWidth("Sheet1", "A", "*", 1), `invalid column name "*"`)134 // Test set column width on not exists worksheet.135 assert.EqualError(t, f.SetColWidth("SheetN", "B", "A", 12), "sheet SheetN is not exist")136 // Test get column width on not exists worksheet.137 _, err = f.GetColWidth("SheetN", "A")138 assert.EqualError(t, err, "sheet SheetN is not exist")139 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestColWidth.xlsx")))140 convertRowHeightToPixels(0)141}142func TestInsertCol(t *testing.T) {143 f := NewFile()144 sheet1 := f.GetSheetName(1)145 fillCells(f, sheet1, 10, 10)146 assert.NoError(t, f.SetCellHyperLink(sheet1, "A5", "https://github.com/360EntSecGroup-Skylar/excelize", "External"))147 assert.NoError(t, f.MergeCell(sheet1, "A1", "C3"))148 assert.NoError(t, f.AutoFilter(sheet1, "A2", "B2", `{"column":"B","expression":"x != blanks"}`))149 assert.NoError(t, f.InsertCol(sheet1, "A"))150 // Test insert column with illegal cell coordinates.151 assert.EqualError(t, f.InsertCol("Sheet1", "*"), `invalid column name "*"`)152 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestInsertCol.xlsx")))153}154func TestRemoveCol(t *testing.T) {155 f := NewFile()156 sheet1 := f.GetSheetName(1)157 fillCells(f, sheet1, 10, 15)158 assert.NoError(t, f.SetCellHyperLink(sheet1, "A5", "https://github.com/360EntSecGroup-Skylar/excelize", "External"))159 assert.NoError(t, f.SetCellHyperLink(sheet1, "C5", "https://github.com", "External"))160 assert.NoError(t, f.MergeCell(sheet1, "A1", "B1"))161 assert.NoError(t, f.MergeCell(sheet1, "A2", "B2"))162 assert.NoError(t, f.RemoveCol(sheet1, "A"))163 assert.NoError(t, f.RemoveCol(sheet1, "A"))164 // Test remove column with illegal cell coordinates.165 assert.EqualError(t, f.RemoveCol("Sheet1", "*"), `invalid column name "*"`)166 // Test remove column on not exists worksheet.167 assert.EqualError(t, f.RemoveCol("SheetN", "B"), "sheet SheetN is not exist")168 assert.NoError(t, f.SaveAs(filepath.Join("test", "TestRemoveCol.xlsx")))169}...

Full Screen

Full Screen

NoError

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World!!!")4}5func TestMain(m *testing.M) {6 flag.Parse()7 os.Exit(m.Run())8}9func TestHelloWorld(t *testing.T) {10 fmt.Println("Hello World!!!")11}12func TestLog(t *testing.T) {13 t.Log("This is a log")14}15func TestLogf(t *testing.T) {16 t.Logf("This is a logf")17}18func TestError(t *testing.T) {19 err := fmt.Errorf("This is an error")20 t.Error(err)21}22func TestErrorf(t *testing.T) {23 err := fmt.Errorf("This is an errorf")24 t.Errorf("%s", err)25}26func TestFail(t *testing.T) {27 t.Fail()28}29func TestFailNow(t *testing.T) {30 t.FailNow()31}32func TestFatal(t *testing.T) {33 t.Fatal("This is a fatal error")34}35func TestFatalNow(t *testing.T) {36 t.Fatal("This is a fatal error")37}38func TestSkip(t *testing.T) {39 t.Skip("This is a skip")40}41func TestSkipNow(t *testing.T) {42 t.SkipNow()43}44func TestSkipf(t *testing.T) {45 t.Skipf("This is a skipf")46}47func TestNoError(t *testing.T) {48 err := fmt.Errorf("This is an error")49 t.NoError(err)50}51func TestParallel(t *testing.T) {52 t.Parallel()53}54func TestRun(t *testing.T) {55 t.Run("This is a subtest", func(t *testing.T) {56 t.Log("This is a log")

Full Screen

Full Screen

NoError

Using AI Code Generation

copy

Full Screen

1import (2func TestNoError(t *testing.T) {3 t.Error("This is an error")4}5import (6func TestFailNow(t *testing.T) {7 t.FailNow()8}9import (10func TestFail(t *testing.T) {11 t.Fail()12}13import (14func TestFatal(t *testing.T) {15 t.Fatal("Fatal error")16}17import (18func TestFatalf(t *testing.T) {19 t.Fatalf("Fatal error")20}21import (22func TestLog(t *testing.T) {23 t.Log("This is a log")24}25import (26func TestLogf(t *testing.T) {27 t.Logf("This is a log")28}29import (30func TestLog(t *testing.T) {31 t.Log("This is a log")32}33import (34func TestLogf(t *testing.T) {35 t.Logf("This is a log")36}37import (38func TestSkip(t *testing.T) {39 t.Skip("This test is skipped")40}41import (42func TestSkipNow(t *testing.T) {43 t.SkipNow()44}45import (46func TestSkipf(t *testing.T) {

Full Screen

Full Screen

NoError

Using AI Code Generation

copy

Full Screen

1import (2func TestNoError(t *testing.T) {3 err := doSomething()4 t.NoError(err)5}6func doSomething() error {7}

Full Screen

Full Screen

NoError

Using AI Code Generation

copy

Full Screen

1import (2func TestNoError(t *testing.T) {3 if err != nil {4 t.Error("Error")5 }6 t.Log("No Error")7}8import (9func TestErrorf(t *testing.T) {10 if err != nil {11 t.Errorf("Error: %v", err)12 }13 t.Log("No Error")14}15import (16func TestFail(t *testing.T) {17 if err != nil {18 t.Fail()19 }20 t.Log("No Error")21}22import (23func TestFailNow(t *testing.T) {24 if err != nil {25 t.FailNow()26 }27 t.Log("No Error")28}29import (30func TestFailed(t *testing.T) {31 if err != nil {32 t.Fail()33 }34 if t.Failed() {35 t.Log("Error")36 }37 t.Log("No Error")38}39import (40func TestFatal(t *testing.T) {41 if err != nil {42 t.Fatal("Error")43 }44 t.Log("No Error")45}46import (47func TestFatalIf(t *testing.T) {48 t.FatalIf(err, "Error")49 t.Log("No Error")50}51import (52func TestFatalIfErr(t *testing.T) {53 t.FatalIfErr(err)54 t.Log("No Error")55}56import (

Full Screen

Full Screen

NoError

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4}5func TestNoError(t *testing.T) {6 err := fmt.Errorf("this is an error")7 if err != nil {8 t.Fatal("expected no error")9 }10}

Full Screen

Full Screen

NoError

Using AI Code Generation

copy

Full Screen

1import (2func TestError(t *testing.T) {3 fmt.Println("Error is:", err)4 t.Error("Error is not nil")5}6func TestNoError(t *testing.T) {7 fmt.Println("Error is:", err)8 t.NoError(err)9}

Full Screen

Full Screen

NoError

Using AI Code Generation

copy

Full Screen

1import (2func TestNoError(t *testing.T) {3 err := getError()4 t.Log("getError returned ", err)5 t.Log("Calling NoError method")6 t.NoError(err)7 t.Log("NoError method returned")8}9func getError() error {10}

Full Screen

Full Screen

NoError

Using AI Code Generation

copy

Full Screen

1import (2func TestNoError(t *testing.T) {3 fmt.Println("No Error Test")4 t.Logf("This is a test log")5 t.Fail()6}7func TestError(t *testing.T) {8 fmt.Println("Error Test")9 t.Errorf("This is a test error")10}11func TestFatal(t *testing.T) {12 fmt.Println("Fatal Test")13 t.Fatalf("This is a test fatal")14}15func TestLog(t *testing.T) {16 fmt.Println("Log Test")17 t.Logf("This is a test log")18}19func TestFail(t *testing.T) {20 fmt.Println("Fail Test")21 t.Fail()22}23import (24func TestErrorf(t *testing.T) {25 fmt.Println("Errorf Test")26 t.Errorf("This is a test error")27}28import (29func TestFailNow(t *testing.T) {30 fmt.Println("FailNow Test")31 t.FailNow()32}33import (34func TestLogf(t *testing.T) {35 fmt.Println("Logf Test")36 t.Logf("This is a test log")37}38import (39func TestSkipNow(t *testing.T) {40 fmt.Println("SkipNow Test")41 t.SkipNow()42}43import (44func TestSkipf(t *testing.T) {45 fmt.Println("Skipf Test")46 t.Skipf("This is a test skip")47}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful