Skip to content

Commit fdb4c1a

Browse files
committed
add "unit test" for ReadQuestion
1 parent 5a8f8ff commit fdb4c1a

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package tests
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"log"
7+
"net/http"
8+
"net/http/httptest"
9+
"os"
10+
"path/filepath"
11+
"question-service/handlers"
12+
"strings"
13+
"testing"
14+
15+
"cloud.google.com/go/firestore"
16+
firebase "firebase.google.com/go/v4"
17+
"github.com/go-chi/chi/v5"
18+
"github.com/joho/godotenv"
19+
"google.golang.org/api/option"
20+
)
21+
22+
func createService(t testing.TB) *handlers.Service {
23+
err := godotenv.Load(filepath.Join("../", ".env"))
24+
if err != nil {
25+
log.Fatalf("Error loading .env file")
26+
}
27+
28+
ctx := context.Background()
29+
client, err := initFirestore(ctx)
30+
31+
if err != nil {
32+
t.Fatalf("failed to initialize Firestore: %v", err)
33+
}
34+
35+
return &handlers.Service{Client: client}
36+
}
37+
38+
// initFirestore initializes the Firestore client
39+
func initFirestore(ctx context.Context) (*firestore.Client, error) {
40+
credentialsPath := "../" + os.Getenv("FIREBASE_CREDENTIAL_PATH")
41+
opt := option.WithCredentialsFile(credentialsPath)
42+
app, err := firebase.NewApp(ctx, nil, opt)
43+
if err != nil {
44+
return nil, fmt.Errorf("failed to initialize Firebase App: %v", err)
45+
}
46+
47+
client, err := app.Firestore(ctx)
48+
if err != nil {
49+
return nil, fmt.Errorf("failed to get Firestore client: %v", err)
50+
}
51+
return client, nil
52+
}
53+
54+
func Test_Read(t *testing.T) {
55+
service := createService(t)
56+
res := httptest.NewRecorder()
57+
58+
// adds chi context
59+
// https://stackoverflow.com/questions/54580582/testing-chi-routes-w-path-variables
60+
rctx := chi.NewRouteContext()
61+
rctx.URLParams.Add("docRefID", "6SdbW4Awcfm5x0UQtWmg")
62+
63+
req := httptest.NewRequest(http.MethodGet, "http://localhost:8080/questions/6SdbW4Awcfm5x0UQtWmg", strings.NewReader(""))
64+
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
65+
66+
service.ReadQuestion(res, req)
67+
68+
if res.Result().StatusCode != 200 {
69+
t.Fatalf("expected status code 200 but got %v", res.Result())
70+
}
71+
}

0 commit comments

Comments
 (0)