Skip to content

Commit

Permalink
Merge pull request #675 from noborus/fix-setdocument
Browse files Browse the repository at this point in the history
Fix DocumentLen() out-of-range checks
  • Loading branch information
noborus authored Dec 29, 2024
2 parents cc895e4 + 0e60fe9 commit a54116a
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 26 deletions.
7 changes: 4 additions & 3 deletions oviewer/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -259,11 +259,12 @@ type eventDocument struct {
}

// SetDocument fires the eventDocument event.
func (root *Root) SetDocument(docNum int) {
if docNum < 0 || docNum < root.DocumentLen() {
return
func (root *Root) SetDocument(docNum int) error {
if docNum < 0 || docNum >= root.DocumentLen() {
return ErrInvalidDocumentNum
}
root.sendDocument(docNum)
return nil
}

func (root *Root) sendDocument(docNum int) {
Expand Down
40 changes: 17 additions & 23 deletions oviewer/event_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
package oviewer

import (
"bytes"
"context"
"log"
"os"
"testing"

"github.com/gdamore/tcell/v2"
Expand Down Expand Up @@ -38,40 +35,37 @@ func TestRoot_SetDocument(t *testing.T) {
docNum int
}
tests := []struct {
name string
args args
want string
name string
args args
wantErr bool
}{
{
name: "set document",
name: "valid document number",
args: args{
docNum: 1,
docNum: 0,
},
want: "",
wantErr: false,
},
{
name: "set document",
name: "invalid document number - negative",
args: args{
docNum: -1,
},
want: "",
wantErr: true,
},
{
name: "invalid document number - out of range",
args: args{
docNum: 100,
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
root := rootHelper(t)
var buf bytes.Buffer
log.SetOutput(&buf)
defaultFlags := log.Flags()
log.SetFlags(0)
defer func() {
log.SetOutput(os.Stderr)
log.SetFlags(defaultFlags)
}()
root.SetDocument(tt.args.docNum)
got := buf.String()
if got != tt.want {
t.Errorf("Root.SetDocument() = %v, want %v", got, tt.want)
if err := root.SetDocument(tt.args.docNum); (err != nil) != tt.wantErr {
t.Errorf("Root.SetDocument() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
Expand Down
2 changes: 2 additions & 0 deletions oviewer/oviewer.go
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,8 @@ var (
ErrInvalidSGR = errors.New("invalid SGR")
// ErrNotSuuport indicates that it is not supported.
ErrNotSuuport = errors.New("not support")
// ErrInvalidDocumentNum indicates that the document number is invalid.
ErrInvalidDocumentNum = errors.New("invalid document number")
)

// This is a function of tcell.NewScreen but can be replaced with mock.
Expand Down

0 comments on commit a54116a

Please sign in to comment.