json_test.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package ezdb
  2. import (
  3. "bytes"
  4. "testing"
  5. )
  6. func TestJSONFactory(t *testing.T) {
  7. t.Logf("creating empty student")
  8. var value any = studentMarshaler.Factory()
  9. if _, ok := value.(*Student); !ok {
  10. t.Errorf("factory did not create correct value type (expected '*Student', got '%T')", value)
  11. }
  12. }
  13. func TestJSONMarshal(t *testing.T) {
  14. for key, value := range students {
  15. t.Logf("marshaling student '%s'", key)
  16. b, err := studentMarshaler.Marshal(value)
  17. if err != nil {
  18. t.Errorf("failed to marshal student '%s' (%q)", key, err)
  19. } else if !bytes.Equal(b, studentsMarshaled[key]) {
  20. t.Errorf("student '%s' incorrectly marshaled (expected '%s', got '%s')", key, studentsMarshaled[key], b)
  21. }
  22. }
  23. }
  24. func TestJSONUnmarshal(t *testing.T) {
  25. for key, b := range studentsMarshaled {
  26. t.Logf("unmarshaling student '%s'", key)
  27. value := studentMarshaler.Factory()
  28. if err := studentMarshaler.Unmarshal(b, value); err != nil {
  29. t.Errorf("failed to unmarshal student \"%s\" (%q)", key, err)
  30. } else {
  31. if value.Name != students[key].Name {
  32. t.Errorf("student '%s' name incorrectly unmarshaled (expected '%s', got '%s')", key, students[key].Name, value.Name)
  33. }
  34. if value.Age != students[key].Age {
  35. t.Errorf("student '%s' age incorrectly unmarshaled (expected '%d', got '%d')", key, students[key].Age, value.Age)
  36. }
  37. }
  38. }
  39. }