Skip to content

Commit

Permalink
Improve code coverage unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
xuri committed Dec 21, 2019
1 parent 7358dca commit ae2865d
Show file tree
Hide file tree
Showing 16 changed files with 438 additions and 142 deletions.
19 changes: 19 additions & 0 deletions calcchain_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package excelize

import "testing"

func TestCalcChainReader(t *testing.T) {
f := NewFile()
f.CalcChain = nil
f.XLSX["xl/calcChain.xml"] = MacintoshCyrillicCharset
f.calcChainReader()
}

func TestDeleteCalcChain(t *testing.T) {
f := NewFile()
f.CalcChain = &xlsxCalcChain{C: []xlsxCalcChainC{}}
f.ContentTypes.Overrides = append(f.ContentTypes.Overrides, xlsxOverride{
PartName: "/xl/calcChain.xml",
})
f.deleteCalcChain(1, "A1")
}
9 changes: 8 additions & 1 deletion cell_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,15 @@ func TestSetCellBool(t *testing.T) {
}

func TestGetCellFormula(t *testing.T) {
// Test get cell formula on not exist worksheet.
f := NewFile()
f.GetCellFormula("Sheet", "A1")
_, err := f.GetCellFormula("SheetN", "A1")
assert.EqualError(t, err, "sheet SheetN is not exist")

// Test get cell formula on no formula cell.
f.SetCellValue("Sheet1", "A1", true)
_, err = f.GetCellFormula("Sheet1", "A1")
assert.NoError(t, err)
}

func ExampleFile_SetCellFloat() {
Expand Down
56 changes: 56 additions & 0 deletions comment_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.10 or later.

package excelize

import (
"path/filepath"
"strings"
"testing"

"github.com/stretchr/testify/assert"
)

func TestAddComments(t *testing.T) {
f, err := prepareTestBook1()
if !assert.NoError(t, err) {
t.FailNow()
}

s := strings.Repeat("c", 32768)
assert.NoError(t, f.AddComment("Sheet1", "A30", `{"author":"`+s+`","text":"`+s+`"}`))
assert.NoError(t, f.AddComment("Sheet2", "B7", `{"author":"Excelize: ","text":"This is a comment."}`))

// Test add comment on not exists worksheet.
assert.EqualError(t, f.AddComment("SheetN", "B7", `{"author":"Excelize: ","text":"This is a comment."}`), "sheet SheetN is not exist")

if assert.NoError(t, f.SaveAs(filepath.Join("test", "TestAddComments.xlsx"))) {
assert.Len(t, f.GetComments(), 2)
}
}

func TestDecodeVMLDrawingReader(t *testing.T) {
f := NewFile()
path := "xl/drawings/vmlDrawing1.xml"
f.XLSX[path] = MacintoshCyrillicCharset
f.decodeVMLDrawingReader(path)
}

func TestCommentsReader(t *testing.T) {
f := NewFile()
path := "xl/comments1.xml"
f.XLSX[path] = MacintoshCyrillicCharset
f.commentsReader(path)
}

func TestCountComments(t *testing.T) {
f := NewFile()
f.Comments["xl/comments1.xml"] = nil
assert.Equal(t, f.countComments(), 1)
}
9 changes: 9 additions & 0 deletions datavalidation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ package excelize

import (
"path/filepath"
"strings"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -85,4 +86,12 @@ func TestDataValidationError(t *testing.T) {
if !assert.NoError(t, f.SaveAs(resultFile)) {
t.FailNow()
}

// Test width invalid data validation formula.
dvRange.Formula1 = strings.Repeat("s", dataValidationFormulaStrLen+22)
assert.EqualError(t, dvRange.SetRange(10, 20, DataValidationTypeWhole, DataValidationOperatorGreaterThan), "data validation must be 0-255 characters")

// Test add data validation on no exists worksheet.
f = NewFile()
assert.EqualError(t, f.AddDataValidation("SheetN", nil), "sheet SheetN is not exist")
}
13 changes: 13 additions & 0 deletions docProps_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import (
"github.com/stretchr/testify/assert"
)

var MacintoshCyrillicCharset = []byte{0x8F, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2, 0x20, 0xEC, 0xE8, 0xF0}

func TestSetDocProps(t *testing.T) {
f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
if !assert.NoError(t, err) {
Expand All @@ -40,6 +42,11 @@ func TestSetDocProps(t *testing.T) {
assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetDocProps.xlsx")))
f.XLSX["docProps/core.xml"] = nil
assert.NoError(t, f.SetDocProps(&DocProperties{}))

// Test unsupport charset
f = NewFile()
f.XLSX["docProps/core.xml"] = MacintoshCyrillicCharset
assert.EqualError(t, f.SetDocProps(&DocProperties{}), "xml decode error: XML syntax error on line 1: invalid UTF-8")
}

func TestGetDocProps(t *testing.T) {
Expand All @@ -53,4 +60,10 @@ func TestGetDocProps(t *testing.T) {
f.XLSX["docProps/core.xml"] = nil
_, err = f.GetDocProps()
assert.NoError(t, err)

// Test unsupport charset
f = NewFile()
f.XLSX["docProps/core.xml"] = MacintoshCyrillicCharset
_, err = f.GetDocProps()
assert.EqualError(t, err, "xml decode error: XML syntax error on line 1: invalid UTF-8")
}
133 changes: 104 additions & 29 deletions excelize_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package excelize

import (
"bytes"
"compress/gzip"
"encoding/xml"
"fmt"
"image/color"
_ "image/gif"
Expand Down Expand Up @@ -184,6 +186,11 @@ func TestSaveAsWrongPath(t *testing.T) {
}
}

func TestCharsetTranscoder(t *testing.T) {
f := NewFile()
f.CharsetTranscoder(*new(charsetTranscoderFn))
}

func TestOpenReader(t *testing.T) {
_, err := OpenReader(strings.NewReader(""))
assert.EqualError(t, err, "zip: not a valid zip file")
Expand All @@ -195,6 +202,18 @@ func TestOpenReader(t *testing.T) {
0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
}))
assert.EqualError(t, err, "not support encrypted file currently")

// Test unexpected EOF.
var b bytes.Buffer
w := gzip.NewWriter(&b)
defer w.Close()
w.Flush()

r, _ := gzip.NewReader(&b)
defer r.Close()

_, err = OpenReader(r)
assert.EqualError(t, err, "unexpected EOF")
}

func TestBrokenFile(t *testing.T) {
Expand Down Expand Up @@ -924,24 +943,6 @@ func TestAddShape(t *testing.T) {
assert.NoError(t, f.SaveAs(filepath.Join("test", "TestAddShape2.xlsx")))
}

func TestAddComments(t *testing.T) {
f, err := prepareTestBook1()
if !assert.NoError(t, err) {
t.FailNow()
}

s := strings.Repeat("c", 32768)
assert.NoError(t, f.AddComment("Sheet1", "A30", `{"author":"`+s+`","text":"`+s+`"}`))
assert.NoError(t, f.AddComment("Sheet2", "B7", `{"author":"Excelize: ","text":"This is a comment."}`))

// Test add comment on not exists worksheet.
assert.EqualError(t, f.AddComment("SheetN", "B7", `{"author":"Excelize: ","text":"This is a comment."}`), "sheet SheetN is not exist")

if assert.NoError(t, f.SaveAs(filepath.Join("test", "TestAddComments.xlsx"))) {
assert.Len(t, f.GetComments(), 2)
}
}

func TestGetSheetComments(t *testing.T) {
f := NewFile()
assert.Equal(t, "", f.getSheetComments(0))
Expand Down Expand Up @@ -1005,18 +1006,37 @@ func TestAutoFilterError(t *testing.T) {
}
}

func TestSetPane(t *testing.T) {
func TestSetActiveSheet(t *testing.T) {
f := NewFile()
f.WorkBook.BookViews = nil
f.SetActiveSheet(1)
f.WorkBook.BookViews = &xlsxBookViews{WorkBookView: []xlsxWorkBookView{}}
f.Sheet["xl/worksheets/sheet1.xml"].SheetViews = &xlsxSheetViews{SheetView: []xlsxSheetView{}}
f.SetActiveSheet(1)
}

func TestSetSheetVisible(t *testing.T) {
f := NewFile()
f.WorkBook.Sheets.Sheet[0].Name = "SheetN"
assert.EqualError(t, f.SetSheetVisible("Sheet1", false), "sheet SheetN is not exist")
}

func TestGetActiveSheetIndex(t *testing.T) {
f := NewFile()
f.WorkBook.BookViews = nil
assert.Equal(t, 1, f.GetActiveSheetIndex())
}

func TestRelsWriter(t *testing.T) {
f := NewFile()
f.Relationships["xl/worksheets/sheet/rels/sheet1.xml.rel"] = &xlsxRelationships{}
f.relsWriter()
}

func TestGetSheetView(t *testing.T) {
f := NewFile()
f.SetPanes("Sheet1", `{"freeze":false,"split":false}`)
f.NewSheet("Panes 2")
f.SetPanes("Panes 2", `{"freeze":true,"split":false,"x_split":1,"y_split":0,"top_left_cell":"B1","active_pane":"topRight","panes":[{"sqref":"K16","active_cell":"K16","pane":"topRight"}]}`)
f.NewSheet("Panes 3")
f.SetPanes("Panes 3", `{"freeze":false,"split":true,"x_split":3270,"y_split":1800,"top_left_cell":"N57","active_pane":"bottomLeft","panes":[{"sqref":"I36","active_cell":"I36"},{"sqref":"G33","active_cell":"G33","pane":"topRight"},{"sqref":"J60","active_cell":"J60","pane":"bottomLeft"},{"sqref":"O60","active_cell":"O60","pane":"bottomRight"}]}`)
f.NewSheet("Panes 4")
f.SetPanes("Panes 4", `{"freeze":true,"split":false,"x_split":0,"y_split":9,"top_left_cell":"A34","active_pane":"bottomLeft","panes":[{"sqref":"A11:XFD11","active_cell":"A11","pane":"bottomLeft"}]}`)
f.SetPanes("Panes 4", "")

assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetPane.xlsx")))
_, err := f.getSheetView("SheetN", 0)
assert.EqualError(t, err, "sheet SheetN is not exist")
}

func TestConditionalFormat(t *testing.T) {
Expand Down Expand Up @@ -1207,6 +1227,61 @@ func TestAddVBAProject(t *testing.T) {
assert.NoError(t, f.SaveAs(filepath.Join("test", "TestAddVBAProject.xlsm")))
}

func TestContentTypesReader(t *testing.T) {
// Test unsupport charset.
f := NewFile()
f.ContentTypes = nil
f.XLSX["[Content_Types].xml"] = MacintoshCyrillicCharset
f.contentTypesReader()
}

func TestWorkbookReader(t *testing.T) {
// Test unsupport charset.
f := NewFile()
f.WorkBook = nil
f.XLSX["xl/workbook.xml"] = MacintoshCyrillicCharset
f.workbookReader()
}

func TestWorkSheetReader(t *testing.T) {
// Test unsupport charset.
f := NewFile()
delete(f.Sheet, "xl/worksheets/sheet1.xml")
f.XLSX["xl/worksheets/sheet1.xml"] = MacintoshCyrillicCharset
_, err := f.workSheetReader("Sheet1")
assert.EqualError(t, err, "xml decode error: XML syntax error on line 1: invalid UTF-8")

// Test on no checked worksheet.
f = NewFile()
delete(f.Sheet, "xl/worksheets/sheet1.xml")
f.XLSX["xl/worksheets/sheet1.xml"] = []byte(`<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData/></worksheet>`)
f.checked = nil
_, err = f.workSheetReader("Sheet1")
assert.NoError(t, err)
}

func TestRelsReader(t *testing.T) {
// Test unsupport charset.
f := NewFile()
rels := "xl/_rels/workbook.xml.rels"
f.Relationships[rels] = nil
f.XLSX[rels] = MacintoshCyrillicCharset
f.relsReader(rels)
}

func TestDeleteSheetFromWorkbookRels(t *testing.T) {
f := NewFile()
rels := "xl/_rels/workbook.xml.rels"
f.Relationships[rels] = nil
assert.Equal(t, f.deleteSheetFromWorkbookRels("rID"), "")
}

func TestAttrValToInt(t *testing.T) {
_, err := attrValToInt("r", []xml.Attr{
{Name: xml.Name{Local: "r"}, Value: "s"}})
assert.EqualError(t, err, `strconv.Atoi: parsing "s": invalid syntax`)
}

func prepareTestBook1() (*File, error) {
f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
if err != nil {
Expand Down
39 changes: 26 additions & 13 deletions picture.go
Original file line number Diff line number Diff line change
Expand Up @@ -477,24 +477,14 @@ func (f *File) getPicture(row, col int, drawingXML, drawingRelationships string)
var (
wsDr *xlsxWsDr
ok bool
anchor *xdrCellAnchor
deWsDr *decodeWsDr
drawRel *xlsxRelationship
deTwoCellAnchor *decodeTwoCellAnchor
)

wsDr, _ = f.drawingParser(drawingXML)
for _, anchor = range wsDr.TwoCellAnchor {
if anchor.From != nil && anchor.Pic != nil {
if anchor.From.Col == col && anchor.From.Row == row {
drawRel = f.getDrawingRelationships(drawingRelationships,
anchor.Pic.BlipFill.Blip.Embed)
if _, ok = supportImageTypes[filepath.Ext(drawRel.Target)]; ok {
ret, buf = filepath.Base(drawRel.Target), []byte(f.XLSX[strings.Replace(drawRel.Target, "..", "xl", -1)])
return
}
}
}
if ret, buf = f.getPictureFromWsDr(row, col, drawingRelationships, wsDr); len(buf) > 0 {
return
}
deWsDr = new(decodeWsDr)
if err = f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(f.readXML(drawingXML)))).
Expand All @@ -514,13 +504,36 @@ func (f *File) getPicture(row, col int, drawingXML, drawingRelationships string)
if deTwoCellAnchor.From.Col == col && deTwoCellAnchor.From.Row == row {
drawRel = f.getDrawingRelationships(drawingRelationships, deTwoCellAnchor.Pic.BlipFill.Blip.Embed)
if _, ok = supportImageTypes[filepath.Ext(drawRel.Target)]; ok {
ret, buf = filepath.Base(drawRel.Target), []byte(f.XLSX[strings.Replace(drawRel.Target, "..", "xl", -1)])
ret, buf = filepath.Base(drawRel.Target), f.XLSX[strings.Replace(drawRel.Target, "..", "xl", -1)]
return
}
}
}
}
return
}

// getPictureFromWsDr provides a function to get picture base name and raw
// content in worksheet drawing by given coordinates and drawing
// relationships.
func (f *File) getPictureFromWsDr(row, col int, drawingRelationships string, wsDr *xlsxWsDr) (ret string, buf []byte) {
var (
ok bool
anchor *xdrCellAnchor
drawRel *xlsxRelationship
)
for _, anchor = range wsDr.TwoCellAnchor {
if anchor.From != nil && anchor.Pic != nil {
if anchor.From.Col == col && anchor.From.Row == row {
drawRel = f.getDrawingRelationships(drawingRelationships,
anchor.Pic.BlipFill.Blip.Embed)
if _, ok = supportImageTypes[filepath.Ext(drawRel.Target)]; ok {
ret, buf = filepath.Base(drawRel.Target), f.XLSX[strings.Replace(drawRel.Target, "..", "xl", -1)]
return
}
}
}
}
return
}

Expand Down
Loading

0 comments on commit ae2865d

Please sign in to comment.