-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
5e41670
commit 0635cd4
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
package api_test | ||
|
||
import ( | ||
"bytes" | ||
"encoding/json" | ||
"net/http" | ||
"net/http/httptest" | ||
"testing" | ||
|
||
"github.com/SartajBhuvaji/api" | ||
) | ||
|
||
func TestShortenURLHandler(t *testing.T) { | ||
// create a request body | ||
reqBody := map[string]string{"url": "https://www.sartaj.me"} | ||
reqBytes, err := json.Marshal(reqBody) | ||
if err != nil { | ||
t.Fatalf("could not marshal JSON: %v", err) | ||
} | ||
|
||
// create a request | ||
req, err := http.NewRequest(http.MethodPost, "/shorten", bytes.NewBuffer(reqBytes)) | ||
if err != nil { | ||
t.Fatalf("could not create request: %v", err) | ||
} | ||
|
||
// create a response recorder | ||
rec := httptest.NewRecorder() | ||
|
||
// call the handler | ||
http.HandlerFunc(api.ShortenURLHandler).ServeHTTP(rec, req) | ||
|
||
// check the status code | ||
if rec.Code != http.StatusOK { | ||
t.Errorf("expected status OK; got %v", rec.Code) | ||
} | ||
|
||
// check the response body | ||
var respBody map[string]string | ||
if err := json.NewDecoder(rec.Body).Decode(&respBody); err != nil { | ||
t.Fatalf("could not decode JSON: %v", err) | ||
} | ||
|
||
if _, ok := respBody["short_url"]; !ok { | ||
t.Fatalf("response body does not have short_url field") | ||
} | ||
} |