~wrycode/DWCHelper

601a395b460e2666749cbf330241bb097709f8da — Nick Econopouly 1 year, 2 days ago 5b2411d
add inputNumber and corresponding tests.

One of the building blocks for the interactive helper functions.
2 files changed, 55 insertions(+), 0 deletions(-)

M lib.go
M lib_test.go
M lib.go => lib.go +30 -0
@@ 1,5 1,12 @@
package main

import (
	"io"
	"os"
	"strconv"
	"bufio"
	"fmt"
)
// Index returns the first index of the target string t, or -1 if no
// match is found
func Index(terms []string, s string) int {


@@ 44,3 51,26 @@ func Rename(terms []string, oldTerm, newTerm string) []string {
	}
	return terms
}

// inputNumber returns an int between the given upper and lower
// limits, taken from the io.Reader argument (such as os.Stdin). If
// the input is invalid, it returns 0
func inputNumber (first int, second int, r io.Reader) int {
	fmt.Printf("Your choice? (%v-%v): ",first,second)
	b := bufio.NewScanner(r)
	for b.Scan() {
		n, err := strconv.Atoi(b.Text())
		if err == nil {
			if first <= n && n <= second {
				fmt.Println()
				return n
			}
		}
		fmt.Printf("Please enter a valid number between %v and %v and hit Enter:\n", first, second)
	}
	if err := b.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "reading standard input:", err)
	}
	fmt.Println()
	return 0
}

M lib_test.go => lib_test.go +25 -0
@@ 4,6 4,7 @@ import (

	"testing"
	"encoding/json"
	"strings"
)

func TestRemove (t *testing.T) {


@@ 54,3 55,27 @@ func TestRename (t *testing.T) {
	}
	
}

func TestInputNumber(t *testing.T) {
	var inputNumberTests = []struct {
		first int // lower limit
		second int //upper limit
		choice string // user input
		result int // number returned
	}{
		{0, 5, "5", 5},
		{0, 5, "0", 0},
		{0, 5, "a\n4", 4},
		{0, 5, "asaf\nasf\n4", 4},
		{0, 5, "6\n0", 0},
		{0, 5, "-400\n0", 0},
	}

	for _, test := range inputNumberTests {
		reader := strings.NewReader(test.choice)
		result := inputNumber(test.first,test.second,reader)
		if result != test.result {
			t.Errorf("inputNumber(%v,%v) with user input: %v \n got %v, expected %v",test.first,test.second,test.choice,result,test.result)
		}
	}
}