|
| 1 | +package lua |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "io/ioutil" |
| 6 | + "os" |
| 7 | + "strings" |
| 8 | + "testing" |
| 9 | +) |
| 10 | + |
| 11 | +// TODO: add missing tests |
| 12 | + |
| 13 | +func TestReadAll(t *testing.T) { |
| 14 | + l := NewState() |
| 15 | + OpenLibraries(l) |
| 16 | + output := captureOutput(func() { |
| 17 | + DoFile(l, "fixtures/read_all.lua") |
| 18 | + }) |
| 19 | + |
| 20 | + expected := `A banana contains 75% water. |
| 21 | +The most consumed fruit in America is the banana |
| 22 | +Bananas are a good source of vitamin C, potassium and fiber. |
| 23 | +Fresh apples float because they contain 25% air. |
| 24 | +Bananas contain no fat, cholesterol or sodium.` |
| 25 | + |
| 26 | + if strings.Trim(output, "\n") != expected { |
| 27 | + t.Errorf("Expecting:\n%s\nbut received:\n%s\n", expected, output) |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +func TestReadLines(t *testing.T) { |
| 32 | + l := NewState() |
| 33 | + OpenLibraries(l) |
| 34 | + output := captureOutput(func() { |
| 35 | + DoFile(l, "fixtures/read_lines.lua") |
| 36 | + }) |
| 37 | + |
| 38 | + expected := `A banana contains 75% water. |
| 39 | +
|
| 40 | +The most consumed fruit in America is the banana` |
| 41 | + |
| 42 | + if strings.Trim(output, "\n") != expected { |
| 43 | + t.Errorf("Expecting:\n%s\nbut received:\n%s\n", expected, output) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +func TestReadNumber(t *testing.T) { |
| 48 | + l := NewState() |
| 49 | + OpenLibraries(l) |
| 50 | + output := captureOutput(func() { |
| 51 | + DoFile(l, "fixtures/read_number.lua") |
| 52 | + }) |
| 53 | + |
| 54 | + expected := "12345" |
| 55 | + if strings.Trim(output, "\n") != expected { |
| 56 | + t.Errorf("Expecting:\n%s\nbut received:\n%s\n", expected, output) |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +func TestReadBytes(t *testing.T) { |
| 61 | + l := NewState() |
| 62 | + OpenLibraries(l) |
| 63 | + output := captureOutput(func() { |
| 64 | + DoFile(l, "fixtures/read_bytes.lua") |
| 65 | + }) |
| 66 | + |
| 67 | + expected := "A banana contains 75" |
| 68 | + if strings.Trim(output, "\n") != expected { |
| 69 | + t.Errorf("Expecting:\n%s\nbut received:\n%s\n", expected, output) |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +func captureOutput(f func()) string { |
| 74 | + rescueStdout := os.Stdout |
| 75 | + r, w, _ := os.Pipe() |
| 76 | + os.Stdout = w |
| 77 | + |
| 78 | + f() |
| 79 | + |
| 80 | + w.Close() |
| 81 | + out, _ := ioutil.ReadAll(r) |
| 82 | + fmt.Println(string(out)) |
| 83 | + os.Stdout = rescueStdout |
| 84 | + return string(out) |
| 85 | +} |
0 commit comments