~mendelmaleh/bin

bin/main_test.go -rw-r--r-- 2.0 KiB
2fc3ccd2Mendel E Try getting scheme from X-Forwarded-Proto 9 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main

import (
	"bytes"
	"io"
	"mime/multipart"
	"net/http"
	"net/http/httptest"
	"os"
	"testing"

	"github.com/prologic/bitcask"
	"github.com/stretchr/testify/assert"
)

var path = "db_test"

func prepareDB(path string) *bitcask.Bitcask {
	db, err := bitcask.Open(path)
	if err != nil {
		panic("unable to create/open DB")
	}

	return db
}

func cleanupDB(path string) {
	os.RemoveAll(path)
}

func TestNonExisting(t *testing.T) {
	db := prepareDB(path)
	defer cleanupDB(path)

	handler := func(w http.ResponseWriter, r *http.Request) {
		Bin(w, r, db)
	}

	req := httptest.NewRequest("GET", "http://example.com/", nil)
	val := req.URL.Query()
	val.Add("id", "nonexisting")
	req.URL.RawQuery = val.Encode()

	w := httptest.NewRecorder()
	handler(w, req)

	resp := w.Result()
	assert.Equal(t, http.StatusNotFound, resp.StatusCode)
}

func TestExisting(t *testing.T) {
	db := prepareDB(path)
	defer cleanupDB(path)

	handler := func(w http.ResponseWriter, r *http.Request) {
		Bin(w, r, db)
	}

	// post
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)

	// add id to form
	id, err := writer.CreateFormField("id")
	if err != nil {
		panic(err)
	}
	io.WriteString(id, "existing")

	// add file to form
	file, err := writer.CreateFormFile("file", "f")
	if err != nil {
		panic(err)
	}
	io.WriteString(file, "existing")

	writer.Close()

	req := httptest.NewRequest("POST", "http://example.com/", body)
	req.Header.Add("Content-Type", writer.FormDataContentType())

	w := httptest.NewRecorder()
	handler(w, req)

	resp := w.Result()
	assert.Equal(t, http.StatusCreated, resp.StatusCode)

	// get
	w, req, body = nil, nil, nil
	req = httptest.NewRequest("GET", "http://example.com/", nil)
	val := req.URL.Query()
	val.Set("id", "existing")
	req.URL.RawQuery = val.Encode()

	w = httptest.NewRecorder()
	handler(w, req)

	resp = w.Result()
	body = &bytes.Buffer{}
	body.ReadFrom(resp.Body)

	assert.Equal(t, http.StatusOK, resp.StatusCode)
	assert.Equal(t, "existing", body.String())
}