Skip to content

Commit

Permalink
Added a test with random data, and prepared for re-usability when we …
Browse files Browse the repository at this point in the history
…have a server to test
  • Loading branch information
jonasfj committed Mar 26, 2017
1 parent b4dea4b commit 8a80448
Showing 1 changed file with 51 additions and 4 deletions.
55 changes: 51 additions & 4 deletions localtunnel_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package localtunnel

import (
"bytes"
"crypto/rand"
"fmt"
"io/ioutil"
"net/http"
Expand All @@ -16,32 +18,53 @@ func (t testLog) Println(v ...interface{}) {
t.Log(v...)
}

func TestLocalTunnel(t *testing.T) {
// testLocalTunnel against server at baseURL (if given)
func testLocalTunnel(baseURL string, t *testing.T) {
// Collect some random data
random := make([]byte, 4*1024*1024) // 4 MiB
if _, err := rand.Read(random); err != nil {
t.Fatal("failed to generate random data, error:", err)
}

// Setup a test server that we wish to expose
port := 60000
server := http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("hello-world"))
if r.URL.Query().Get("random") == "true" {
w.Write(random)
} else {
w.Write([]byte("hello-world"))
}
}),
}
go server.ListenAndServe()
defer server.Close()

t.Log("setting up LocalTunnel")
lt, err := New(port, "", Options{Log: testLog{t}, MaxConnections: 2})
lt, err := New(port, "", Options{
Log: testLog{t},
MaxConnections: 2,
BaseURL: baseURL,
})
if err != nil {
t.Fatal("failed to create LocalTunnel, error: ", err)
}

// Sleep for 3s giving the server time to register
time.Sleep(3 * time.Second)

// Make http.Client with timeout of 30 seconds
client := &http.Client{
Timeout: 30 * time.Second,
}

// Let's make 3 requests for good measure
for i := 0; i < 3; i++ {
t.Log("sending test request to:", lt.URL())
var res *http.Response
res, err = http.Get(lt.URL())
res, err = client.Get(lt.URL())
if err != nil {
t.Fatal("failed to send GET request through tunnel, error: ", err)
}
Expand All @@ -61,9 +84,33 @@ func TestLocalTunnel(t *testing.T) {
}
}

t.Log("sending testing request to:", lt.URL()+"/?random=true")
var res *http.Response
res, err = client.Get(lt.URL() + "/?random=true")
if err != nil {
t.Fatal("failed to send GET request through tunnel, error: ", err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
t.Error("expected 200 ok, got status: ", res.StatusCode)
}

var data []byte
data, err = ioutil.ReadAll(res.Body)
if err != nil {
t.Fatal("failed to read response from tunnel, error: ", err)
}
if bytes.Compare(data, random) != 0 {
t.Error("unexpected random response, size:", len(data))
}

t.Log("closing LocalTunnel")
err = lt.Close()
if err != nil {
t.Error("error closing the tunnel: ", err)
}
}

func TestLocalTunnel(t *testing.T) {
testLocalTunnel("", t)
}

0 comments on commit 8a80448

Please sign in to comment.