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

134 lines
3.6 KiB
Go

package main
import (
"bytes"
"context"
"io"
"net/http"
"testing"
"github.com/lukaszraczylo/go-telegram/api"
"github.com/lukaszraczylo/go-telegram/client"
"github.com/lukaszraczylo/go-telegram/dispatch"
"github.com/lukaszraczylo/go-telegram/dispatch/conversation"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
// mockDoer satisfies client.HTTPDoer.
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 anyResp() *http.Response {
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewBufferString(`{"ok":true,"result":{"message_id":1,"date":0,"chat":{"id":1,"type":"private"}}}`)),
Header: http.Header{"Content-Type": []string{"application/json"}},
}
}
// msgUpd builds a message update with the given user/chat/text.
func msgUpd(userID, chatID int64, text string) api.Update {
entities := []api.MessageEntity{}
if len(text) > 0 && text[0] == '/' {
end := len(text)
for i, r := range text {
if r == ' ' {
end = i
break
}
}
entities = append(entities, api.MessageEntity{
Type: api.MessageEntityTypeBotCommand,
Offset: 0,
Length: int64(end),
})
}
return api.Update{
UpdateID: 1,
Message: &api.Message{
MessageID: 1,
From: &api.User{ID: userID},
Chat: api.Chat{ID: chatID, Type: api.ChatTypePrivate},
Text: text,
Entities: entities,
},
}
}
func makeCtx(bot *client.Bot, u *api.Update) *dispatch.Context {
return dispatch.NewContext(context.Background(), bot, u)
}
// allowAny mocks unlimited sendMessage calls.
func allowAny(m *mockDoer) {
m.On("Do", mock.Anything).Return(anyResp(), nil)
}
func TestConversation_NewBot_AsksName(t *testing.T) {
m := &mockDoer{}
allowAny(m)
bot := client.New("test:token", client.WithHTTPClient(m))
store := conversation.NewMemoryStorage()
conv := buildConv(store)
mw := conv.Dispatch(func(c *dispatch.Context, u *api.Update) error { return nil })
u := msgUpd(42, 1, "/newbot")
require.NoError(t, mw(makeCtx(bot, &u), &u))
state, err := store.Get(context.Background(), "uc:1:42")
require.NoError(t, err)
require.Equal(t, conversation.State("await_name"), state)
}
func TestConversation_NewBot_StoresName_AsksDesc(t *testing.T) {
m := &mockDoer{}
allowAny(m)
bot := client.New("test:token", client.WithHTTPClient(m))
store := conversation.NewMemoryStorage()
conv := buildConv(store)
mw := conv.Dispatch(func(c *dispatch.Context, u *api.Update) error { return nil })
// Enter conversation.
u1 := msgUpd(42, 1, "/newbot")
require.NoError(t, mw(makeCtx(bot, &u1), &u1))
// Reply with name — should advance to await_desc.
u2 := msgUpd(42, 1, "MyBot")
require.NoError(t, mw(makeCtx(bot, &u2), &u2))
state, err := store.Get(context.Background(), "uc:1:42")
require.NoError(t, err)
require.Equal(t, conversation.State("await_desc"), state)
}
func TestConversation_Cancel_EndsConversation(t *testing.T) {
m := &mockDoer{}
allowAny(m)
bot := client.New("test:token", client.WithHTTPClient(m))
store := conversation.NewMemoryStorage()
conv := buildConv(store)
mw := conv.Dispatch(func(c *dispatch.Context, u *api.Update) error { return nil })
// Enter conversation.
u1 := msgUpd(42, 1, "/newbot")
require.NoError(t, mw(makeCtx(bot, &u1), &u1))
// Cancel mid-flow.
u2 := msgUpd(42, 1, "/cancel")
require.NoError(t, mw(makeCtx(bot, &u2), &u2))
_, err := store.Get(context.Background(), "uc:1:42")
require.ErrorIs(t, err, conversation.ErrKeyNotFound, "cancel must clear state")
}