Skip to content

Commit

Permalink
separate main part and add tests for entire logic
Browse files Browse the repository at this point in the history
  • Loading branch information
rhysd committed Jun 29, 2024
1 parent db2b043 commit affa3cc
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 12 deletions.
30 changes: 18 additions & 12 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,25 +51,31 @@ func parseOptions(out io.Writer, args []string) (*options, int) {
return o, -1
}

func main() {
opts, code := parseOptions(os.Stderr, os.Args)
if code >= 0 {
os.Exit(code)
}

func measure(opts *options, out io.Writer) error {
collected, err := collectMeasurements(opts)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
return err
}

summary, err := summarizeStartuptime(collected, opts.verbose)
if err != nil {
return err
}

fmt.Fprintf(out, "Extra options: %v\n", opts.extraArgs)
fmt.Fprintf(out, "Measured: %d times\n\n", opts.count)
summary.print(out)
return nil
}

func main() {
opts, code := parseOptions(os.Stderr, os.Args)
if code >= 0 {
os.Exit(code)
}

if err := measure(opts, os.Stdout); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}

fmt.Printf("Extra options: %v\n", opts.extraArgs)
fmt.Printf("Measured: %d times\n\n", opts.count)
summary.print(os.Stdout)
}
46 changes: 46 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"bytes"
"io"
"strings"
"testing"

Expand Down Expand Up @@ -62,3 +63,48 @@ func TestParseOptionsHelpOutput(t *testing.T) {
t.Fatal("unexpected help output to stderr:", stderr)
}
}

func TestRunMeasurementMainOK(t *testing.T) {
o := &options{
count: 1,
vimPath: "vim",
script: false,
extraArgs: []string{},
warmup: 0,
verbose: false,
}

var b bytes.Buffer
if err := measure(o, &b); err != nil {
t.Fatal(err)
}

out := b.String()
for _, want := range []string{
"Extra options: []",
"Measured: 1 times",
"Total Average:",
"Total Max:",
"Total Min:",
} {
if !strings.Contains(out, want) {
t.Errorf("output should contain %q but got %q", want, out)
}
}
}

func TestErrorWhileRunningMain(t *testing.T) {
o := &options{
count: 1,
vimPath: "this-executable-does-not-exist",
script: false,
extraArgs: []string{},
warmup: 0,
verbose: false,
}

err := measure(o, io.Discard)
if !strings.Contains(err.Error(), `failed to run "this-executable-does-not-exist"`) {
t.Fatal("error was unexpected:", err)
}
}

0 comments on commit affa3cc

Please sign in to comment.