Skip to content

Commit

Permalink
Add cmd tests
Browse files Browse the repository at this point in the history
- minor refactoring
  • Loading branch information
ronnyfriedland committed Mar 25, 2024
1 parent a4ec421 commit 5c970db
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 2 deletions.
21 changes: 19 additions & 2 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,32 @@ package main

import (
"flag"
"os"
"ronnyfriedland/timetracker/v2/internal/cli"
)

func main() {
mode, configPath := parseArguments()
if mode == "" {
os.Exit(0)
} else if mode == "cli" {
cli.Run(&configPath)
os.Exit(0)
} else {
os.Exit(1)
}
}

func parseArguments() (string, string) {
mode := flag.String("mode", "cli", "the application mode, available: cli")
configPath := flag.String("configpath", "/var/lib/timetracker", "the config path")
help := flag.Bool("help", false, "print this help message")
flag.Parse()

if *mode == "cli" {
cli.Run(configPath)
if *help {
flag.PrintDefaults()
return "", ""
} else {
return *mode, *configPath
}
}
62 changes: 62 additions & 0 deletions cmd/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package main

import (
"flag"
"log"
"os"
"testing"
)

func TestParameter(t *testing.T) {
oldArgs := os.Args
defer func() { os.Args = oldArgs }()

params := []string{"-configpath", "/foo", "-mode", "testmode"}

flag.CommandLine = flag.NewFlagSet("test", flag.ContinueOnError)
os.Args = append([]string{"params"}, params...)

mode, configPath := parseArguments()
if mode != "testmode" {
log.Fatalf("Got unexpected mode result, got %s, expected %s", "testmode", mode)
}
if configPath != "/foo" {
log.Fatalf("Got unexpected config path result, got %s, expected %s", "/foo", configPath)
}
}

func TestParameterDefaults(t *testing.T) {
oldArgs := os.Args
defer func() { os.Args = oldArgs }()

params := []string{}

flag.CommandLine = flag.NewFlagSet("test", flag.ContinueOnError)
os.Args = append([]string{"defaults"}, params...)

mode, configPath := parseArguments()
if mode != "cli" {
log.Fatalf("Got unexpected mode result, got %s, expected %s", "cli", mode)
}
if configPath != "/var/lib/timetracker" {
log.Fatalf("Got unexpected config path result, got %s, expected %s", "/var/lib/timetracker", configPath)
}
}

func TestParameterHelp(t *testing.T) {
oldArgs := os.Args
defer func() { os.Args = oldArgs }()

params := []string{"-help"}

flag.CommandLine = flag.NewFlagSet("test", flag.ContinueOnError)
os.Args = append([]string{"help"}, params...)

mode, configPath := parseArguments()
if mode != "" {
log.Fatalf("Got unexpected mode result, got %s, expected %s", "", mode)
}
if configPath != "" {
log.Fatalf("Got unexpected config path result, got %s, expected %s", "", configPath)
}
}

0 comments on commit 5c970db

Please sign in to comment.