aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJulien Dessaux2021-01-18 12:33:22 +0100
committerJulien Dessaux2021-01-18 12:33:59 +0100
commit833563a66f71d7505fd0306933cbd715274ac48a (patch)
tree77bbe571981675b5a15be7cd59feeb2eaa3ba513
parentImproved menu display tests (diff)
downloadshell-game-launcher-833563a66f71d7505fd0306933cbd715274ac48a.tar.gz
shell-game-launcher-833563a66f71d7505fd0306933cbd715274ac48a.tar.bz2
shell-game-launcher-833563a66f71d7505fd0306933cbd715274ac48a.zip
Added menu input gathering
-rw-r--r--client/input.go26
-rw-r--r--client/input_test.go60
2 files changed, 86 insertions, 0 deletions
diff --git a/client/input.go b/client/input.go
new file mode 100644
index 0000000..8c814a6
--- /dev/null
+++ b/client/input.go
@@ -0,0 +1,26 @@
+package client
+
+import (
+ "bufio"
+ "os"
+
+ "github.com/pkg/errors"
+)
+
+// getValidInput returns the selected menu command as a string or an error
+func (s *State) getValidInput() (string, error) {
+ menu := s.config.Menus[s.currentMenu]
+
+ reader := bufio.NewReader(os.Stdin)
+ for {
+ input, err := reader.ReadByte()
+ if err != nil {
+ return "", errors.Wrapf(err, "Could not read byte from stdin")
+ }
+ for _, menuEntry := range menu.MenuEntries {
+ if []byte(menuEntry.Key)[0] == input {
+ return menuEntry.Action, nil
+ }
+ }
+ }
+}
diff --git a/client/input_test.go b/client/input_test.go
new file mode 100644
index 0000000..fe8feeb
--- /dev/null
+++ b/client/input_test.go
@@ -0,0 +1,60 @@
+package client
+
+import (
+ "os"
+ "shell-game-launcher/config"
+ "testing"
+)
+
+func TestGetValidInput(t *testing.T) {
+ realStdin := os.Stdin
+ t.Cleanup(func() { os.Stdin = realStdin })
+
+ // Complete menu, no input error
+ state := State{
+ config: &config.Config{
+ Menus: map[string]config.Menu{
+ "test": config.Menu{
+ Banner: "TEST TEST TEST",
+ MenuEntries: []config.MenuEntry{
+ config.MenuEntry{
+ Key: "w",
+ Label: "wait entry",
+ Action: "wait",
+ },
+ config.MenuEntry{
+ Key: "q",
+ Label: "quit entry",
+ Action: "quit",
+ },
+ },
+ },
+ },
+ },
+ currentMenu: "test",
+ login: "",
+ }
+ r, w, _ := os.Pipe()
+ os.Stdin = r
+
+ // Simply test quit entry
+ w.WriteString("q")
+ if cmd, err := state.getValidInput(); err != nil || cmd != "quit" {
+ t.Fatalf("Input handled incorrectly:\nwant: wait\ngot: %s\nerror: %s\n", cmd, err)
+ }
+ // test quit entry after wrong keys
+ w.WriteString("abcdq")
+ if cmd, err := state.getValidInput(); err != nil || cmd != "quit" {
+ t.Fatalf("Input handled incorrectly:\nwant: wait\ngot: %s\nerror: %s\n", cmd, err)
+ }
+ // test wait entry with valid quit after
+ w.WriteString("wq")
+ if cmd, err := state.getValidInput(); err != nil || cmd != "wait" {
+ t.Fatalf("Input handled incorrectly:\nwant: wait\ngot: %s\nerror: %s\n", cmd, err)
+ }
+ // test input error
+ w.Close()
+ if cmd, err := state.getValidInput(); err == nil {
+ t.Fatalf("Input handled incorrectly:\nwant: wait\ngot: %s\nerror: %s\n", cmd, err)
+ }
+}