Browse Source

Tests, do not save empty session file to disk

Vova Tkach 6 years ago
parent
commit
7427f68d4c
2 changed files with 68 additions and 1 deletions
  1. 0 1
      session/session.go
  2. 68 0
      session/session_test.go

+ 0 - 1
session/session.go

@@ -63,7 +63,6 @@ func New(w http.ResponseWriter, r *http.Request, tmpdir string) *Session {
 		Int:    map[string]int{},
 		String: map[string]string{},
 	}
-	sess.c = true
 
 	return &sess
 }

+ 68 - 0
session/session_test.go

@@ -177,3 +177,71 @@ func TestSessionActualFile(t *testing.T) {
 		t.Fatal(err)
 	}
 }
+
+func TestSessionDoNotCreateSessionFileForDefValues(t *testing.T) {
+	// Set default values
+	request, err := http.NewRequest("GET", "/set", nil)
+	if err != nil {
+		t.Fatal(err)
+	}
+	recorder := httptest.NewRecorder()
+	http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		sess := New(w, r, "./../tmp")
+		defer sess.Close()
+		if r.URL.Path == "/set" {
+			sess.SetBool("some_bool", false)
+			sess.SetInt("some_int", 0)
+			sess.SetString("some_str", "")
+			w.Write([]byte(`ok`))
+		} else {
+			w.WriteHeader(http.StatusNotFound)
+			w.Write([]byte(`404`))
+		}
+	}).ServeHTTP(recorder, request)
+	if recorder.Body.String() != "ok" {
+		t.Fatalf("bad body response, not match")
+	}
+
+	// Remember session id
+	var sessId string
+	if len(recorder.Result().Cookies()) > 0 {
+		sessId = recorder.Result().Cookies()[0].Value
+	}
+	if sessId == "" {
+		t.Fatalf("session identifier is not defined")
+	}
+
+	// Get value
+	request, err = http.NewRequest("GET", "/get", nil)
+	if err != nil {
+		t.Fatal(err)
+	}
+	request.Header.Set("Cookie", "session="+sessId)
+	recorder = httptest.NewRecorder()
+	http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		sess := New(w, r, "./../tmp")
+		defer sess.Close()
+		if r.URL.Path == "/get" {
+			w.Write([]byte(fmt.Sprintf(
+				"(%v)(%v)(%v)",
+				sess.GetBool("some_bool", false),
+				sess.GetInt("some_int", 0),
+				sess.GetString("some_str", ""),
+			)))
+		} else {
+			w.WriteHeader(http.StatusNotFound)
+			w.Write([]byte(`404`))
+		}
+	}).ServeHTTP(recorder, request)
+	if recorder.Body.String() != "(false)(0)()" {
+		t.Fatalf("bad body response, not match")
+	}
+
+	// Check session file
+	fname := "./../tmp" + string(os.PathSeparator) + sessId
+	_, err = ioutil.ReadFile(fname)
+	if err == nil {
+		_ = os.Remove(fname)
+		t.Fatalf("session file in tmp folder do not must exists")
+	}
+}