Skip to content

Commit

Permalink
🧪 [main] finish success related unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
DenChenn committed Mar 30, 2022
1 parent 05e8619 commit 1bf3d8f
Showing 1 changed file with 72 additions and 2 deletions.
74 changes: 72 additions & 2 deletions test/success_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func TestCreateUrlEntitySuccess(t *testing.T) {
panic("MISSING_SERVER_HOST_ENV_VAR")
}

req, err := http.NewRequest("POST", serverHost+"/v1/urls/", bytes.NewBuffer(body))
req, err := http.NewRequest("POST", serverHost+"/"+constants.CURRENT_VERSION+"/urls/", bytes.NewBuffer(body))
if err != nil {
panic(err.Error())
}
Expand All @@ -57,6 +57,76 @@ func TestCreateUrlEntitySuccess(t *testing.T) {
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, 5, len(partition))
assert.Equal(t, serverHost, "http://"+partition[2])
assert.Equal(t, "v1", partition[3])
assert.Equal(t, constants.CURRENT_VERSION, partition[3])
assert.Equal(t, 27, len(partition[4]))
}

func TestRedirectToUrlSuccess(t *testing.T) {
testUrl := "test.com"

// Create url
loc, _ := time.LoadLocation(constants.TIME_ZONE)

testUrlEntity := model.UrlEntityInDB{
Url: testUrl,
ExpireAt: time.Now().In(loc).Add(time.Hour).Format(time.RFC3339),
}

body, err := json.Marshal(testUrlEntity)
if err != nil {
panic(err.Error())
}

// get server host
serverHost, isExisted := os.LookupEnv("SERVER_HOST")
if !isExisted {
panic("MISSING_SERVER_HOST_ENV_VAR")
}

req, err := http.NewRequest("POST", serverHost+"/"+constants.CURRENT_VERSION+"/urls/", bytes.NewBuffer(body))
if err != nil {
panic(err.Error())
}

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err.Error())
}

var rspEntity model.UrlEntity
err = json.NewDecoder(resp.Body).Decode(&rspEntity)
if err != nil {
panic(err.Error())
}

// test redirecting
req, err = http.NewRequest("GET", serverHost+"/"+constants.CURRENT_VERSION+"/"+rspEntity.Id, nil)
if err != nil {
panic(err.Error())
}

client = &http.Client{
// do not follow the redirect path, return 302 response directly
CheckRedirect: func(req *http.Request, via []*http.Request) error {
// skip first 301 redirect
if len(via) <= 1 {
return nil
}
return http.ErrUseLastResponse
},
}

resp, err = client.Do(req)
if err != nil {
panic(err.Error())
}
defer resp.Body.Close()

// check redirect location
rsp302Header := resp.Header.Get("Location")
partition := strings.Split(rsp302Header, "/")
rspTargetLocationUrl := partition[len(partition)-1]

assert.Equal(t, testUrl, rspTargetLocationUrl)
}

0 comments on commit 1bf3d8f

Please sign in to comment.