| 1 | package exporter |
| 2 | |
| 3 | import ( |
| 4 | "net/http/httptest" |
| 5 | "os" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | ) |
| 9 | |
| 10 | func TestLuaScript(t *testing.T) { |
| 11 | for _, tst := range []struct { |
| 12 | Name string |
| 13 | Script string |
| 14 | LuaScriptReadOnly bool |
| 15 | ExpectedKeys int |
| 16 | ExpectedError bool |
| 17 | Wants []string |
| 18 | }{ |
| 19 | { |
| 20 | Name: "ok1", |
| 21 | Script: `return {"a", "11", "b", "12", "c", "13"}`, |
| 22 | ExpectedKeys: 4, |
| 23 | Wants: []string{`test_exporter_last_scrape_error{err=""} 0`, `test_script_values{filename="test.lua",key="a"} 11`, `test_script_values{filename="test.lua",key="b"} 12`, `test_script_values{filename="test.lua",key="c"} 13`, `test_script_result{filename="test.lua"} 1`}, |
| 24 | }, |
| 25 | { |
| 26 | Name: "ok2", |
| 27 | Script: `return {"key1", "6389"}`, |
| 28 | ExpectedKeys: 4, |
| 29 | Wants: []string{`test_exporter_last_scrape_error{err=""} 0`, `test_script_values{filename="test.lua",key="key1"} 6389`, `test_script_result{filename="test.lua"} 1`}, |
| 30 | }, |
| 31 | { |
| 32 | Name: "ok3", |
| 33 | Script: `return {} `, |
| 34 | ExpectedKeys: 1, |
| 35 | Wants: []string{`test_script_result{filename="test.lua"} 2`}, |
| 36 | }, |
| 37 | { |
| 38 | Name: "borked1", |
| 39 | Script: `return {"key1" BROKEN `, |
| 40 | ExpectedKeys: 1, |
| 41 | ExpectedError: true, |
| 42 | Wants: []string{`test_exporter_last_scrape_error`, `err="ERR Error compiling script`, `test_script_result{filename="test.lua"} 0`}, |
| 43 | }, |
| 44 | { |
| 45 | Name: "borked2", |
| 46 | Script: `return {"key1", "abc"}`, |
| 47 | ExpectedKeys: 1, |
| 48 | ExpectedError: true, |
| 49 | Wants: []string{`test_exporter_last_scrape_error{err="strconv.ParseFloat: parsing \"abc\": invalid syntax"} 1`, `test_script_result{filename="test.lua"} 0`}, |
| 50 | }, |
| 51 | { |
| 52 | Name: "borked3", |
| 53 | Script: `redis.call('SET', 'foo', 'bar'); return {"key1", "123"}`, |
| 54 | LuaScriptReadOnly: true, |
| 55 | ExpectedKeys: 1, |
| 56 | ExpectedError: true, |
| 57 | Wants: []string{`test_exporter_last_scrape_error`, `err="ERR Write commands are not allowed from read-only scripts.`, `test_script_result{filename="test.lua"} 0`}, |
| 58 | }, |
| 59 | } { |
| 60 | t.Run(tst.Name, func(t *testing.T) { |
| 61 | e, _ := NewRedisExporter( |
| 62 | os.Getenv("TEST_REDIS_URI"), |
| 63 | Options{ |
| 64 | Namespace: "test", |
| 65 | LuaScript: map[string][]byte{"test.lua": []byte(tst.Script)}, |
| 66 | LuaScriptReadOnly: tst.LuaScriptReadOnly, |
| 67 | }) |
| 68 | ts := httptest.NewServer(e) |
| 69 | defer ts.Close() |
| 70 | |
| 71 | body := downloadURL(t, ts.URL+"/metrics") |
| 72 | |
| 73 | for _, want := range tst.Wants { |
| 74 | if !strings.Contains(body, want) { |
| 75 | t.Errorf(`error, expected string "%s" in body, got body: \n\n%s`, want, body) |
| 76 | } |
| 77 | } |
| 78 | }) |
| 79 | } |
| 80 | } |