lundi 31 juillet 2017

trying to extend a struct type but i want nest the embbeded struct

i am trying to write some integration tests for me RESTAPI. I am at the point where i need some testdata. I thought it would be cool to use my Type: User in my Tests from my own package.

type User struct {
    ID        string `db:"id" json:"id"`
    AccountID string `db:"account_id" json:"account_id,omitempty"`
    Email     string `db:"email" json:"email"`
    Password  string `db:"password" json:"password,omitempty"`
}

I have defined a new field called valid in the fixtures/users.json.

[
{
    "AccountID": "19b849bd-f3db-4a92-8968-603e5473a9e2",
    "Email": "mail@domain.tld",
    "Password": "test116",
    "valid": false
},
{
    "AccountID": "19b849bd-f3db-4a92-8968-603e5473a9e2",
    "Email": "mail1@domain.tld",
    "Password": "test147",
    "valid": false
},
{
    "AccountID": "403fd0d1-cca1-4a7b-80fb-1a51c85fbde0",
    "Email": "mail2@domain.tld",
    "Password": "test2617",
    "valid": true
}
]

now i have this little helper method to load the json into a my struct.

func loadJSONtoStruct(target interface{}, filename string) error {

    file, err := ioutil.ReadFile(filename)
    if err != nil {
        fmt.Printf("Cant read file: %v\n", err)
        return err
    }

    err = json.Unmarshal(file, &target)
    if err != nil {
        fmt.Printf("Cant unmarshal: %v\n", err)
        return err
    }

    return nil
}

package main_test

import (
    "encoding/json"
    "fmt"
    "io/ioutil"

    . "http://ift.tt/1ontsJN"
    . "http://ift.tt/1eRuMUy"
    "http://ift.tt/2vfyiXi"
    "http://ift.tt/2tRhy5k"
)

type user struct {
    package_with-types.User
    valid bool
}

var _ = BeforeSuite(func() {
    request = gorequest.New()
    err := loadJSONtoStruct(&users, "fixtures/users.json")
    if err != nil {
        fmt.Printf("%+v", err)
    }

    fmt.Printf("%+v\n", users)
})

but i get this nested struct back

[{
User: {
    ID: AccountID: 
    Email:mail@domain.tld 
    Password:test116
} 
valid:false
},
{
User:  {
    ID: AccountID: 
    Email:mail1@domain.tld 
    Password:test147
} 
valid:false
},
{
User: {
    ID: AccountID: 
    Email:mail2@domain.tld 
    Password:test2617
} 
valid:false
}]

and i want this:

[{
    ID: AccountID: 
    Email:mail@domain.tld 
    Password:test116
    valid:false
},
{
    ID: AccountID: 
    Email:mail1@domain.tld 
    Password:test147
    valid:false
},
{
    ID: AccountID: 
    Email:mail2@domain.tld 
    Password:test2617
    valid:false
}]

what do you think? should i live with it, and use user.user.ID user.valid in my tests?

Thank you Tim

Aucun commentaire:

Enregistrer un commentaire