fake.go (2093B)
1 package jira 2 3 import ( 4 "errors" 5 "fmt" 6 "io" 7 "io/fs" 8 "log" 9 "net/http" 10 "net/http/httptest" 11 "os" 12 "path" 13 ) 14 15 // newFakeServer returns a fake JIRA server which serves projects, 16 // issues, and comments from the filesystem tree rooted at root. 17 // For an example tree, see the testdata directory. 18 // 19 // The server provides a limited read-only subset of the JIRA HTTP API 20 // intended for testing API clients. 21 // All search requests return a list of every issue, even if the JQL query is invalid. 22 // Paginated responses are not supported. 23 func newFakeServer(root string) *httptest.Server { 24 mux := http.NewServeMux() 25 mux.HandleFunc("/project", serveJSONList(path.Join(root, "project"))) 26 mux.HandleFunc("/search", serveJSONList(path.Join(root, "issue"))) 27 mux.HandleFunc("/issue", serveJSONList(path.Join(root, "issue"))) 28 mux.HandleFunc("/issue/", handleIssues(root)) 29 mux.Handle("/", http.FileServer(http.Dir(root))) 30 return httptest.NewServer(mux) 31 } 32 33 func serveJSONList(dir string) http.HandlerFunc { 34 return func(w http.ResponseWriter, req *http.Request) { 35 prefix := "[" 36 if path.Base(dir) == "issue" { 37 prefix = `{"issues": [` 38 } 39 dirs, err := os.ReadDir(dir) 40 if errors.Is(err, fs.ErrNotExist) { 41 http.NotFound(w, req) 42 return 43 } else if err != nil { 44 http.Error(w, err.Error(), http.StatusInternalServerError) 45 return 46 } 47 fmt.Fprintln(w, prefix) 48 for i, d := range dirs { 49 f, err := os.Open(path.Join(dir, d.Name())) 50 if err != nil { 51 log.Println(err) 52 return 53 } 54 if _, err := io.Copy(w, f); err != nil { 55 log.Printf("copy %s: %v", f.Name(), err) 56 } 57 f.Close() 58 if i == len(dirs)-1 { 59 break 60 } 61 fmt.Fprintln(w, ",") 62 } 63 fmt.Fprintln(w, "]}") 64 } 65 } 66 67 func handleIssues(dir string) http.HandlerFunc { 68 return func(w http.ResponseWriter, req *http.Request) { 69 if match, _ := path.Match("/issue/*/comment/*", req.URL.Path); match { 70 // ignore error; we know pattern is ok. 71 file := path.Base(req.URL.Path) 72 http.ServeFile(w, req, path.Join(dir, "comment", file)) 73 return 74 } 75 http.FileServerFS(os.DirFS(dir)).ServeHTTP(w, req) 76 } 77 }