package domain_test

import (
	"encoding/json"
	"os"
	"testing"
)

type User struct {
	First string `json:"first"`
	Last  string `json:"last"`
}

// section: test
func Test_JSON(t *testing.T) {
	tests := []struct {
		fn   string
		user User
	}{
		{
			fn:   "testdata/valid.json",
			user: User{First: "Jenny", Last: "Smith"},
		},
		{
			fn:   "testdata/invalid.json", // this file doesn't exist
			user: User{First: "Jenny", Last: "Smith"},
		},
	}

	for _, test := range tests {
		u := &User{}
		// call a helper method to load the file and decode it
		decode(t, test.fn, u)
		if got, exp := u.First, test.user.First; got != exp {
			t.Errorf("unexpected first name.  got: %s, exp: %s", got, exp)
		}
		if got, exp := u.Last, test.user.Last; got != exp {
			t.Errorf("unexpected last name.  got: %s, exp: %s", got, exp)
		}
	}
}

// section: test

// section: helper
func decode(t *testing.T, fn string, u *User) {
	t.Helper()
	r, err := os.Open(fn)
	if err != nil {
		t.Fatal(err)
	}
	d := json.NewDecoder(r)
	err = d.Decode(u)
	if err != nil {
		t.Fatal(err)
	}
}

// section: helper
