expect_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Copyright 2016 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // build !windows
  15. package expect
  16. import "testing"
  17. func TestExpectFunc(t *testing.T) {
  18. ep, err := NewExpect("/bin/echo", "hello world")
  19. if err != nil {
  20. t.Fatal(err)
  21. }
  22. wstr := "hello world\r\n"
  23. l, eerr := ep.ExpectFunc(func(a string) bool { return len(a) > 10 })
  24. if eerr != nil {
  25. t.Fatal(eerr)
  26. }
  27. if l != wstr {
  28. t.Fatalf(`got "%v", expected "%v"`, l, wstr)
  29. }
  30. if cerr := ep.Close(); cerr != nil {
  31. t.Fatal(cerr)
  32. }
  33. }
  34. func TestEcho(t *testing.T) {
  35. ep, err := NewExpect("/bin/echo", "hello world")
  36. if err != nil {
  37. t.Fatal(err)
  38. }
  39. l, eerr := ep.Expect("world")
  40. if eerr != nil {
  41. t.Fatal(eerr)
  42. }
  43. wstr := "hello world"
  44. if l[:len(wstr)] != wstr {
  45. t.Fatalf(`got "%v", expected "%v"`, l, wstr)
  46. }
  47. if cerr := ep.Close(); cerr != nil {
  48. t.Fatal(cerr)
  49. }
  50. if _, eerr = ep.Expect("..."); eerr == nil {
  51. t.Fatalf("expected error on closed expect process")
  52. }
  53. }
  54. func TestLineCount(t *testing.T) {
  55. ep, err := NewExpect("/usr/bin/printf", "1\n2\n3")
  56. if err != nil {
  57. t.Fatal(err)
  58. }
  59. wstr := "3"
  60. l, eerr := ep.Expect(wstr)
  61. if eerr != nil {
  62. t.Fatal(eerr)
  63. }
  64. if l != wstr {
  65. t.Fatalf(`got "%v", expected "%v"`, l, wstr)
  66. }
  67. if ep.LineCount() != 3 {
  68. t.Fatalf("got %d, expected 3", ep.LineCount())
  69. }
  70. if cerr := ep.Close(); cerr != nil {
  71. t.Fatal(cerr)
  72. }
  73. }
  74. func TestSend(t *testing.T) {
  75. ep, err := NewExpect("/usr/bin/tr", "a", "b")
  76. if err != nil {
  77. t.Fatal(err)
  78. }
  79. if err := ep.Send("a\r"); err != nil {
  80. t.Fatal(err)
  81. }
  82. if _, err := ep.Expect("b"); err != nil {
  83. t.Fatal(err)
  84. }
  85. if err := ep.Stop(); err != nil {
  86. t.Fatal(err)
  87. }
  88. }