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.

71 lines
1.8 KiB

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