github.com/axw/juju@v0.0.0-20161005053422-4bd6544d08d4/cmd/juju/interact/query_test.go (about) 1 // Copyright 2016 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package interact 5 6 import ( 7 "bufio" 8 "bytes" 9 "errors" 10 "io/ioutil" 11 "strings" 12 13 "github.com/juju/testing" 14 jc "github.com/juju/testing/checkers" 15 gc "gopkg.in/check.v1" 16 ) 17 18 type Suite struct { 19 testing.IsolationSuite 20 } 21 22 var _ = gc.Suite(Suite{}) 23 24 func (Suite) TestAnswer(c *gc.C) { 25 scanner := bufio.NewScanner(strings.NewReader("hi!\n")) 26 answer, err := QueryVerify([]byte("boo: "), scanner, ioutil.Discard, nil) 27 c.Assert(err, jc.ErrorIsNil) 28 c.Assert(answer, gc.Equals, "hi!") 29 } 30 31 func (Suite) TestVerify(c *gc.C) { 32 scanner := bufio.NewScanner(strings.NewReader("hi!\nok!\n")) 33 out := bytes.Buffer{} 34 verify := func(s string) error { 35 if s == "ok!" { 36 return nil 37 } 38 return errors.New("No!") 39 } 40 answer, err := QueryVerify([]byte("boo: "), scanner, &out, verify) 41 c.Assert(err, jc.ErrorIsNil) 42 c.Assert(answer, gc.Equals, "ok!") 43 // in practice, "No!" will be on a separate line, since the cursor will get 44 // moved down by the user hitting return for their answer, but the output 45 // we generate doesn't do that itself.' 46 expected := ` 47 boo: No! 48 49 boo: 50 `[1:] 51 c.Assert(out.String(), gc.Equals, expected) 52 } 53 54 func (Suite) TestQueryMultiple(c *gc.C) { 55 scanner := bufio.NewScanner(strings.NewReader(` 56 hi! 57 ok! 58 bob 59 `[1:])) 60 verify := func(s string) error { 61 if s == "ok!" { 62 return nil 63 } 64 return errors.New("No!") 65 } 66 answer, err := QueryVerify([]byte("boo: "), scanner, ioutil.Discard, verify) 67 c.Assert(err, jc.ErrorIsNil) 68 c.Assert(answer, gc.Equals, "ok!") 69 70 answer, err = QueryVerify([]byte("name: "), scanner, ioutil.Discard, nil) 71 c.Assert(err, jc.ErrorIsNil) 72 c.Assert(answer, gc.Equals, "bob") 73 } 74 75 func (Suite) TestMatchOptions(c *gc.C) { 76 err := errors.New("err") 77 f := MatchOptions([]string{"foo", "BAR"}, err) 78 c.Check(f("foo"), jc.ErrorIsNil) 79 c.Check(f("FOO"), jc.ErrorIsNil) 80 c.Check(f("BAR"), jc.ErrorIsNil) 81 c.Check(f("bar"), jc.ErrorIsNil) 82 c.Check(f("baz"), gc.Equals, err) 83 } 84 85 func (Suite) TestFindMatch(c *gc.C) { 86 options := []string{"foo", "BAR"} 87 m, ok := FindMatch("foo", options) 88 c.Check(m, gc.Equals, "foo") 89 c.Check(ok, jc.IsTrue) 90 91 m, ok = FindMatch("FOO", options) 92 c.Check(m, gc.Equals, "foo") 93 c.Check(ok, jc.IsTrue) 94 95 m, ok = FindMatch("bar", options) 96 c.Check(m, gc.Equals, "BAR") 97 c.Check(ok, jc.IsTrue) 98 99 m, ok = FindMatch("BAR", options) 100 c.Check(m, gc.Equals, "BAR") 101 c.Check(ok, jc.IsTrue) 102 103 m, ok = FindMatch("baz", options) 104 c.Check(ok, jc.IsFalse) 105 }