contacts_model_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package main
  2. import "testing"
  3. func TestNewContactsStore(t *testing.T) {
  4. t.Run("normal build", func(t *testing.T) {
  5. cs, err := NewContactsStore()
  6. if err != nil {
  7. t.Fatal(err)
  8. }
  9. if cs == nil {
  10. t.Fatal("nil store created")
  11. }
  12. if len(cs.data) == 0 {
  13. t.Fatal("empty store")
  14. }
  15. })
  16. t.Run("building with missing file", func(t *testing.T) {
  17. scf := ContactsFile
  18. t.Cleanup(func() {
  19. ContactsFile = scf
  20. })
  21. ContactsFile = "badfile.json"
  22. cs, err := NewContactsStore()
  23. if err == nil || cs != nil {
  24. t.Fatalf("unexpected success creation from missing file")
  25. }
  26. })
  27. }
  28. func TestContactsStore_Load(t *testing.T) {
  29. var cs *ContactsStore
  30. t.Run("nil store", func(t *testing.T) {
  31. if err := cs.Load(); err == nil {
  32. t.Fatalf("unexpected success on loading nil store")
  33. }
  34. })
  35. cs = &ContactsStore{
  36. data: make(map[int]Contact),
  37. }
  38. t.Run("valid load", func(t *testing.T) {
  39. if err := cs.Load(); err != nil {
  40. t.Fatalf("unexpected error on loading valid store: err")
  41. }
  42. })
  43. t.Run("missing file", func(t *testing.T) {
  44. scf := ContactsFile
  45. t.Cleanup(func() {
  46. ContactsFile = scf
  47. })
  48. ContactsFile = "badfile.json"
  49. if err := cs.Load(); err == nil {
  50. t.Fatalf("unexpected success on loading missing file")
  51. }
  52. })
  53. t.Run("non-json file", func(t *testing.T) {
  54. scf := ContactsFile
  55. t.Cleanup(func() {
  56. ContactsFile = scf
  57. })
  58. ContactsFile = "contacts_model_test.go"
  59. if err := cs.Load(); err == nil {
  60. t.Fatalf("unexpected success on loading non-json file")
  61. }
  62. })
  63. }