Skip to content

Commit

Permalink
add test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
pm-saurabh-narkhede committed Jan 7, 2025
1 parent 6452327 commit 1ec697b
Show file tree
Hide file tree
Showing 6 changed files with 785 additions and 15 deletions.
95 changes: 95 additions & 0 deletions modules/pubmatic/openwrap/cache/gocache/compliance_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package gocache

import (
"errors"
"testing"

"github.com/golang/mock/gomock"
gocache "github.com/patrickmn/go-cache"

"github.com/prebid/prebid-server/v2/modules/pubmatic/openwrap/config"
"github.com/prebid/prebid-server/v2/modules/pubmatic/openwrap/database"
mock_database "github.com/prebid/prebid-server/v2/modules/pubmatic/openwrap/database/mock"
"github.com/prebid/prebid-server/v2/modules/pubmatic/openwrap/metrics"
mock_metrics "github.com/prebid/prebid-server/v2/modules/pubmatic/openwrap/metrics/mock"
"github.com/prebid/prebid-server/v2/modules/pubmatic/openwrap/models"
"github.com/stretchr/testify/assert"
)

func TestCache_GetGDPRCountryCodes(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockDatabase := mock_database.NewMockDatabase(ctrl)
mockEngine := mock_metrics.NewMockMetricsEngine(ctrl)
type fields struct {
cache *gocache.Cache
cfg config.Cache
db database.Database
metricEngine metrics.MetricsEngine
}
tests := []struct {
name string
fields fields
want map[string]struct{}
setup func()
wantErr bool
}{
{
name: "Valid Data present in DB, return same",
want: map[string]struct{}{
"US": {},
"LV": {},
"DE": {},
},
setup: func() {
mockDatabase.EXPECT().GetGDPRCountryCodes().Return(map[string]struct{}{
"US": {},
"LV": {},
"DE": {},
}, nil)
},
fields: fields{
cache: gocache.New(100, 100),
db: mockDatabase,
cfg: config.Cache{
CacheDefaultExpiry: 1000,
},
},
wantErr: false,
},
{
name: "Error In DB, Set Empty",
want: nil,
setup: func() {
mockDatabase.EXPECT().GetGDPRCountryCodes().Return(nil, errors.New("QUERY FAILD"))
mockEngine.EXPECT().RecordDBQueryFailure(models.GDPRCountryCodesQuery, "", "").Return()
},
fields: fields{
cache: gocache.New(100, 100),
db: mockDatabase,
cfg: config.Cache{
CacheDefaultExpiry: 1000,
},
metricEngine: mockEngine,
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.setup()
c := &cache{
cache: tt.fields.cache,
cfg: tt.fields.cfg,
db: tt.fields.db,
metricEngine: tt.fields.metricEngine,
}
got, err := c.GetGDPRCountryCodes()
if (err != nil) != tt.wantErr {
t.Errorf("cache.GetGDPRCountryCodes() error = %v, wantErr %v", err, tt.wantErr)
return
}
assert.Equal(t, tt.want, got, tt.name)
})
}
}
1 change: 1 addition & 0 deletions modules/pubmatic/openwrap/database/mysql/compliance.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ func (db *mySqlDB) GetGDPRCountryCodes() (map[string]struct{}, error) {
glog.Error("ErrRowScanFailed GetGDPRCountryCodes Err: ", err.Error())
continue
}
//TO-DO keeping case-sensitive?
countryCodes[countryCode] = struct{}{}
}

Expand Down
156 changes: 156 additions & 0 deletions modules/pubmatic/openwrap/database/mysql/compliance_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
package mysql

import (
"database/sql"
"errors"
"regexp"
"testing"

"github.com/DATA-DOG/go-sqlmock"
"github.com/prebid/prebid-server/v2/modules/pubmatic/openwrap/config"
"github.com/stretchr/testify/assert"
)

func Test_mySqlDB_GetGDPRCountryCodes(t *testing.T) {
type fields struct {
cfg config.Database
}
tests := []struct {
name string
fields fields
want map[string]struct{}
wantErr error
setup func() *sql.DB
}{
{
name: "empty query in config file",
fields: fields{
cfg: config.Database{
MaxDbContextTimeout: 100,
},
},
want: nil,
wantErr: errors.New("all expectations were already fulfilled, call to Query '' with args [] was not expected"),
setup: func() *sql.DB {
db, _, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
return db
},
},
{
name: "valid rows returned from DB",
fields: fields{
cfg: config.Database{
MaxDbContextTimeout: 100,
Queries: config.Queries{
GetGDPRCountryCodes: "^SELECT (.+) FROM KomliAdServer.geo (.+)",
},
},
},
want: map[string]struct{}{
"DE": {},
"LV": {},
},
wantErr: nil,
setup: func() *sql.DB {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
rows := sqlmock.NewRows([]string{"countrycode"}).
AddRow(`DE`).
AddRow(`LV`)
mock.ExpectQuery(regexp.QuoteMeta("^SELECT (.+) FROM KomliAdServer.geo (.+)")).WillReturnRows(rows)
return db
},
},
{
name: "no rows returned from DB",
fields: fields{
cfg: config.Database{
MaxDbContextTimeout: 100,
Queries: config.Queries{
GetGDPRCountryCodes: "^SELECT (.+) FROM KomliAdServer.geo (.+)",
},
},
},
want: map[string]struct{}{},
wantErr: nil,
setup: func() *sql.DB {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
rows := sqlmock.NewRows([]string{"countrycode"})
mock.ExpectQuery(regexp.QuoteMeta("^SELECT (.+) FROM KomliAdServer.geo (.+)")).WillReturnRows(rows)
return db
},
},
{
name: "partial row scan error",
fields: fields{
cfg: config.Database{
MaxDbContextTimeout: 1000000,
Queries: config.Queries{
GetGDPRCountryCodes: "^SELECT (.+) FROM KomliAdServer.geo (.+)",
},
},
},
want: map[string]struct{}{},
wantErr: nil,
setup: func() *sql.DB {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
rows := sqlmock.NewRows([]string{"countrycode", "extra_column"}).
AddRow(`DE`, `12`)
rows = rows.RowError(1, errors.New("error in row scan"))
mock.ExpectQuery(regexp.QuoteMeta("^SELECT (.+) FROM KomliAdServer.geo (.+)")).WillReturnRows(rows)
return db
},
},
{
name: "error in row scan",
fields: fields{
cfg: config.Database{
MaxDbContextTimeout: 100,
Queries: config.Queries{
GetGDPRCountryCodes: "^SELECT (.+) FROM KomliAdServer.geo (.+)",
},
},
},
want: nil,
wantErr: errors.New("error in row scan"),
setup: func() *sql.DB {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
rows := sqlmock.NewRows([]string{"countrycode"}).
AddRow(`DE`).
AddRow(`LV`)
rows = rows.RowError(1, errors.New("error in row scan"))
mock.ExpectQuery(regexp.QuoteMeta("^SELECT (.+) FROM KomliAdServer.geo (.+)")).WillReturnRows(rows)
return db
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
db := &mySqlDB{
conn: tt.setup(),
cfg: tt.fields.cfg,
}
got, err := db.GetGDPRCountryCodes()
if tt.wantErr == nil {
assert.NoError(t, err, tt.name)
} else {
assert.EqualError(t, err, tt.wantErr.Error(), tt.name)
}
assert.Equal(t, tt.want, got)
})
}
}
22 changes: 7 additions & 15 deletions modules/pubmatic/openwrap/geo.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (

"git.pubmatic.com/PubMatic/go-common/util"
"github.com/golang/glog"
"github.com/prebid/prebid-server/v2/modules/pubmatic/openwrap/geodb/netacuity"
"github.com/prebid/prebid-server/v2/modules/pubmatic/openwrap/metrics"
"github.com/prebid/prebid-server/v2/modules/pubmatic/openwrap/metrics/prometheus"
"github.com/prebid/prebid-server/v2/modules/pubmatic/openwrap/models"
Expand All @@ -33,18 +32,6 @@ const (
headerAccessControlAllowOriginValue = "*"
)

// geoHandler provides a handler for geo lookups.
type geoHandler struct {
geoService netacuity.NetAcuity
}

// NewGeo initializes and returns a new GeoHandler.
func NewGeo() *geoHandler {
return &geoHandler{
geoService: netacuity.NetAcuity{},
}
}

var gppSectionIDs = map[string]int{
"ca": 8,
"va": 9,
Expand All @@ -64,7 +51,7 @@ const (
)

// Handler for /geo endpoint
func (handler *geoHandler) Handler(w http.ResponseWriter, r *http.Request) {
func Handler(w http.ResponseWriter, r *http.Request) {
var pubIdStr string
metricEngine := ow.GetMetricEngine()
metricLabels := metrics.Labels{RType: models.EndpointGeo, RequestStatus: prometheus.RequestStatusOK}
Expand All @@ -77,6 +64,11 @@ func (handler *geoHandler) Handler(w http.ResponseWriter, r *http.Request) {
}
}()

if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
metricLabels.RequestStatus = prometheus.RequestStatusBadInput
return
}
pubIdStr = r.URL.Query().Get(models.PublisherID)
_, err := strconv.Atoi(pubIdStr)
if err != nil {
Expand All @@ -91,7 +83,7 @@ func (handler *geoHandler) Handler(w http.ResponseWriter, r *http.Request) {
w.Header().Set(headerContentType, headerContentTypeValue)
w.Header().Set(headerAccessControlAllowOrigin, "*")
success := false
geoInfo, _ := handler.geoService.LookUp(ip)
geoInfo, _ := ow.geoInfoFetcher.LookUp(ip)
if geoInfo != nil {
if geoInfo.ISOCountryCode != "" {
success = true
Expand Down
Loading

0 comments on commit 1ec697b

Please sign in to comment.