Skip to content

Commit

Permalink
add ErrFlagsAlreadyParsed; fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mycrEEpy committed Aug 17, 2024
1 parent f744922 commit 8d01004
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
14 changes: 9 additions & 5 deletions box_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package box_test
import (
"context"
"errors"
"flag"
"log/slog"
"net/http"
"testing"
Expand Down Expand Up @@ -53,15 +52,20 @@ func TestWithConfigFromPath(t *testing.T) {
}

func TestWithFlags(t *testing.T) {
defer func() {
if r := recover(); r != nil {
// we expect to panic due to go test already parsing flags
if !errors.Is(r.(error), box.ErrFlagsAlreadyParsed) {
t.Errorf("expected %s, got %s", box.ErrFlagsAlreadyParsed, r)
}
}
}()

b := box.New(box.WithFlags())
if b == nil {
t.Error("box.New() returned nil")
return
}

if !flag.Parsed() {
t.Errorf("flag.Parsed() should be true")
}
}

func TestWithGlobalLogger(t *testing.T) {
Expand Down
6 changes: 5 additions & 1 deletion options.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package box

import (
"errors"
"flag"
"net/http"
"os"
Expand All @@ -11,6 +12,9 @@ import (
"gopkg.in/yaml.v3"
)

// ErrFlagsAlreadyParsed indicates that the flag.Parse function has already been called.
var ErrFlagsAlreadyParsed = errors.New("flag.Parse() has already been called")

// Option is a modifier function which can alter the provided functionality of a Box.
type Option func(*Box)

Expand Down Expand Up @@ -59,7 +63,7 @@ func WithFlags() Option {
flag.StringVar(&box.Config.TLSKeyFile, "tls-key-file", box.Config.TLSKeyFile, "Webserver TLS key file")

if flag.Parsed() {
panic("flag.Parse() has already been called")
panic(ErrFlagsAlreadyParsed)
}

flag.Parse()
Expand Down

0 comments on commit 8d01004

Please sign in to comment.