Skip to content

Commit

Permalink
update with development, add tests in google_test.go
Browse files Browse the repository at this point in the history
  • Loading branch information
stella551 committed Nov 28, 2023
1 parent fefe64c commit 0fc10ec
Show file tree
Hide file tree
Showing 6 changed files with 153 additions and 6 deletions.
35 changes: 35 additions & 0 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -430,10 +430,44 @@ jobs:
name: PKG-Coverage-Report
path: profile.cov

parse_coverage:
name: Code Coverage
runs-on: ubuntu-latest
needs: [Example-Unit-Testing,CMD-Unit-Testing,PKG-Unit-Testing]
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v4

- name: Download Coverage Report
uses: actions/download-artifact@v3
with:
path: artifacts

- name: Merge Coverage Files
working-directory: artifacts
run: |
awk '!/^mode: / && FNR==1{print "mode: set"} {print}' ./CMD-Test-Report/profile.cov > merged_profile.cov
tail -n +2 ./Example-Test-Report/profile.cov >> merged_profile.cov
tail -n +2 ./PKG-Coverage-Report/profile.cov >> merged_profile.cov
- name: Parse code-coverage value
working-directory: artifacts
run: |
codeCoverage=$(go tool cover -func=merged_profile.cov | grep total | awk '{print $3}')
codeCoverage=${codeCoverage%?}
echo "CODE_COVERAGE=$codeCoverage" >> $GITHUB_ENV
- name: Check if code-coverage is greater than threshold
run: |
codeCoverage=${{ env.CODE_COVERAGE }}
codeCoverage=${codeCoverage%??}
if [[ $codeCoverage -lt 92 ]]; then echo "code coverage cannot be less than 92%, currently its ${{ env.CODE_COVERAGE }}%" && exit 1; fi;
upload_coverage:
name: Upload Coverage📊
runs-on: ubuntu-latest
needs: [Example-Unit-Testing,CMD-Unit-Testing,PKG-Unit-Testing]
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/development' }}
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v4
Expand All @@ -450,6 +484,7 @@ jobs:
tail -n +2 ./Example-Test-Report/profile.cov >> merged_profile.cov
tail -n +2 ./PKG-Coverage-Report/profile.cov >> merged_profile.cov
- name: Upload
uses: paambaati/codeclimate-action@v5.0.0
env:
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.idea
.vscode
coverage.txt
.DS_Store
4 changes: 2 additions & 2 deletions pkg/datastore/pubsub/google/google.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ func (g *GCPubSub) SubscribeWithCommit(commitFunc pubsub.CommitFunc) (*pubsub.Me
res.Topic = g.config.TopicName

handler := func(_ context.Context, m *gpubsub.Message) {
g.handleReceivedMessage(m, &res, commitFunc, cancel)
g.processMessage(m, &res, commitFunc, cancel)
}

for {
Expand All @@ -273,7 +273,7 @@ func (g *GCPubSub) SubscribeWithCommit(commitFunc pubsub.CommitFunc) (*pubsub.Me
}
}

func (g *GCPubSub) handleReceivedMessage(m *gpubsub.Message, res *pubsub.Message, commitFunc pubsub.CommitFunc,
func (g *GCPubSub) processMessage(m *gpubsub.Message, res *pubsub.Message, commitFunc pubsub.CommitFunc,
cancelFunc context.CancelFunc) {
g.logger.Debug("Received message: ", string(m.Data))
res.Value = string(m.Data)
Expand Down
44 changes: 43 additions & 1 deletion pkg/datastore/pubsub/google/google_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,46 @@ func Test_createSubscription(t *testing.T) {
}
}

func Test_Subscribe(t *testing.T) {
t.Setenv("PUBSUB_BACKEND", "google")
t.Setenv("PUBSUB_EMULATOR_HOST", "localhost:8086")

conf := config.NewGoDotEnvProvider(log.NewLogger(), "../../../../configs")

sampleData := struct {
ID string `avro:"Id"`
Name string `avro:"Name"`
Email string `avro:"Email"`
}{
ID: "1",
Name: "Rohan",
Email: "rohan@email.xyz",
}
byteData, _ := json.Marshal(sampleData)

configs := Config{
ProjectID: conf.Get("GOOGLE_PROJECT_ID"),
TopicName: conf.Get("GOOGLE_TOPIC_NAME"),
TimeoutDuration: 30,
SubscriptionDetails: &Subscription{Name: conf.Get("GOOGLE_SUBSCRIPTION_NAME")},
}

conn, err := New(&configs, log.NewMockLogger(new(bytes.Buffer)))
if err != nil {
t.Fatal(err)
}

_ = conn.PublishEvent("", sampleData, nil)

res, err := conn.Subscribe()

assert.Equal(t, res, &pubsub.Message{
Value: string(byteData),
Topic: conf.Get("GOOGLE_TOPIC_NAME")}, "Testcase Failed")

assert.Equal(t, err != nil, false, "Testcase Failed")
}

func Test_SubscribeWithCommit(t *testing.T) {
t.Setenv("PUBSUB_BACKEND", "google")
t.Setenv("PUBSUB_EMULATOR_HOST", "localhost:8086")
Expand Down Expand Up @@ -117,7 +157,9 @@ func Test_SubscribeWithCommit(t *testing.T) {

_ = conn.PublishEvent("", sampleData, nil)

res, err := conn.SubscribeWithCommit(nil)
res, err := conn.SubscribeWithCommit(func(message *pubsub.Message) (bool, bool) {
return true, false
})

assert.Equal(t, res, &pubsub.Message{
Value: string(byteData),
Expand Down
20 changes: 17 additions & 3 deletions pkg/gofr/request/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package request

import (
"bytes"

"encoding/json"
"encoding/xml"
"fmt"
Expand All @@ -12,6 +11,7 @@ import (

"github.com/golang-jwt/jwt/v4"
"github.com/gorilla/mux"
"github.com/mitchellh/mapstructure"

"gofr.dev/pkg/middleware/oauth"
)
Expand Down Expand Up @@ -125,9 +125,23 @@ func (h *HTTP) Bind(i interface{}) error {
}

cType := h.req.Header.Get("Content-type")
switch cType {
case "text/xml", "application/xml":

switch {
case strings.HasPrefix(cType, "text/xml"), strings.HasPrefix(cType, "application/xml"):
return xml.Unmarshal(body, &i)
case strings.HasPrefix(cType, "multipart/form-data"):
if err := h.req.ParseMultipartForm(0); err != nil {
return err
}

form := h.req.Form
data := make(map[string]interface{})

for key, values := range form {
data[key] = values[0]
}

return mapstructure.Decode(data, &i)
default:
return json.Unmarshal(body, &i)
}
Expand Down
55 changes: 55 additions & 0 deletions pkg/gofr/request/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ import (
ctx "context"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"reflect"
"sort"
"strings"
"testing"

"github.com/golang-jwt/jwt/v4"
Expand Down Expand Up @@ -281,24 +283,28 @@ func TestHTTP_Bind(t *testing.T) {
i interface{}
err error
isXML bool
isJSON bool
}{
{
bytes.NewBuffer([]byte(jsonData)),
resp{},
nil,
false,
true,
},
{
bytes.NewBuffer([]byte(xmlData)),
resp{},
nil,
true,
false,
},
{
malformedReader{},
nil,
fmt.Errorf("something unexpected occurred"),
false,
false,
},
}

Expand All @@ -322,6 +328,55 @@ func TestHTTP_Bind(t *testing.T) {
}
}

func TestHTTP_BindMultipartFormData(t *testing.T) {
var h HTTP

// Create a sample multipart form data request body
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)

// Add form fields
_ = writer.WriteField("username", "testuser")
_ = writer.WriteField("password", "testpass")

// Close the writer to add the boundary
writer.Close()

// Create a new request with the multipart form data
req := httptest.NewRequest(http.MethodPost, "http://dummy", body)
req.Header.Set("Content-Type", writer.FormDataContentType())

h.req = req

// Create a struct to decode the form data into
type FormData struct {
Username string `form:"username"`
Password string `form:"password"`
}

var formData FormData

// Call the Bind method
err := h.Bind(&formData)

// Assert that there is no error and the form data is correctly decoded
assert.NoError(t, err)
assert.Equal(t, "testuser", formData.Username)
assert.Equal(t, "testpass", formData.Password)

t.Run("MalformedData", func(t *testing.T) {
var hMalformed HTTP
reqMalformed := httptest.NewRequest(http.MethodPost, "http://dummy", strings.NewReader("malformed data"))
reqMalformed.Header.Set("Content-Type", "multipart/form-data")

hMalformed.req = reqMalformed
errMalformed := hMalformed.Bind(&formData)

assert.Error(t, errMalformed)
assert.Contains(t, errMalformed.Error(), "no multipart boundary param")
})
}

func TestHTTP_BindStrict(t *testing.T) {
type resp struct {
ID string
Expand Down

0 comments on commit 0fc10ec

Please sign in to comment.