You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.5 KiB

  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. )
  8. // newResponse creates a new HTTP response with the given data.
  9. func newResponse(statusCode int, body string) *http.Response {
  10. return &http.Response{
  11. StatusCode: statusCode,
  12. Body: ioutil.NopCloser(bytes.NewBufferString(body)),
  13. }
  14. }
  15. // matrixTripper mocks out RoundTrip and calls a registered handler instead.
  16. type matrixTripper struct {
  17. handlers map[string]func(req *http.Request) (*http.Response, error)
  18. }
  19. func newMatrixTripper() *matrixTripper {
  20. return &matrixTripper{
  21. handlers: make(map[string]func(req *http.Request) (*http.Response, error)),
  22. }
  23. }
  24. func (rt *matrixTripper) RoundTrip(req *http.Request) (*http.Response, error) {
  25. key := req.Method + " " + req.URL.Path
  26. h := rt.handlers[key]
  27. if h == nil {
  28. panic(fmt.Sprintf(
  29. "RoundTrip: Unhandled request: %s\nHandlers: %d",
  30. key, len(rt.handlers),
  31. ))
  32. }
  33. return h(req)
  34. }
  35. func (rt *matrixTripper) Handle(method, path string, handler func(req *http.Request) (*http.Response, error)) {
  36. key := method + " " + path
  37. if _, exists := rt.handlers[key]; exists {
  38. panic(fmt.Sprintf("Test handler with key %s already exists", key))
  39. }
  40. rt.handlers[key] = handler
  41. }
  42. func (rt *matrixTripper) HandlePOSTFilter(userID string) {
  43. rt.Handle("POST", "/_matrix/client/r0/user/"+userID+"/filter",
  44. func(req *http.Request) (*http.Response, error) {
  45. return newResponse(200, `{
  46. "filter_id":"abcdef"
  47. }`), nil
  48. },
  49. )
  50. }
  51. func (rt *matrixTripper) ClearHandlers() {
  52. for k := range rt.handlers {
  53. delete(rt.handlers, k)
  54. }
  55. }