rss-tools/sources/telegram/sdk_test.go (view raw)
| 1 | package telegram |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/base64" |
| 6 | "io" |
| 7 | "net/http" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | |
| 11 | "olexsmir.xyz/x/is" |
| 12 | ) |
| 13 | |
| 14 | type roundTripFunc func(*http.Request) (*http.Response, error) |
| 15 | |
| 16 | func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { |
| 17 | return f(r) |
| 18 | } |
| 19 | |
| 20 | func TestGetUpdatesHydratesPhotoBase64(t *testing.T) { |
| 21 | const token = "TEST_TOKEN" |
| 22 | seenGetFileForID := "" |
| 23 | pngData := []byte{0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x01} |
| 24 | |
| 25 | client := &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { |
| 26 | switch { |
| 27 | case strings.Contains(r.URL.Path, "/getUpdates"): |
| 28 | return jsonResponse(`{ |
| 29 | "ok": true, |
| 30 | "result": [{ |
| 31 | "update_id": 1, |
| 32 | "message": { |
| 33 | "message_id": 7, |
| 34 | "date": 1713790000, |
| 35 | "caption": "photo msg", |
| 36 | "photo": [ |
| 37 | {"file_id": "small", "width": 90, "height": 90, "file_size": 100}, |
| 38 | {"file_id": "large", "width": 1280, "height": 720, "file_size": 2048} |
| 39 | ] |
| 40 | } |
| 41 | }] |
| 42 | }`) |
| 43 | case strings.Contains(r.URL.Path, "/getFile"): |
| 44 | seenGetFileForID = r.URL.Query().Get("file_id") |
| 45 | return jsonResponse(`{"ok": true, "result": {"file_path": "photos/large.png"}}`) |
| 46 | case strings.Contains(r.URL.Path, "/file/bot"+token+"/photos/large.png"): |
| 47 | return byteResponse(pngData), nil |
| 48 | default: |
| 49 | t.Fatalf("unexpected request URL: %s", r.URL.String()) |
| 50 | return nil, nil |
| 51 | } |
| 52 | })} |
| 53 | |
| 54 | sdk := NewSDK(client, token) |
| 55 | updates, err := sdk.GetUpdates(context.Background(), 0) |
| 56 | is.Err(t, err, nil) |
| 57 | is.Equal(t, 1, len(updates)) |
| 58 | |
| 59 | msg := updates[0].Message |
| 60 | is.Equal(t, "large", seenGetFileForID) |
| 61 | is.Equal(t, "photo msg", msg.Caption) |
| 62 | is.Equal(t, base64.StdEncoding.EncodeToString(pngData), msg.PhotoBase64) |
| 63 | is.Equal(t, "image/png", msg.PhotoMIMEType) |
| 64 | } |
| 65 | |
| 66 | func jsonResponse(body string) (*http.Response, error) { |
| 67 | return &http.Response{ |
| 68 | StatusCode: http.StatusOK, |
| 69 | Body: io.NopCloser(strings.NewReader(body)), |
| 70 | Header: make(http.Header), |
| 71 | }, nil |
| 72 | } |
| 73 | |
| 74 | func byteResponse(data []byte) *http.Response { |
| 75 | return &http.Response{ |
| 76 | StatusCode: http.StatusOK, |
| 77 | Body: io.NopCloser(strings.NewReader(string(data))), |
| 78 | Header: make(http.Header), |
| 79 | } |
| 80 | } |