Skip to content

Commit

Permalink
Fix ParseMode.MarshalJSON
Browse files Browse the repository at this point in the history
  • Loading branch information
koorgoo committed Jul 12, 2017
1 parent 511cd4a commit acd9ede
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 10 deletions.
25 changes: 15 additions & 10 deletions types.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//go:generate python keyboards.py
package telegram

//go:generate python keyboards.py

import (
"encoding/json"
"io"
Expand Down Expand Up @@ -209,23 +210,27 @@ type InputFile interface {

// Parse modes.
const (
ModeDefault ParseMode = iota
ModeMarkdown
ModeHTML
ModeDefault ParseMode = 0
ModeMarkdown = 1
ModeHTML = 2
)

type ParseMode int

// MarshalJSON implements json.Marshaler interface.
func (m *ParseMode) MarshalJSON() ([]byte, error) {
var s string
switch *m {
func (m ParseMode) MarshalJSON() (b []byte, err error) {
switch m {
case ModeDefault:
// ModeDefault should be evaluated as empty by json package and skipped
// in message marshalling. But empty string was a simplest solution to
// leave ParseMode a simple type.
b = []byte(`""`)
case ModeMarkdown:
s = "Markdown"
b = []byte(`"Markdown"`)
case ModeHTML:
s = "HTML"
b = []byte(`"HTML"`)
}
return []byte(s), nil
return
}

type NewMessage struct {
Expand Down
21 changes: 21 additions & 0 deletions types_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package telegram

import (
"bytes"
"encoding/json"
"testing"
)
Expand Down Expand Up @@ -29,3 +30,23 @@ func TestReplyKeyboardMarkup_UnmarshalJSON(t *testing.T) {
t.Fatalf("button: want %q, got %q", "test", s)
}
}

var parseModeTests = []struct {
Name string
Mode ParseMode
Bytes []byte
}{
{"default", ModeDefault, []byte(`""`)},
{"markdown", ModeMarkdown, []byte(`"Markdown"`)},
{"html", ModeHTML, []byte(`"HTML"`)},
}

func TestParseMode_MarshalJSON(t *testing.T) {
for _, tt := range parseModeTests {
if b, err := json.Marshal(tt.Mode); err != nil {
t.Fatalf("%s: %s", tt.Name, err)
} else if !bytes.Equal(b, tt.Bytes) {
t.Fatalf("%s: want %v, got %v", tt.Name, tt.Bytes, b)
}
}
}

0 comments on commit acd9ede

Please sign in to comment.