Files
lukaszraczylo 3c04d7b0b1 feat(api): typed enums for all string-enum fields
The Telegram docs describe many string fields and parameters with
phrases like "can be ..., or ...", "must be one of ...", or "always X",
yet the generated Go API surface used raw `string` for every one of
them. Callers had to write magic strings or `string(api.ChatTypePrivate)`
to satisfy the field type. This change makes those fields typed Go
string enums emitted from the IR, so the IDE autocompletes valid values
and breaking-value drift surfaces at compile time.

Pipeline changes:

- internal/spec/ir.go: Field gains EnumValues []string. Empty for non-
  enum fields; otherwise the wire-level values in doc order, deduped.

- cmd/scrape/enums.go: extractEnumValues recognises the curly-quoted
  patterns Telegram uses ("can be either", "currently can be", "one
  of", "must be", "always X") and rejects free-text quoted refs (e.g.
  "Can be available only for X") via a tight gap check between the
  trigger phrase and the first quoted value. parse_mode parameters
  get the canonical Markdown / MarkdownV2 / HTML triple injected
  because Telegram links to a separate formatting-options section
  instead of listing values inline.

- cmd/genapi/enums.go: planEnums groups fields by sorted value-tuple,
  picks a canonical Go enum name (most-common candidate, parent-
  prefixed beats plain, shortest beats longer, alphabetical for
  determinism), resolves cross-group name collisions by parent prefix.

- cmd/genapi/emitter.go + templates: goField rewrites the field type
  to the planned enum name; multipartFieldEntry casts typed enum
  values back to string when composing the wire map; enums.tmpl now
  iterates the planned enums instead of hardcoding four hand-curated
  ones; sentinelForField produces typed-constant test fixtures.

- api/enums.gen.go: regenerated from the live IR. 66 enum types, 155
  constants. ParseMode, ChatType, MessageEntityType, ChatMember /
  MessageOrigin / PaidMedia / Background / StoryAreaType / Reaction /
  TransactionPartner / PassportElement variant Status & Type fields
  are now typed.

- api/enums.go: hand-coded UpdateType (used by transport.LongPoller).
  The Telegram docs do not enumerate Update payload kinds inline, so
  the codegen pipeline cannot synthesise this enum.

- api/types.gen.go, api/methods.gen.go, api/methods_gen_test.go: 137
  field declarations rewritten string -> typed enum.

- dispatch/, examples/: dropped every string(api.<Const>) cast. The
  HasEntity filter now takes api.MessageEntityType; ChatType filter
  compares typed values directly. ChatMember discriminator filter
  casts variant.Status (typed per variant) to string for comparison.

- internal/spec/api.json, testdata/golden/*: regenerated and
  refreshed. make regen-from-fixture is byte-deterministic across
  runs.

Renames (no compat shims; v1 pre-public):
- EntityX  -> MessageEntityTypeX  (e.g. EntityBotCommand -> MessageEntityTypeBotCommand)
- EntityStrike -> MessageEntityTypeStrikethrough (full wire name)
2026-05-09 17:55:34 +01:00

94 lines
2.6 KiB
Go

package main
import (
"bytes"
"context"
"io"
"net/http"
"strings"
"testing"
"github.com/lukaszraczylo/go-telegram/api"
"github.com/lukaszraczylo/go-telegram/client"
"github.com/lukaszraczylo/go-telegram/dispatch"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
// mockDoer satisfies client.HTTPDoer via testify/mock.
type mockDoer struct{ mock.Mock }
func (m *mockDoer) Do(r *http.Request) (*http.Response, error) {
args := m.Called(r)
if v := args.Get(0); v != nil {
return v.(*http.Response), args.Error(1)
}
return nil, args.Error(1)
}
func okResp(body string) *http.Response {
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewBufferString(body)),
Header: http.Header{"Content-Type": []string{"application/json"}},
}
}
const sendMsgResult = `{"ok":true,"result":{"message_id":1,"date":0,"chat":{"id":42,"type":"private"}}}`
func makeCtx(bot *client.Bot, upd *api.Update) *dispatch.Context {
return dispatch.NewContext(context.Background(), bot, upd)
}
func TestHandleStart_GreetsUser(t *testing.T) {
m := &mockDoer{}
m.On("Do", mock.MatchedBy(func(r *http.Request) bool {
if !strings.HasSuffix(r.URL.Path, "/sendMessage") {
return false
}
buf := new(bytes.Buffer)
_, _ = buf.ReadFrom(r.Body)
body := buf.String()
return strings.Contains(body, `"text"`) && strings.Contains(body, "Alice")
})).Return(okResp(sendMsgResult), nil)
bot := client.New("test:token", client.WithHTTPClient(m))
msg := &api.Message{
MessageID: 1,
Chat: api.Chat{ID: 42, Type: api.ChatTypePrivate},
From: &api.User{ID: 7, FirstName: "Alice"},
Text: "/start",
}
upd := &api.Update{UpdateID: 1, Message: msg}
require.NoError(t, handleStart(makeCtx(bot, upd), msg))
m.AssertExpectations(t)
}
func TestHandleEcho_RepliesWithSameText(t *testing.T) {
m := &mockDoer{}
m.On("Do", mock.MatchedBy(func(r *http.Request) bool {
if !strings.HasSuffix(r.URL.Path, "/sendMessage") {
return false
}
buf := new(bytes.Buffer)
_, _ = buf.ReadFrom(r.Body)
body := buf.String()
// text is echoed and reply_to_message_id is set to source message ID (5)
return strings.Contains(body, `"hello echo"`) &&
strings.Contains(body, `"message_id":5`)
})).Return(okResp(sendMsgResult), nil)
bot := client.New("test:token", client.WithHTTPClient(m))
msg := &api.Message{
MessageID: 5,
Chat: api.Chat{ID: 42, Type: api.ChatTypePrivate},
From: &api.User{ID: 7, FirstName: "Alice"},
Text: "hello echo",
}
upd := &api.Update{UpdateID: 1, Message: msg}
require.NoError(t, handleEcho(makeCtx(bot, upd), msg))
m.AssertExpectations(t)
}