mardi 20 août 2019

Can't initialize env var when testing in Golang

I am using Gin Framework with Golang, and I try to unit test a validator:

here is the function to test:

// main.go
var (
    artikUser  = os.Getenv("ARTIKUSER")
)
func init() {
    validator.SetValidationFunc("valid_prm", isValidPRM)
    if artikUser == "" {
        panic("Can't init env var")
    }
}
func isValidPRM(v interface{}, param string) error {
    st := reflect.ValueOf(v)
    if st.Kind() != reflect.String {
        return fmt.Errorf("PRM is not a string")
    }
    if len(st.String()) != 14 {
        return fmt.Errorf("wrong size of PRM, expected 14, got : %d : %s", len(st.String()), st.String())
    }
    return nil
}

and my test:

func TestIsValidPRM(t *testing.T) {
    router := setupRouter()
    w := httptest.NewRecorder()
    // PRM has 15 chars
    req, _ := http.NewRequest("GET", "/prm/135972503541522", nil)
    router.ServeHTTP(w, req)
    assert.Equal(t, 400, w.Code)
    assert.Equal(t, "wrong size of PRM, expected 14, got : 15 : 235972503541522", w.Body.String())
}

But I get:

panic: Can't init env var

I tried to put an init function in my test with:

func init() {
    artikUser  = os.Getenv("ARTIKUSER")
}

but it is not working. Can anybody tell me how should I do ?

Aucun commentaire:

Enregistrer un commentaire