package telegramtext import ( "strings" "testing" "unicode/utf8" ) // TestSplitKeepsEveryPartUnderTheLimit is the one behaviour both Telegram // senders depend on: a long body goes out in parts, none of which the Bot API // refuses, and together they still say everything. func TestSplitKeepsEveryPartUnderTheLimit(t *testing.T) { tests := []struct { name string text string max int parts int // first is the part the splitter should have started with. first string }{ {name: "a message that fits is one part", text: "short", max: MaxLen, parts: 1}, {name: "a long paragraph is cut", text: strings.Repeat("a", 9000), max: 4000, parts: 3}, {name: "a blank line ends a part", text: "one\n\n" + strings.Repeat("a", 5000), max: 4000, parts: 3, first: "one\n\n"}, {name: "a line break is preferred to the middle of a word", text: strings.Repeat("hold a line\n", 500), max: 4000}, // An emoji is two UTF-16 units, so 3000 of them are 6000: cutting by // runes alone would hand Telegram a message it rejects. {name: "emoji count twice", text: strings.Repeat("😀", 3000), max: 4000, parts: 2}, {name: "an emoji is never cut in half", text: strings.Repeat("😀", 4001)}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { max := tt.max if max == 0 { max = MaxLen } parts := Split(tt.text, max) if tt.parts > 0 && len(parts) != tt.parts { t.Fatalf("Split gave %d parts, want %d", len(parts), tt.parts) } for i, p := range parts { if units := Units(p); units > max { t.Errorf("part %d is %d units, over the %d limit", i+1, units, max) } if !utf8.ValidString(p) { t.Errorf("part %d cuts a character in half", i+1) } } if tt.first != "" && parts[0] != tt.first { t.Errorf("first part = %q, want %q", parts[0], tt.first) } if joined := strings.Join(parts, ""); joined != tt.text { t.Errorf("the parts carry %d characters, want the %d they were given", len(joined), len(tt.text)) } }) } }