versioning/json_test.go

106 lines
2.3 KiB
Go
Raw Normal View History

package versioning_test
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
"git.bit5.ru/backend/versioning"
)
type structWithVersion struct {
Version versioning.Version `json:"v"`
}
func TestMarshalJSON(t *testing.T) {
cases := []struct {
version structWithVersion
expectedJson string
}{
{
version: structWithVersion{versioning.MustParseVersion("")},
expectedJson: `{"v":"0.0.0"}`,
},
{
version: structWithVersion{versioning.MustParseVersion("10")},
expectedJson: `{"v":"10.0.0"}`,
},
{
version: structWithVersion{versioning.MustParseVersion("11.2")},
expectedJson: `{"v":"11.2.0"}`,
},
{
version: structWithVersion{versioning.MustParseVersion("11.2.33")},
expectedJson: `{"v":"11.2.33"}`,
},
}
for i, c := range cases {
caseNum := i + 1
actualJson, err := json.Marshal(c.version)
require.NoError(t, err, "case #%d", caseNum)
require.EqualValues(t, []byte(c.expectedJson), actualJson, "case #%d", caseNum)
}
}
func TestUnmarshalJSON(t *testing.T) {
cases := []struct {
versionJson string
expectedVal structWithVersion
}{
{
versionJson: `{"v":"0.0.0"}`,
expectedVal: structWithVersion{versioning.MustParseVersion("")},
},
{
versionJson: `{"v":"0.0.1"}`,
expectedVal: structWithVersion{versioning.MustParseVersion("0.0.1")},
},
{
versionJson: `{"v":"0.1"}`,
expectedVal: structWithVersion{versioning.MustParseVersion("0.1.0")},
},
{
versionJson: `{"v":"1"}`,
expectedVal: structWithVersion{versioning.MustParseVersion("1.0.0")},
},
{
versionJson: `{"v":0}`,
expectedVal: structWithVersion{versioning.MustParseVersion("0.0.0")},
},
{
versionJson: `{"v":99}`,
expectedVal: structWithVersion{versioning.MustParseVersion("0.0.99")},
},
{
versionJson: `{"v":88899}`,
expectedVal: structWithVersion{versioning.MustParseVersion("0.888.99")},
},
{
versionJson: `{"v":7788899}`,
expectedVal: structWithVersion{versioning.MustParseVersion("77.888.99")},
},
}
for i, c := range cases {
caseNum := i + 1
var actualVal structWithVersion
err := json.Unmarshal([]byte(c.versionJson), &actualVal)
require.NoError(t, err, "case #%d", caseNum)
require.EqualValues(t, c.expectedVal, actualVal, "case #%d", caseNum)
}
}