Best Go-testdeep code snippet using test.Name
genericdao_mongo_test.go
Source:genericdao_mongo_test.go
...11 "github.com/btnguyen2k/godal"12 "github.com/btnguyen2k/prom/mongo"13 "go.mongodb.org/mongo-driver/bson"14)15func _createMongoConnect(t *testing.T, testName string) *mongo.MongoConnect {16 mongoDb := strings.ReplaceAll(os.Getenv("MONGO_DB"), `"`, "")17 mongoUrl := strings.ReplaceAll(os.Getenv("MONGO_URL"), `"`, "")18 if mongoDb == "" || mongoUrl == "" {19 t.Skipf("%s skipped", testName)20 return nil21 }22 mc, _ := mongo.NewMongoConnectWithPoolOptions(mongoUrl, mongoDb, 10000, &mongo.MongoPoolOpts{23 ConnectTimeout: 10 * time.Second,24 SocketTimeout: 10 * time.Second,25 ServerSelectionTimeout: 10 * time.Second,26 })27 return mc28}29func prepareMongoCollection(mc *mongo.MongoConnect, collectionName string) error {30 if err := mc.GetCollection(collectionName).Drop(nil); err != nil {31 return err32 }33 if err := mc.CreateCollection(collectionName); err != nil {34 return err35 }36 indexes := []interface{}{37 map[string]interface{}{38 "key": map[string]interface{}{"username": 1},39 "name": "uidx_username",40 "unique": true,41 },42 }43 if _, err := mc.CreateCollectionIndexes(collectionName, indexes); err != nil {44 return err45 }46 return nil47}48func createDaoMongo(mc *mongo.MongoConnect, collectionName string) *UserDaoMongo {49 dao := &UserDaoMongo{collectionName: collectionName}50 dao.GenericDaoMongo = NewGenericDaoMongo(mc, godal.NewAbstractGenericDao(dao))51 dao.SetTxModeOnWrite(false)52 return dao53}54type UserBoMongo struct {55 Id string `json:"_id"`56 Username string `json:"username"`57 Name string `json:"name"`58 Version int `json:"version"`59 Active bool `json:"active"`60 Created time.Time `json:"created"`61}62const (63 testMongoCollectionName = "test_user"64 fieldId = "_id"65 testTimeZone = "Asia/Ho_Chi_Minh"66)67type UserDaoMongo struct {68 *GenericDaoMongo69 collectionName string70}71// GdaoCreateFilter implements godal.IGenericDao.GdaoCreateFilter.72func (dao *UserDaoMongo) GdaoCreateFilter(collectionName string, bo godal.IGenericBo) godal.FilterOpt {73 if collectionName == dao.collectionName {74 return godal.FilterOptFieldOpValue{FieldName: fieldId, Operator: godal.FilterOpEqual, Value: bo.GboGetAttrUnsafe(fieldId, reddo.TypeString)}75 }76 return nil77}78func (dao *UserDaoMongo) toGbo(u *UserBoMongo) godal.IGenericBo {79 gbo := godal.NewGenericBo()80 if err := gbo.GboImportViaJson(u); err != nil {81 return nil82 }83 return gbo84}85func (dao *UserDaoMongo) toUser(gbo godal.IGenericBo) *UserBoMongo {86 bo := UserBoMongo{}87 if err := gbo.GboTransferViaJson(&bo); err != nil {88 return nil89 }90 return &bo91}92/*----------------------------------------------------------------------*/93func _initDao(t *testing.T, testName, collectionName string) *UserDaoMongo {94 mc := _createMongoConnect(t, testName)95 return createDaoMongo(mc, collectionName)96}97func _compareUsers(t *testing.T, name string, expected, target *UserBoMongo) {98 if target == nil {99 t.Fatalf("%s failed: target is nil", name)100 }101 if target.Id != expected.Id {102 t.Fatalf("%s failed: field [Id] mismatched - %#v / %#v", name, expected.Id, target.Id)103 }104 if target.Username != expected.Username {105 t.Fatalf("%s failed: field [Username] mismatched - %#v / %#v", name, expected.Username, target.Username)106 }107 if target.Name != expected.Name {108 t.Fatalf("%s failed: field [Name] mismatched - %#v / %#v", name, expected.Name, target.Name)109 }110 if target.Version != expected.Version {111 t.Fatalf("%s failed: field [Version] mismatched - %#v / %#v", name, expected.Version, target.Version)112 }113 if target.Active != expected.Active {114 t.Fatalf("%s failed: field [Active] mismatched - %#v / %#v", name, expected.Active, target.Active)115 }116 layout := time.RFC3339117 loc, _ := time.LoadLocation(testTimeZone)118 if target.Created.In(loc).Format(layout) != expected.Created.In(loc).Format(layout) {119 t.Fatalf("%s failed: field [Created] mismatched - %#v / %#v", name, expected.Created.Format(layout), target.Created.Format(layout))120 }121 // if (expected.ValPInt != nil && (target.ValPInt == nil || *target.ValPInt != *expected.ValPInt)) || (expected.ValPInt == nil && target.ValPInt != nil) {122 // t.Fatalf("%s failed: field [PInt] mismatched - %#v / %#v", name, expected.ValPInt, target.ValPInt)123 // }124 // if (expected.ValPFloat != nil && (target.ValPFloat == nil || *target.ValPFloat != *expected.ValPFloat)) || (expected.ValPFloat == nil && target.ValPFloat != nil) {125 // t.Fatalf("%s failed: field [PFloat] mismatched - %#v / %#v", name, expected.ValPFloat, target.ValPFloat)126 // }127 // if (expected.ValPString != nil && (target.ValPString == nil || *target.ValPString != *expected.ValPString)) || (expected.ValPString == nil && target.ValPString != nil) {128 // t.Fatalf("%s failed: field [PString] mismatched - %#v / %#v", name, expected.ValPString, target.ValPString)129 // }130 // if (expected.ValPTime != nil && (target.ValPTime == nil || target.ValPTime.In(loc).Format(layout) != expected.ValPTime.In(loc).Format(layout))) || (expected.ValPTime == nil && target.ValPTime != nil) {131 // t.Fatalf("%s failed: field [PTime] mismatched - %#v / %#v", name, expected.ValPTime, target.ValPTime)132 // }133}134func TestGenericRowMapperMongo_ColumnsList(t *testing.T) {135 testName := "TestGenericRowMapperMongo_ColumnsList"136 table := "table"137 rowmapper := &GenericRowMapperMongo{}138 colList := rowmapper.ColumnsList(table)139 if len(colList) != 1 || colList[0] != "*" {140 t.Fatalf("%s failed: %v", testName, colList)141 }142}143func testToBo(t *testing.T, name string, rowmapper godal.IRowMapper, table string, row interface{}) {144 colA, colB, colC, col1, col2 := "cola", "ColB", "colC", "Col1", "coL2"145 valA, valB, val1, val2 := "a", "B", int64(1), int64(2)146 bo, err := rowmapper.ToBo(table, row)147 if err != nil || bo == nil {148 t.Fatalf("%s failed: %s / %v", name, err, bo)149 }150 if bo.GboGetAttrUnsafe(colA, reddo.TypeString) != valA ||151 bo.GboGetAttrUnsafe(colB, reddo.TypeString) != valB ||152 bo.GboGetAttrUnsafe(colC, reddo.TypeString) != nil ||153 bo.GboGetAttrUnsafe(col1, reddo.TypeInt).(int64) != val1 ||154 bo.GboGetAttrUnsafe(col2, reddo.TypeInt).(int64) != val2 {155 t.Fatalf("%s failed, Row: %v - Bo: %v", name, row, bo)156 }157}158func TestGenericRowMapperMongo_ToBo(t *testing.T) {159 name := "TestGenericRowMapperMongo_ToBo"160 table := "table"161 colA, colB, col1, col2 := "cola", "ColB", "Col1", "coL2"162 valA, valB, val1, val2 := "a", "B", int64(1), int64(2)163 rowmapper := &GenericRowMapperMongo{}164 if v, err := rowmapper.ToBo("", time.Time{}); v != nil || err == nil {165 t.Fatalf("%s failed: %#v / %s", name, v, err)166 }167 {168 row := map[string]interface{}{colA: valA, colB: valB, col1: val1, col2: val2}169 testToBo(t, name, rowmapper, table, row)170 testToBo(t, name, rowmapper, table, &row)171 testToBo(t, name, rowmapper, table+"-not-exists", row)172 row2 := &row173 testToBo(t, name, rowmapper, table, &row2)174 }175 {176 row := fmt.Sprintf(`{"%s": "%v", "%s": "%v", "%s": %v, "%s": %v}`, colA, valA, colB, valB, col1, val1, col2, val2)177 testToBo(t, name, rowmapper, table, row)178 testToBo(t, name, rowmapper, table, &row)179 testToBo(t, name, rowmapper, table+"-not-exists", row)180 row2 := &row181 testToBo(t, name, rowmapper, table, &row2)182 }183 {184 row := []byte(fmt.Sprintf(`{"%s": "%v", "%s": "%v", "%s": %v, "%s": %v}`, colA, valA, colB, valB, col1, val1, col2, val2))185 testToBo(t, name, rowmapper, table, row)186 testToBo(t, name, rowmapper, table, &row)187 testToBo(t, name, rowmapper, table+"-not-exists", row)188 row2 := &row189 testToBo(t, name, rowmapper, table, &row2)190 }191 {192 var row interface{} = nil193 if bo, err := rowmapper.ToBo(table, row); err != nil || bo != nil {194 t.Fatalf("%s failed: %s / %v", name, err, bo)195 }196 if bo, err := rowmapper.ToBo(table, &row); err != nil || bo != nil {197 t.Fatalf("%s failed: %s / %v", name, err, bo)198 }199 row2 := &row200 if bo, err := rowmapper.ToBo(table, &row2); err != nil || bo != nil {201 t.Fatalf("%s failed: %s / %v", name, err, bo)202 }203 }204 {205 var row *string = nil206 if bo, err := rowmapper.ToBo(table, row); err != nil || bo != nil {207 t.Fatalf("%s failed: %s / %v", name, err, bo)208 }209 if bo, err := rowmapper.ToBo(table, &row); err != nil || bo != nil {210 t.Fatalf("%s failed: %s / %v", name, err, bo)211 }212 row2 := &row213 if bo, err := rowmapper.ToBo(table, &row2); err != nil || bo != nil {214 t.Fatalf("%s failed: %s / %v", name, err, bo)215 }216 }217 {218 var row []byte = nil219 if bo, err := rowmapper.ToBo(table, row); err != nil || bo != nil {220 t.Fatalf("%s failed: %s / %v", name, err, bo)221 }222 if bo, err := rowmapper.ToBo(table, &row); err != nil || bo != nil {223 t.Fatalf("%s failed: %s / %v", name, err, bo)224 }225 row2 := &row226 if bo, err := rowmapper.ToBo(table, &row2); err != nil || bo != nil {227 t.Fatalf("%s failed: %s / %v", name, err, bo)228 }229 }230 {231 var row *[]byte = nil232 if bo, err := rowmapper.ToBo(table, row); err != nil || bo != nil {233 t.Fatalf("%s failed: %s / %v", name, err, bo)234 }235 if bo, err := rowmapper.ToBo(table, &row); err != nil || bo != nil {236 t.Fatalf("%s failed: %s / %v", name, err, bo)237 }238 row2 := &row239 if bo, err := rowmapper.ToBo(table, &row2); err != nil || bo != nil {240 t.Fatalf("%s failed: %s / %v", name, err, bo)241 }242 }243}244func TestGenericRowMapperMongo_ToRow(t *testing.T) {245 name := "TestGenericRowMapperMongo_ToRow"246 table := "table"247 colA, colB, colC, col1, col2 := "cola", "ColB", "colC", "Col1", "coL2"248 valA, valB, val1, val2 := "a", "B", int64(1), int64(2)249 rowmapper := &GenericRowMapperMongo{}250 if v, err := rowmapper.ToRow("", nil); v != nil || err != nil {251 t.Fatalf("%s failed: %#v / %s", name, v, err)252 }253 {254 bo := godal.NewGenericBo()255 bo.GboSetAttr(colA, valA)256 bo.GboSetAttr(colB, valB)257 bo.GboSetAttr(col1, val1)258 bo.GboSetAttr(col2, val2)259 row, err := rowmapper.ToRow(table, bo)260 if err != nil || row == nil {261 t.Fatalf("%s failed: %s / %v", name, err, row)262 }263 if bo.GboGetAttrUnsafe(colA, reddo.TypeString) != valA ||264 bo.GboGetAttrUnsafe(colB, reddo.TypeString) != valB ||265 bo.GboGetAttrUnsafe(colC, reddo.TypeString) != nil ||266 bo.GboGetAttrUnsafe(col1, reddo.TypeInt).(int64) != val1 ||267 bo.GboGetAttrUnsafe(col2, reddo.TypeInt).(int64) != val2 {268 t.Fatalf("%s failed, Row: %v - Bo: %v", name, row, bo)269 }270 }271}272func TestGenericRowMapperMongo_ToDbColName(t *testing.T) {273 name := "TestGenericRowMapperMongo_ToDbColName"274 table := "table"275 colA, colB := "cola", "ColB"276 rowMapper := &GenericRowMapperMongo{}277 if fieldName := rowMapper.ToDbColName(table, colA); fieldName != colA {278 t.Fatalf("%s failed, expect %#v but received %#v", name, colA, fieldName)279 }280 if fieldName := rowMapper.ToDbColName("table", colB); fieldName != colB {281 t.Fatalf("%s failed, expect %#v but received %#v", name, colB, fieldName)282 }283}284func TestGenericRowMapperMongo_ToBoFieldName(t *testing.T) {285 name := "TestGenericRowMapperMongo_ToBoFieldName"286 table := "table"287 colA, colB := "cola", "ColB"288 rowMapper := &GenericRowMapperMongo{}289 if colName := rowMapper.ToBoFieldName(table, colA); colName != colA {290 t.Fatalf("%s failed, expect %#v but received %#v", name, colA, colName)291 }292 if colName := rowMapper.ToBoFieldName("table", colB); colName != colB {293 t.Fatalf("%s failed, expect %#v but received %#v", name, colB, colName)294 }295}296func TestNewGenericDaoMongo(t *testing.T) {297 name := "TestNewGenericDaoMongo"298 dao := _initDao(t, name, testMongoCollectionName)299 if dao == nil {300 t.Fatalf("%s failed: nil", name)301 }302 defer dao.mongoConnect.Close(nil)303}304type _testSetupOrTeardownFunc func(t *testing.T, testName string)305func setupTest(t *testing.T, testName string, extraSetupFunc, extraTeardownFunc _testSetupOrTeardownFunc) func(t *testing.T) {306 if extraSetupFunc != nil {307 extraSetupFunc(t, testName)308 }309 return func(t *testing.T) {310 if extraTeardownFunc != nil {311 extraTeardownFunc(t, testName)312 }313 }314}315var _setupTestDaoAndCollection _testSetupOrTeardownFunc = func(t *testing.T, testName string) {316 testDao = _initDao(t, testName, testMongoCollectionName)317 err := prepareMongoCollection(testDao.GetMongoConnect(), testDao.collectionName)318 if err != nil {319 t.Fatalf("%s failed: %s", testName+"/prepareMongoCollection", err)320 }321}322var _teardownTest _testSetupOrTeardownFunc = func(t *testing.T, testName string) {323 if testDao != nil {324 testDao.GetMongoConnect().Close(nil)325 }326}327var testDao *UserDaoMongo328func TestGenericDaoMongo_SetGetMongoConnect(t *testing.T) {329 testName := "TestGenericDaoMongo_SetGetMongoConnect"330 teardownTest := setupTest(t, testName, _setupTestDaoAndCollection, _teardownTest)331 defer teardownTest(t)332 testDao.mongoConnect.Close(nil)333 mc := _createMongoConnect(t, testName)334 testDao.SetMongoConnect(mc)335 if testDao.GetMongoConnect() != mc {336 t.Fatalf("%s failed", testName)337 }338}339func TestGenericDaoMongo_SetGetTxModeOnWrite(t *testing.T) {340 testName := "TestGenericDaoMongo_SetGetTxModeOnWrite"341 teardownTest := setupTest(t, testName, _setupTestDaoAndCollection, _teardownTest)342 defer teardownTest(t)343 txModeOnWrite := testDao.GetTxModeOnWrite()344 testDao.SetTxModeOnWrite(!txModeOnWrite)345 txModeOnWrite2 := testDao.GetTxModeOnWrite()346 if txModeOnWrite == txModeOnWrite2 {347 t.Fatalf("%s failed", testName)348 }349}350func TestGenericDaoMongo_BuildFilter(t *testing.T) {351 testName := "TestGenericDaoMongo_BuildFilter"352 teardownTest := setupTest(t, testName, _setupTestDaoAndCollection, _teardownTest)353 defer teardownTest(t)354 var input godal.FilterOpt355 var output, expected bson.M356 var err error357 input = nil358 expected = nil359 if output, err = testDao.BuildFilter(testMongoCollectionName, input); err != nil || !reflect.DeepEqual(expected, output) {360 t.Fatalf("%s failed: expected %#v but received %#v / Error: %s", testName, expected, output, err)361 }362 // _n := expression.Name("field")363 // _v := expression.Value("value")364 optsList := []godal.FilterOperator{godal.FilterOpEqual, godal.FilterOpNotEqual, godal.FilterOpGreater, godal.FilterOpGreaterOrEqual, godal.FilterOpLess, godal.FilterOpLessOrEqual}365 expectedList := []bson.M{{"field": bson.M{"$eq": 0}}, {"field": bson.M{"$ne": 1}}, {"field": bson.M{"$gt": 2}}, {"field": bson.M{"$gte": 3}}, {"field": bson.M{"$lt": 4}}, {"field": bson.M{"$lte": 5}}}366 for i, opt := range optsList {367 expected = expectedList[i]368 input = godal.FilterOptFieldOpValue{FieldName: "field", Operator: opt, Value: i}369 if output, err = testDao.BuildFilter(testMongoCollectionName, input); err != nil || !reflect.DeepEqual(expected, output) {370 t.Fatalf("%s failed: expected %#v but received %#v / Error: %s", testName, expected, output, err)371 }372 input = &godal.FilterOptFieldOpValue{FieldName: "field", Operator: opt, Value: i}373 if output, err = testDao.BuildFilter(testMongoCollectionName, input); err != nil || !reflect.DeepEqual(expected, output) {374 t.Fatalf("%s failed: expected %#v but received %#v / Error: %s", testName, expected, output, err)375 }376 }377 expected = bson.M{"field": bson.M{"$eq": nil}}378 input = godal.FilterOptFieldIsNull{FieldName: "field"}379 if output, err = testDao.BuildFilter(testMongoCollectionName, input); err != nil || !reflect.DeepEqual(expected, output) {380 t.Fatalf("%s failed: expected %#v but received %#v / Error: %s", testName, expected, output, err)381 }382 input = &godal.FilterOptFieldIsNull{FieldName: "field"}383 if output, err = testDao.BuildFilter(testMongoCollectionName, input); err != nil || !reflect.DeepEqual(expected, output) {384 t.Fatalf("%s failed: expected %#v but received %#v / Error: %s", testName, expected, output, err)385 }386 expected = bson.M{"field": bson.M{"$ne": nil}}387 input = godal.FilterOptFieldIsNotNull{FieldName: "field"}388 if output, err = testDao.BuildFilter(testMongoCollectionName, input); err != nil || !reflect.DeepEqual(expected, output) {389 t.Fatalf("%s failed: expected %#v but received %#v / Error: %s", testName, expected, output, err)390 }391 input = &godal.FilterOptFieldIsNotNull{FieldName: "field"}392 if output, err = testDao.BuildFilter(testMongoCollectionName, input); err != nil || !reflect.DeepEqual(expected, output) {393 t.Fatalf("%s failed: expected %#v but received %#v / Error: %s", testName, expected, output, err)394 }395 expected = bson.M{"$and": bson.A{bson.M{"field1": bson.M{"$gt": 1}}, bson.M{"field2": bson.M{"$lte": "3"}}}}396 input = godal.FilterOptAnd{Filters: []godal.FilterOpt{397 godal.FilterOptFieldOpValue{FieldName: "field1", Operator: godal.FilterOpGreater, Value: 1},398 godal.FilterOptFieldOpValue{FieldName: "field2", Operator: godal.FilterOpLessOrEqual, Value: "3"}}}399 if output, err = testDao.BuildFilter(testMongoCollectionName, input); err != nil || !reflect.DeepEqual(expected, output) {400 t.Fatalf("%s failed: expected %#v but received %#v / Error: %s", testName, expected, output, err)401 }402 input = &godal.FilterOptAnd{Filters: []godal.FilterOpt{403 godal.FilterOptFieldOpValue{FieldName: "field1", Operator: godal.FilterOpGreater, Value: 1},404 godal.FilterOptFieldOpValue{FieldName: "field2", Operator: godal.FilterOpLessOrEqual, Value: "3"}}}405 if output, err = testDao.BuildFilter(testMongoCollectionName, input); err != nil || !reflect.DeepEqual(expected, output) {406 t.Fatalf("%s failed: expected %#v but received %#v / Error: %s", testName, expected, output, err)407 }408 expected = bson.M{"$or": bson.A{bson.M{"field3": bson.M{"$gt": "5"}}, bson.M{"field4": bson.M{"$lte": 7}}}}409 input = godal.FilterOptOr{Filters: []godal.FilterOpt{410 godal.FilterOptFieldOpValue{FieldName: "field3", Operator: godal.FilterOpGreater, Value: "5"},411 godal.FilterOptFieldOpValue{FieldName: "field4", Operator: godal.FilterOpLessOrEqual, Value: 7}}}412 if output, err = testDao.BuildFilter(testMongoCollectionName, input); err != nil || !reflect.DeepEqual(expected, output) {413 t.Fatalf("%s failed: expected %#v but received %#v / Error: %s", testName, expected, output, err)414 }415 input = &godal.FilterOptOr{Filters: []godal.FilterOpt{416 godal.FilterOptFieldOpValue{FieldName: "field3", Operator: godal.FilterOpGreater, Value: "5"},417 godal.FilterOptFieldOpValue{FieldName: "field4", Operator: godal.FilterOpLessOrEqual, Value: 7}}}418 if output, err = testDao.BuildFilter(testMongoCollectionName, input); err != nil || !reflect.DeepEqual(expected, output) {419 t.Fatalf("%s failed: expected %#v but received %#v / Error: %s", testName, expected, output, err)420 }421}422func TestGenericDaoMongo_GdaoDelete(t *testing.T) {423 testName := "TestGenericDaoMongo_GdaoDelete"424 teardownTest := setupTest(t, testName, _setupTestDaoAndCollection, _teardownTest)425 defer teardownTest(t)426 user := &UserBoMongo{427 Id: "1",428 Username: "btnguyen2k",429 Name: "Thanh Nguyen",430 Version: int(time.Now().Unix()),431 Active: false,432 Created: time.Now(),433 }434 _, err := testDao.GdaoCreate(testDao.collectionName, testDao.toGbo(user))435 if err != nil {436 t.Fatalf("%s failed: %s", testName+"/GdaoCreate", err)437 }438 filterUser := &UserBoMongo{Id: "2"}439 if numRows, err := testDao.GdaoDelete(testDao.collectionName, testDao.toGbo(filterUser)); err != nil {440 t.Fatalf("%s failed: %s", testName, err)441 } else if numRows != 0 {442 t.Fatalf("%s failed: expected %#v row(s) deleted but received %#v", testName, 0, numRows)443 }444 if numRows, err := testDao.GdaoDelete(testDao.collectionName, testDao.toGbo(user)); err != nil {445 t.Fatalf("%s failed: %s", testName, err)446 } else if numRows != 1 {447 t.Fatalf("%s failed: expected %#v row(s) deleted but received %#v", testName, 1, numRows)448 }449 filterUser = &UserBoMongo{Id: user.Id}450 if u, err := testDao.GdaoFetchOne(testDao.collectionName, testDao.GdaoCreateFilter(testDao.collectionName, testDao.toGbo(filterUser))); err != nil {451 t.Fatalf("%s failed: %s", testName+"/GdaoFetchOne", err)452 } else if u != nil {453 t.Fatalf("%s failed: non-nil", testName+"/GdaoFetchOne")454 }455}456func TestGenericDaoMongo_GdaoDeleteMany(t *testing.T) {457 testName := "TestGenericDaoMongo_GdaoDeleteMany"458 teardownTest := setupTest(t, testName, _setupTestDaoAndCollection, _teardownTest)459 defer teardownTest(t)460 filter := &godal.FilterOptOr{Filters: []godal.FilterOpt{461 &godal.FilterOptFieldOpValue{FieldName: fieldId, Operator: godal.FilterOpGreaterOrEqual, Value: "8"},462 &godal.FilterOptFieldOpValue{FieldName: fieldId, Operator: godal.FilterOpLess, Value: "3"},463 }}464 if numRows, err := testDao.GdaoDeleteMany(testDao.collectionName, filter); err != nil {465 t.Fatalf("%s failed: %s", testName, err)466 } else if numRows != 0 {467 t.Fatalf("%s failed: expected %#v row(s) deleted but received %#v", testName, 0, numRows)468 }469 for i := 0; i < 10; i++ {470 id := strconv.Itoa(i)471 user := &UserBoMongo{472 Id: id,473 Username: "user" + id,474 Name: "Thanh " + id,475 Version: int(time.Now().UnixNano()),476 Active: i%3 == 0,477 Created: time.Now(),478 }479 _, err := testDao.GdaoCreate(testDao.collectionName, testDao.toGbo(user))480 if err != nil {481 t.Fatalf("%s failed: %s", testName+"/GdaoCreate", err)482 }483 }484 if numRows, err := testDao.GdaoDeleteMany(testDao.collectionName, filter); err != nil {485 t.Fatalf("%s failed: %s", testName, err)486 } else if numRows != 5 {487 t.Fatalf("%s failed: expected %#v row(s) deleted but received %#v", testName, 5, numRows)488 }489}490func TestGenericDaoMongo_GdaoFetchOne(t *testing.T) {491 testName := "TestGenericDaoMongo_GdaoFetchOne"492 teardownTest := setupTest(t, testName, _setupTestDaoAndCollection, _teardownTest)493 defer teardownTest(t)494 filter := testDao.GdaoCreateFilter(testDao.collectionName, testDao.toGbo(&UserBoMongo{Id: "1"}))495 if gbo, err := testDao.GdaoFetchOne(testDao.collectionName, filter); err != nil {496 t.Fatalf("%s failed: %s", testName+"/GdaoFetchOne", err)497 } else if gbo != nil {498 t.Fatalf("%s failed: non-nil", testName+"/GdaoFetchOne")499 }500 user := &UserBoMongo{501 Id: "1",502 Username: "btnguyen2k",503 Name: "Thanh Nguyen",504 Version: int(time.Now().Unix()),505 Active: false,506 Created: time.Now(),507 }508 _, err := testDao.GdaoCreate(testDao.collectionName, testDao.toGbo(user))509 if err != nil {510 t.Fatalf("%s failed: %s", testName+"/GdaoCreate", err)511 }512 if gbo, err := testDao.GdaoFetchOne(testDao.collectionName, filter); err != nil {513 t.Fatalf("%s failed: %s", testName+"/GdaoFetchOne", err)514 } else if gbo == nil {515 t.Fatalf("%s failed: nil", testName+"/GdaoFetchOne")516 } else {517 fetchedUser := testDao.toUser(gbo)518 _compareUsers(t, testName, user, fetchedUser)519 }520}521func TestGenericDaoMongo_GdaoFetchMany(t *testing.T) {522 testName := "TestGenericDaoMongo_GdaoFetchMany"523 teardownTest := setupTest(t, testName, _setupTestDaoAndCollection, _teardownTest)524 defer teardownTest(t)525 filter := &godal.FilterOptAnd{Filters: []godal.FilterOpt{526 &godal.FilterOptFieldOpValue{FieldName: fieldId, Operator: godal.FilterOpLessOrEqual, Value: "8"},527 &godal.FilterOptFieldOpValue{FieldName: fieldId, Operator: godal.FilterOpGreater, Value: "3"},528 }}529 if dbRows, err := testDao.GdaoFetchMany(testDao.collectionName, filter, nil, 1, 3); err != nil {530 t.Fatalf("%s failed: %s", testName, err)531 } else if dbRows == nil || len(dbRows) != 0 {532 t.Fatalf("%s failed: expected %#v row(s) but received %#v", testName, 0, dbRows)533 }534 userMap := make(map[string]*UserBoMongo)535 for i := 0; i < 10; i++ {536 id := strconv.Itoa(i)537 user := &UserBoMongo{538 Id: id,539 Username: "user" + id,540 Name: "Thanh " + id,541 Version: int(time.Now().Unix()),542 Active: i%3 == 0,543 Created: time.Now(),544 }545 _, err := testDao.GdaoCreate(testDao.collectionName, testDao.toGbo(user))546 if err != nil {547 t.Fatalf("%s failed: %s", testName+"/GdaoCreate", err)548 }549 userMap[id] = user550 }551 sorting := (&godal.SortingOpt{}).Add(&godal.SortingField{FieldName: fieldId, Descending: true})552 if dbRows, err := testDao.GdaoFetchMany(testDao.collectionName, filter, sorting, 1, 3); err != nil {553 t.Fatalf("%s failed: %s", testName, err)554 } else if dbRows == nil || len(dbRows) != 3 {555 t.Fatalf("%s failed: expected %#v row(s) but received %#v", testName, 3, dbRows)556 } else {557 for _, row := range dbRows {558 fetchedUser := testDao.toUser(row)559 _compareUsers(t, testName, userMap[fetchedUser.Id], fetchedUser)560 }561 }562}563func TestGenericDaoMongo_GdaoCreate(t *testing.T) {564 testName := "TestGenericDaoMongo_GdaoCreate"565 teardownTest := setupTest(t, testName, _setupTestDaoAndCollection, _teardownTest)566 defer teardownTest(t)567 user := &UserBoMongo{568 Id: "1",569 Username: "btnguyen2k",570 Name: "Thanh Nguyen",571 Version: int(time.Now().Unix()),572 Active: false,573 Created: time.Now(),574 }575 if numRows, err := testDao.GdaoCreate(testDao.collectionName, testDao.toGbo(user)); err != nil {576 t.Fatalf("%s failed: %s", testName, err)577 } else if numRows != 1 {578 t.Fatalf("%s failed: expected %#v row(s) inserted but received %#v", testName, 1, numRows)579 }580 // duplicated id581 clone := *user582 clone.Username = "thanhn"583 if numRows, err := testDao.GdaoCreate(testDao.collectionName, testDao.toGbo(&clone)); err != godal.ErrGdaoDuplicatedEntry || numRows != 0 {584 t.Fatalf("%s failed: num rows %#v / error: %s", testName, numRows, err)585 }586 filter := testDao.GdaoCreateFilter(testDao.collectionName, testDao.toGbo(&UserBoMongo{Id: "1"}))587 if gbo, err := testDao.GdaoFetchOne(testDao.collectionName, filter); err != nil {588 t.Fatalf("%s failed: %s", testName+"/GdaoFetchOne", err)589 } else if gbo == nil {590 t.Fatalf("%s failed: nil", testName+"/GdaoFetchOne")591 } else {592 fetchedUser := testDao.toUser(gbo)593 _compareUsers(t, testName, user, fetchedUser)594 }595}596func TestGenericDaoMongo_GdaoCreate_TxOn(t *testing.T) {597 testName := "TestGenericDaoMongo_GdaoCreate_TxOn"598 teardownTest := setupTest(t, testName, _setupTestDaoAndCollection, _teardownTest)599 defer teardownTest(t)600 if strings.Index(testDao.mongoConnect.GetUrl(), "replicaSet=") < 0 {601 t.Skipf("%s skipped", testName)602 }603 testDao.SetTxModeOnWrite(true)604 user := &UserBoMongo{605 Id: "1",606 Username: "btnguyen2k",607 Name: "Thanh Nguyen",608 Version: int(time.Now().Unix()),609 Active: false,610 Created: time.Now(),611 }612 if numRows, err := testDao.GdaoCreate(testDao.collectionName, testDao.toGbo(user)); err != nil {613 t.Fatalf("%s failed: %s", testName, err)614 } else if numRows != 1 {615 t.Fatalf("%s failed: expected %#v row(s) inserted but received %#v", testName, 1, numRows)616 }617 // duplicated id618 clone := *user619 clone.Username = "thanhn"620 if numRows, err := testDao.GdaoCreate(testDao.collectionName, testDao.toGbo(&clone)); err != godal.ErrGdaoDuplicatedEntry || numRows != 0 {621 t.Fatalf("%s failed: num rows %#v / error: %s", testName, numRows, err)622 }623 filter := testDao.GdaoCreateFilter(testDao.collectionName, testDao.toGbo(&UserBoMongo{Id: "1"}))624 if gbo, err := testDao.GdaoFetchOne(testDao.collectionName, filter); err != nil {625 t.Fatalf("%s failed: %s", testName+"/GdaoFetchOne", err)626 } else if gbo == nil {627 t.Fatalf("%s failed: nil", testName+"/GdaoFetchOne")628 } else {629 fetchedUser := testDao.toUser(gbo)630 _compareUsers(t, testName, user, fetchedUser)631 }632}633func TestGenericDaoMongo_GdaoUpdate(t *testing.T) {634 testName := "TestGenericDaoMongo_GdaoUpdate"635 teardownTest := setupTest(t, testName, _setupTestDaoAndCollection, _teardownTest)636 defer teardownTest(t)637 user := &UserBoMongo{638 Id: "1",639 Username: "btnguyen2k",640 Name: "Thanh Nguyen",641 Version: int(time.Now().Unix()),642 Active: false,643 Created: time.Now(),644 }645 if numRows, err := testDao.GdaoUpdate(testDao.collectionName, testDao.toGbo(user)); err != nil {646 t.Fatalf("%s failed: %s", testName+"/GdaoUpdate", err)647 } else if numRows != 0 {648 t.Fatalf("%s failed: expected %#v row(s) inserted but received %#v", testName+"/GdaoUpdate", 0, numRows)649 }650 if numRows, err := testDao.GdaoCreate(testDao.collectionName, testDao.toGbo(user)); err != nil {651 t.Fatalf("%s failed: %s", testName+"/GdaoCreate", err)652 } else if numRows != 1 {653 t.Fatalf("%s failed: expected %#v row(s) inserted but received %#v", testName+"/GdaoCreate", 1, numRows)654 }655 user.Username = "thanhn"656 if numRows, err := testDao.GdaoUpdate(testDao.collectionName, testDao.toGbo(user)); err != nil {657 t.Fatalf("%s failed: %s", testName+"/GdaoUpdate", err)658 } else if numRows != 1 {659 t.Fatalf("%s failed: expected %#v row(s) inserted but received %#v", testName+"/GdaoUpdate", 1, numRows)660 }661 filter := testDao.GdaoCreateFilter(testDao.collectionName, testDao.toGbo(&UserBoMongo{Id: "1"}))662 if gbo, err := testDao.GdaoFetchOne(testDao.collectionName, filter); err != nil {663 t.Fatalf("%s failed: %s", testName+"/GdaoFetchOne", err)664 } else if gbo == nil {665 t.Fatalf("%s failed: nil", testName+"/GdaoFetchOne")666 } else {667 fetchedUser := testDao.toUser(gbo)668 _compareUsers(t, testName, user, fetchedUser)669 }670}671func TestGenericDaoMongo_GdaoUpdateDuplicated(t *testing.T) {672 testName := "TestGenericDaoMongo_GdaoUpdateDuplicated"673 teardownTest := setupTest(t, testName, _setupTestDaoAndCollection, _teardownTest)674 defer teardownTest(t)675 user1 := &UserBoMongo{676 Id: "1",677 Username: "user1",678 }679 if numRows, err := testDao.GdaoCreate(testDao.collectionName, testDao.toGbo(user1)); err != nil {680 t.Fatalf("%s failed: %s", testName+"/GdaoCreate", err)681 } else if numRows != 1 {682 t.Fatalf("%s failed: expected %#v row(s) inserted but received %#v", testName+"/GdaoCreate", 1, numRows)683 }684 user2 := &UserBoMongo{685 Id: "2",686 Username: "user2",687 }688 if numRows, err := testDao.GdaoCreate(testDao.collectionName, testDao.toGbo(user2)); err != nil {689 t.Fatalf("%s failed: %s", testName+"/GdaoCreate", err)690 } else if numRows != 1 {691 t.Fatalf("%s failed: expected %#v row(s) inserted but received %#v", testName+"/GdaoCreate", 1, numRows)692 }693 user2.Username = user1.Username694 if numRows, err := testDao.GdaoUpdate(testDao.collectionName, testDao.toGbo(user2)); err != godal.ErrGdaoDuplicatedEntry || numRows != 0 {695 fmt.Println("Error:", err)696 fmt.Printf("Error: %#v\n", err)697 t.Fatalf("%s failed: num rows %#v / error: %s", testName, numRows, err)698 }699}700func TestGenericDaoMongo_GdaoSave(t *testing.T) {701 testName := "TestGenericDaoMongo_GdaoSave"702 teardownTest := setupTest(t, testName, _setupTestDaoAndCollection, _teardownTest)703 defer teardownTest(t)704 user := &UserBoMongo{705 Id: "1",706 Username: "btnguyen2k",707 Name: "Thanh Nguyen",708 Version: int(time.Now().Unix()),709 Active: false,710 Created: time.Now(),711 }712 if numRows, err := testDao.GdaoSave(testDao.collectionName, testDao.toGbo(user)); err != nil {713 t.Fatalf("%s failed: %s", testName+"/GdaoSave", err)714 } else if numRows != 1 {715 t.Fatalf("%s failed: expected %#v row(s) inserted but received %#v", testName+"/GdaoSave", 1, numRows)716 }717 user.Username = "thanhn"718 if numRows, err := testDao.GdaoSave(testDao.collectionName, testDao.toGbo(user)); err != nil {719 t.Fatalf("%s failed: %s", testName+"/GdaoSave", err)720 } else if numRows != 1 {721 t.Fatalf("%s failed: expected %#v row(s) inserted but received %#v", testName+"/GdaoSave", 1, numRows)722 }723 filter := testDao.GdaoCreateFilter(testDao.collectionName, testDao.toGbo(&UserBoMongo{Id: "1"}))724 if gbo, err := testDao.GdaoFetchOne(testDao.collectionName, filter); err != nil {725 t.Fatalf("%s failed: %s", testName+"/GdaoFetchOne", err)726 } else if gbo == nil {727 t.Fatalf("%s failed: nil", testName+"/GdaoFetchOne")728 } else {729 fetchedUser := testDao.toUser(gbo)730 _compareUsers(t, testName, user, fetchedUser)731 }732}733func TestGenericDaoMongo_GdaoSaveShouldReplace(t *testing.T) {734 testName := "TestGenericDaoMongo_GdaoSaveShouldReplace"735 teardownTest := setupTest(t, testName, _setupTestDaoAndCollection, _teardownTest)736 defer teardownTest(t)737 gbo := godal.NewGenericBo()738 data1 := map[string]interface{}{739 "_id": "1",740 "username": "btnguyen2k",741 "active": false,742 "version": 1,743 }744 gbo.GboImportViaJson(data1)745 if numRows, err := testDao.GdaoSave(testDao.collectionName, gbo); err != nil {746 t.Fatalf("%s failed: %s", testName+"/GdaoSave", err)747 } else if numRows != 1 {748 t.Fatalf("%s failed: expected %#v row(s) inserted but received %#v", testName+"/GdaoSave", 1, numRows)749 }750 data2 := map[string]interface{}{751 "_id": "1",752 "testName": "Thanh Nguyen",753 "active": true,754 }755 gbo.GboImportViaJson(data2)756 if numRows, err := testDao.GdaoSave(testDao.collectionName, gbo); err != nil {757 t.Fatalf("%s failed: %s", testName+"/GdaoSave", err)758 } else if numRows != 1 {759 t.Fatalf("%s failed: expected %#v row(s) inserted but received %#v", testName+"/GdaoSave", 1, numRows)760 }761 filter := godal.FilterOptFieldOpValue{FieldName: fieldId, Operator: godal.FilterOpEqual, Value: "1"}762 if gbo, err := testDao.GdaoFetchOne(testDao.collectionName, filter); err != nil {763 t.Fatalf("%s failed: %s", testName+"/GdaoFetchOne", err)764 } else if gbo == nil {765 t.Fatalf("%s failed: nil", testName+"/GdaoFetchOne")766 } else {767 data := make(map[string]interface{})768 gbo.GboTransferViaJson(&data)769 if !reflect.DeepEqual(data2, data) {770 t.Fatalf("%s failed: expected %v but received %v", testName+"/GdaoFetchOne", data2, data)771 }772 }773}774func TestGenericDaoMongo_GdaoSaveDuplicated(t *testing.T) {775 testName := "TestGenericDaoMongo_GdaoSaveDuplicated"776 teardownTest := setupTest(t, testName, _setupTestDaoAndCollection, _teardownTest)777 defer teardownTest(t)778 user1 := &UserBoMongo{779 Id: "1",780 Username: "user1",781 }782 if numRows, err := testDao.GdaoSave(testDao.collectionName, testDao.toGbo(user1)); err != nil {783 t.Fatalf("%s failed: %s", testName+"/GdaoCreate", err)784 } else if numRows != 1 {785 t.Fatalf("%s failed: expected %#v row(s) inserted but received %#v", testName+"/GdaoCreate", 1, numRows)786 }787 user2 := &UserBoMongo{788 Id: "2",789 Username: "user2",790 }791 if numRows, err := testDao.GdaoSave(testDao.collectionName, testDao.toGbo(user2)); err != nil {792 t.Fatalf("%s failed: %s", testName+"/GdaoCreate", err)793 } else if numRows != 1 {794 t.Fatalf("%s failed: expected %#v row(s) inserted but received %#v", testName+"/GdaoCreate", 1, numRows)795 }796 // duplicated id797 user2.Username = user1.Username798 if numRows, err := testDao.GdaoSave(testDao.collectionName, testDao.toGbo(user2)); err != godal.ErrGdaoDuplicatedEntry || numRows != 0 {799 t.Fatalf("%s failed: num rows %#v / error: %s", testName, numRows, err)800 }801}...
validation_test.go
Source:validation_test.go
...6 "testing"7 "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"8 "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"9)10func TestvalidateGCEName(t *testing.T) {11 x := []StringValidationTestCase{12 // No errors13 {TestName: "basic", Value: "foobar"},14 {TestName: "with numbers", Value: "foobar123"},15 {TestName: "short", Value: "f"},16 {TestName: "long", Value: "foobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoo"},17 {TestName: "has a hyphen", Value: "foo-bar"},18 // With errors19 {TestName: "empty", Value: "", ExpectError: true},20 {TestName: "starts with a capital", Value: "Foobar", ExpectError: true},21 {TestName: "starts with a number", Value: "1foobar", ExpectError: true},22 {TestName: "has an underscore", Value: "foo_bar", ExpectError: true},23 {TestName: "too long", Value: "foobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoob", ExpectError: true},24 }25 es := testStringValidationCases(x, validateGCEName)26 if len(es) > 0 {27 t.Errorf("Failed to validate GCP names: %v", es)28 }29}30func TestValidateRFC1918Network(t *testing.T) {31 x := []RFC1918NetworkTestCase{32 // No errors33 {TestName: "valid 10.x", CIDR: "10.0.0.0/8", MinPrefix: 0, MaxPrefix: 32},34 {TestName: "valid 172.x", CIDR: "172.16.0.0/16", MinPrefix: 0, MaxPrefix: 32},35 {TestName: "valid 192.x", CIDR: "192.168.0.0/32", MinPrefix: 0, MaxPrefix: 32},36 {TestName: "valid, bounded 10.x CIDR", CIDR: "10.0.0.0/8", MinPrefix: 8, MaxPrefix: 32},37 {TestName: "valid, bounded 172.x CIDR", CIDR: "172.16.0.0/16", MinPrefix: 12, MaxPrefix: 32},38 {TestName: "valid, bounded 192.x CIDR", CIDR: "192.168.0.0/32", MinPrefix: 16, MaxPrefix: 32},39 // With errors40 {TestName: "empty CIDR", CIDR: "", MinPrefix: 0, MaxPrefix: 32, ExpectError: true},41 {TestName: "missing mask", CIDR: "10.0.0.0", MinPrefix: 0, MaxPrefix: 32, ExpectError: true},42 {TestName: "invalid CIDR", CIDR: "10.1.0.0/8", MinPrefix: 0, MaxPrefix: 32, ExpectError: true},43 {TestName: "valid 10.x CIDR with lower bound violation", CIDR: "10.0.0.0/8", MinPrefix: 16, MaxPrefix: 32, ExpectError: true},44 {TestName: "valid 10.x CIDR with upper bound violation", CIDR: "10.0.0.0/24", MinPrefix: 8, MaxPrefix: 16, ExpectError: true},45 {TestName: "valid public CIDR", CIDR: "8.8.8.8/32", MinPrefix: 0, MaxPrefix: 32, ExpectError: true},46 }47 es := testRFC1918Networks(x)48 if len(es) > 0 {49 t.Errorf("Failed to validate RFC1918 Networks: %v", es)50 }51}52func TestValidateRFC3339Time(t *testing.T) {53 cases := []StringValidationTestCase{54 // No errors55 {TestName: "midnight", Value: "00:00"},56 {TestName: "one minute before midnight", Value: "23:59"},57 // With errors58 {TestName: "single-digit hour", Value: "3:00", ExpectError: true},59 {TestName: "hour out of range", Value: "24:00", ExpectError: true},60 {TestName: "minute out of range", Value: "03:60", ExpectError: true},61 {TestName: "missing colon", Value: "0100", ExpectError: true},62 {TestName: "not numbers", Value: "ab:cd", ExpectError: true},63 }64 es := testStringValidationCases(cases, validateRFC3339Time)65 if len(es) > 0 {66 t.Errorf("Failed to validate RFC3339 times: %v", es)67 }68}69func TestValidateRFC1035Name(t *testing.T) {70 cases := []struct {71 TestName string72 Value string73 Min, Max int74 ExpectError bool75 }{76 {TestName: "valid", Min: 6, Max: 30, Value: "a-valid-name0"},77 {TestName: "valid lower bound", Min: 12, Max: 30, Value: "a-valid-name"},78 {TestName: "valid upper bound", Min: 6, Max: 12, Value: "a-valid-name"},79 {TestName: "valid with numbers", Min: 6, Max: 30, Value: "valid000-name"},80 {TestName: "must start with a letter", Min: 6, Max: 10, Value: "0invalid", ExpectError: true},81 {TestName: "cannot end with a dash", Min: 6, Max: 10, Value: "invalid-", ExpectError: true},82 {TestName: "too short", Min: 6, Max: 10, Value: "short", ExpectError: true},83 {TestName: "too long", Min: 6, Max: 10, Value: "toolooooong", ExpectError: true},84 {TestName: "min too small", Min: 1, Max: 10, Value: "", ExpectError: true},85 {TestName: "min < max", Min: 6, Max: 5, Value: "", ExpectError: true},86 }87 for _, c := range cases {88 errors := testStringValidation(StringValidationTestCase{89 TestName: c.TestName,90 Value: c.Value,91 ExpectError: c.ExpectError,92 }, validateRFC1035Name(c.Min, c.Max))93 if len(errors) > 0 {94 t.Errorf("%s failed; %v", c.TestName, errors)95 }96 }97}98func TestValidateServiceAccountLink(t *testing.T) {99 cases := []StringValidationTestCase{100 // These test cases focus on the project name part of the regex101 // The service account name is covered by the RFC1035Name tests above102 // No errors103 {TestName: "valid with dash", Value: "projects/my-project/serviceAccounts/svcacct@my-project.iam.gserviceaccount.com"},104 {TestName: "valid with colon", Value: "projects/my:project/serviceAccounts/svcacct@project.my.iam.gserviceaccount.com"},105 {TestName: "valid with dot and colon", Value: "projects/my.thing:project/serviceAccounts/svcacct@project.my.thing.iam.gserviceaccount.com"},106 {TestName: "valid with compute default service account", Value: "projects/my-project/serviceAccounts/123456-compute@developer.gserviceaccount.com"},107 {TestName: "valid with app engine default service account", Value: "projects/my-project/serviceAccounts/my-project@appspot.gserviceaccount.com"},108 // Errors109 {TestName: "multiple colons", Value: "projects/my:project:thing/serviceAccounts/svcacct@thing.project.my.iam.gserviceaccount.com", ExpectError: true},110 {TestName: "project name empty", Value: "projects//serviceAccounts/svcacct@.iam.gserviceaccount.com", ExpectError: true},111 {TestName: "dot only with no colon", Value: "projects/my.project/serviceAccounts/svcacct@my.project.iam.gserviceaccount.com", ExpectError: true},112 {113 TestName: "too long",114 Value: "projects/foobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoob/serviceAccounts/svcacct@" +115 "foobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoob.iam.gserviceaccount.com",116 ExpectError: true,117 },118 }119 es := testStringValidationCases(cases, validateRegexp(ServiceAccountLinkRegex))120 if len(es) > 0 {121 t.Errorf("Failed to validate Service Account Links: %v", es)122 }123}124type StringValidationTestCase struct {125 TestName string126 Value string127 ExpectError bool128}129type RFC1918NetworkTestCase struct {130 TestName string131 CIDR string132 MinPrefix int133 MaxPrefix int134 ExpectError bool135}136func testStringValidationCases(cases []StringValidationTestCase, validationFunc schema.SchemaValidateFunc) []error {137 es := make([]error, 0)138 for _, c := range cases {139 es = append(es, testStringValidation(c, validationFunc)...)140 }141 return es142}143func testStringValidation(testCase StringValidationTestCase, validationFunc schema.SchemaValidateFunc) []error {144 _, es := validationFunc(testCase.Value, testCase.TestName)145 if testCase.ExpectError {146 if len(es) > 0 {147 return nil148 } else {149 return []error{fmt.Errorf("Didn't see expected error in case \"%s\" with string \"%s\"", testCase.TestName, testCase.Value)}150 }151 }152 return es153}154func testRFC1918Networks(cases []RFC1918NetworkTestCase) []error {155 es := make([]error, 0)156 for _, c := range cases {157 es = append(es, testRFC1918Network(c)...)158 }159 return es160}161func testRFC1918Network(testCase RFC1918NetworkTestCase) []error {162 f := validateRFC1918Network(testCase.MinPrefix, testCase.MaxPrefix)163 _, es := f(testCase.CIDR, testCase.TestName)164 if testCase.ExpectError {165 if len(es) > 0 {166 return nil167 }168 return []error{fmt.Errorf("Didn't see expected error in case \"%s\" with CIDR=\"%s\" MinPrefix=%v MaxPrefix=%v",169 testCase.TestName, testCase.CIDR, testCase.MinPrefix, testCase.MaxPrefix)}170 }171 return es172}173func TestProjectRegex(t *testing.T) {174 tests := []struct {175 project string176 want bool177 }{178 {"example", true},179 {"example.com:example", true},180 {"12345", true},181 {"", false},182 {"example_", false},183 }184 r := regexp.MustCompile("^" + ProjectRegex + "$")185 for _, test := range tests {186 if got := r.MatchString(test.project); got != test.want {187 t.Errorf("got %t, want %t for project %v", got, test.want, test.project)188 }189 }190}191func TestOrEmpty(t *testing.T) {192 cases := map[string]struct {193 Value string194 ValidateFunc schema.SchemaValidateFunc195 ExpectValidationErrors bool196 }{197 "accept empty value": {198 Value: "",199 ExpectValidationErrors: false,200 },201 "non empty value is accepted when valid": {202 Value: "valid",203 ExpectValidationErrors: false,204 },205 "non empty value is rejected if invalid": {206 Value: "invalid",207 ExpectValidationErrors: true,208 },209 }210 for tn, tc := range cases {211 validateFunc := orEmpty(validation.StringInSlice([]string{"valid"}, false))212 _, errors := validateFunc(tc.Value, tn)213 if len(errors) > 0 && !tc.ExpectValidationErrors {214 t.Errorf("%s: unexpected errors %s", tn, errors)215 } else if len(errors) == 0 && tc.ExpectValidationErrors {216 t.Errorf("%s: expected errors but got none", tn)217 }218 }219}220func TestValidateProjectID(t *testing.T) {221 x := []StringValidationTestCase{222 // No errors223 {TestName: "basic", Value: "foobar"},224 {TestName: "with numbers", Value: "foobar123"},225 {TestName: "short", Value: "foofoo"},226 {TestName: "long", Value: "foobarfoobarfoobarfoobarfoobar"},227 {TestName: "has a hyphen", Value: "foo-bar"},228 // With errors229 {TestName: "empty", Value: "", ExpectError: true},230 {TestName: "has an slash", Value: "foo/bar", ExpectError: true},231 {TestName: "has an uppercase letter", Value: "foo-Bar", ExpectError: true},232 {TestName: "has a final hyphen", Value: "foo-bar-", ExpectError: true},233 }234 es := testStringValidationCases(x, validateProjectID())235 if len(es) > 0 {236 t.Errorf("Failed to validate project ID's: %v", es)237 }238}239func TestValidateProjectName(t *testing.T) {240 x := []StringValidationTestCase{241 // No errors242 {TestName: "basic", Value: "fooBar"},243 {TestName: "complex", Value: "project! 'A-1234'"},244 {TestName: "with numbers", Value: "foobar123"},245 {TestName: "short", Value: "foof"},246 {TestName: "long", Value: "foobarfoobarfoobarfoobarfoobar"},247 {TestName: "has a hyphen", Value: "foo-bar"},248 {TestName: "starts with a number", Value: "1foobar"},249 {TestName: "has a final hyphen", Value: "foo-bar-"},250 // With errors251 {TestName: "empty", Value: "", ExpectError: true},252 {TestName: "has an slash", Value: "foo/bar", ExpectError: true},253 {TestName: "too long", Value: strings.Repeat("a", 31), ExpectError: true},254 }255 es := testStringValidationCases(x, validateProjectName())256 if len(es) > 0 {257 t.Errorf("Failed to validate project ID's: %v", es)258 }259}260func TestValidateIAMCustomRoleIDRegex(t *testing.T) {261 x := []StringValidationTestCase{262 // No errors263 {TestName: "basic", Value: "foobar"},264 {TestName: "with numbers", Value: "foobar123"},265 {TestName: "with capitals", Value: "FooBar"},266 {TestName: "short", Value: "foo"},267 {TestName: "long", Value: strings.Repeat("f", 64)},268 {TestName: "has a dot", Value: "foo.bar"},269 {TestName: "has an underscore", Value: "foo_bar"},270 {TestName: "all of the above", Value: "foo.BarBaz_123"},271 // With errors272 {TestName: "empty", Value: "", ExpectError: true},273 {TestName: "has an slash", Value: "foo/bar", ExpectError: true},274 {TestName: "has a hyphen", Value: "foo-bar", ExpectError: true},275 {TestName: "has a dollar", Value: "foo$", ExpectError: true},276 {TestName: "has a space", Value: "foo bar", ExpectError: true},277 {TestName: "too short", Value: "fo", ExpectError: true},278 {TestName: "too long", Value: strings.Repeat("f", 65), ExpectError: true},279 }280 es := testStringValidationCases(x, validateIAMCustomRoleID)281 if len(es) > 0 {282 t.Errorf("Failed to validate IAMCustomRole IDs: %v", es)283 }284}...
validator_test.go
Source:validator_test.go
...12 assert.NotEqual(t, nil, v)13 t.Run("ValidateStruct", func(t *testing.T) {14 t.Run("should return no errors", func(t *testing.T) {15 type Test struct {16 Name string `json:"name" validate:"required"`17 }18 test := Test{19 Name: "test",20 }21 errors := v.ValidateStruct(test)22 assert.Equal(t, 0, len(errors))23 })24 t.Run("should return errors", func(t *testing.T) {25 type Test struct {26 Name string `json:"name" validate:"required"`27 }28 test := Test{29 Name: "",30 }31 errors := v.ValidateStruct(test)32 assert.Equal(t, 1, len(errors))33 })34 })35 t.Run("ConnectCustom", func(t *testing.T) {36 v.ConnectCustom()37 t.Run("should return no errors", func(t *testing.T) {38 type Test struct {39 Name string `json:"name" validate:"username"`40 }41 test := Test{42 Name: "test",43 }44 errors := v.ValidateStruct(test)45 assert.Equal(46 t,47 0,48 len(errors),49 )50 })51 t.Run("should return errors", func(t *testing.T) {52 type Test struct {53 Name string `json:"name" validate:"username"`54 }55 test := Test{56 Name: "",57 }58 errors := v.ValidateStruct(test)59 assert.Equal(60 t,61 1,62 len(errors),63 )64 })65 })66 t.Run("RegisterTagName", func(t *testing.T) {67 v.RegisterTagName()68 t.Run("should return empty string", func(t *testing.T) {69 type Test struct {70 Name string `json:"-" validate:"required"`71 }72 test := Test{73 Name: "test",74 }75 errors := v.ValidateStruct(test)76 assert.Equal(77 t,78 0,79 len(errors),80 )81 })82 t.Run("should return no errors", func(t *testing.T) {83 type Test struct {84 Name string `json:"name" validate:"required"`85 }86 test := Test{87 Name: "test",88 }89 errors := v.ValidateStruct(test)90 assert.Equal(t, 0, len(errors))91 })92 t.Run("should return errors", func(t *testing.T) {93 type Test struct {94 Name string `json:"name" validate:"required"`95 }96 test := Test{97 Name: "",98 }99 errors := v.ValidateStruct(test)100 assert.Equal(t, 1, len(errors))101 })102 })103 t.Run("translateErrorMessage", func(t *testing.T) {104 t.Run("should return no errors", func(t *testing.T) {105 type Test struct {106 Name string `json:"name" validate:"required"`107 }108 test := Test{109 Name: "test",110 }111 errors := v.ValidateStruct(test)112 assert.Equal(t, 0, len(errors))113 })114 t.Run("should return errors", func(t *testing.T) {115 type Test struct {116 Name string `json:"name" validate:"required"`117 }118 test := Test{119 Name: "",120 }121 errors := v.ValidateStruct(test)122 assert.Equal(t, 1, len(errors))123 })124 t.Run("should return errors", func(t *testing.T) {125 type Test struct {126 Name string `json:"name" validate:"required"`127 }128 test := Test{129 Name: "",130 }131 errors := v.ValidateStruct(test)132 assert.Equal(t, 1, len(errors))133 })134 t.Run("should return errors", func(t *testing.T) {135 type Test struct {136 Name string `json:"name" validate:"required"`137 }138 test := Test{139 Name: "",140 }141 errors := v.ValidateStruct(test)142 assert.Equal(t, 1, len(errors))143 })144 t.Run("should return errors", func(t *testing.T) {145 type Test struct {146 Name string `json:"name" validate:"required"`147 }148 test := Test{149 Name: "",150 }151 errors := v.ValidateStruct(test)152 assert.Equal(t, 1, len(errors))153 })154 })155 t.Run("CustomValidator", func(t *testing.T) {156 t.Run("validateUserName", func(t *testing.T) {157 t.Run("should return no errors", func(t *testing.T) {158 type Test struct {159 Name string `json:"name" validate:"username"`160 }161 test := Test{162 Name: "test",163 }164 errors := v.ValidateStruct(test)165 assert.Equal(t, 0, len(errors))166 })167 t.Run("should return errors", func(t *testing.T) {168 type Test struct {169 Name string `json:"name" validate:"username"`170 }171 test := Test{172 Name: "",173 }174 errors := v.ValidateStruct(test)175 assert.Equal(t, 1, len(errors))176 })177 })178 t.Run("validatePassword", func(t *testing.T) {179 t.Run("should return no errors", func(t *testing.T) {180 type Test struct {181 Name string `json:"name" validate:"password"`182 }183 test := Test{184 Name: "Tat%at334_3s",185 }186 errors := v.ValidateStruct(test)187 assert.Equal(t, 0, len(errors))188 })189 t.Run("should return errors", func(t *testing.T) {190 type Test struct {191 Name string `json:"name" validate:"password"`192 }193 test := Test{194 Name: "",195 }196 errors := v.ValidateStruct(test)197 assert.Equal(t, 1, len(errors))198 })199 })200 t.Run("validateLocale", func(t *testing.T) {201 t.Run("should return no errors", func(t *testing.T) {202 type Test struct {203 Name string `json:"name" validate:"locale"`204 }205 test := Test{206 Name: "test",207 }208 errors := v.ValidateStruct(test)209 assert.Equal(t, 0, len(errors))210 })211 t.Run("should return errors", func(t *testing.T) {212 type Test struct {213 Name string `json:"name" validate:"locale"`214 }215 test := Test{216 Name: "",217 }218 errors := v.ValidateStruct(test)219 assert.Equal(t, 1, len(errors))220 })221 })222 t.Run("validateObjectId", func(t *testing.T) {223 t.Run("should return errors", func(t *testing.T) {224 type Test struct {225 Id string `json:"name" validate:"object_id"`226 }227 test := Test{228 Id: "5e9f8f8f8f8f8f8f8f8f8f8",229 }230 errors := v.ValidateStruct(test)231 assert.Equal(t, 1, len(errors))232 })233 t.Run("should return errors", func(t *testing.T) {234 type Test struct {235 Id string `json:"name" validate:"object_id"`236 }237 test := Test{238 Id: "",239 }240 errors := v.ValidateStruct(test)241 assert.Equal(t, 1, len(errors))242 })243 t.Run("should return no errors", func(t *testing.T) {244 type Test struct {245 Id string `json:"name" validate:"object_id"`246 }247 test := Test{248 Id: primitive.NewObjectID().Hex(),249 }250 errors := v.ValidateStruct(test)251 assert.Equal(t, 0, len(errors))252 })253 })254 t.Run("validateSlug", func(t *testing.T) {255 t.Run("should return no errors", func(t *testing.T) {256 type Test struct {257 Name string `json:"name" validate:"slug"`258 }259 test := Test{260 Name: "test-test",261 }262 errors := v.ValidateStruct(test)263 assert.Equal(t, 0, len(errors))264 })265 t.Run("should return errors", func(t *testing.T) {266 type Test struct {267 Name string `json:"name" validate:"slug"`268 }269 test := Test{270 Name: "@test--",271 }272 errors := v.ValidateStruct(test)273 assert.Equal(t, 1, len(errors))274 })275 })276 })277}...
Name
Using AI Code Generation
1import (2func main() {3 fmt.Println(test.Name())4}5After installing the package, you can use it in any of the Go programs. To use the package, you need to import the package in your program. For example, the following program uses the Name method of the test package:6import (7func main() {8 fmt.Println(test.Name())9}10{
Name
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 t.Name()5}6import "fmt"7type Test struct {8}9func (t *Test) Name() {10 fmt.Println(t.Name)11}12import (13func main() {14 fmt.Println("Hello, playground")15 t.Name()16}17import "fmt"18type Test struct {19}20func (t *Test) Name() {21 fmt.Println(t.Name)22}23t.Name()24t := test.Test{}25t.Name()26t := &test.Test{}27t.Name()28t := &test.Test{Name: "test"}29t.Name()30t := new(test.Test)
Name
Using AI Code Generation
1import "fmt"2func main() {3 fmt.Println(obj.Name)4}5import "fmt"6func main() {7 fmt.Println(obj.name)8}9./2.go:8: obj.name undefined (cannot refer to unexported field or method name)10import "fmt"11func main() {12 fmt.Println(obj.name)13}14./3.go:8: obj.name undefined (cannot refer to unexported field or method name)15import "fmt"16func main() {17 fmt.Println(obj.name)18}19./4.go:8: obj.name undefined (cannot refer to unexported field or method name)20import "fmt"21func main() {22 fmt.Println(obj.name)23}24./5.go:8: obj.name undefined (cannot refer to unexported field or method name)
Name
Using AI Code Generation
1import "fmt"2func main() {3 fmt.Println("Hello, playground")4 t := test{"Rajeev"}5 t.Name()6}
Name
Using AI Code Generation
1import "fmt"2func main() {3 fmt.Println(t.Name)4}5import "fmt"6func main() {7 var t struct {8 }9 fmt.Println(t.Name)10}
Name
Using AI Code Generation
1import "fmt"2func main() {3 fmt.Println(t.Name)4}5import "fmt"6func main() {7 fmt.Println(t.Name)8 t.Name("World")9 fmt.Println(t.Name)10}
Name
Using AI Code Generation
1import "fmt"2func main() {3 a := test{"A"}4 fmt.Println(a.Name())5}6import "fmt"7func main() {8 a := test{"A"}9 fmt.Println(a.Name("B"))10}11import "fmt"12func main() {13 a := test{"A"}14 fmt.Println(a.Name("B"))15}16type test struct {17}18func (t test) Name(name string) string {19}20import "fmt"21func main() {22 a := test{"A"}23 fmt.Println(a.Name("B"))24}25type test struct {26}27func (t *test) Name(name string) string {28}29import
Name
Using AI Code Generation
1import "fmt"2func main() {3t := test{}4fmt.Println(t.Name)5}6type structName struct {7}8type Person struct {9}10type Employee struct {11}12func main() {13 e := Employee{14 Person: Person{15 },16 }17 fmt.Println(e.Name)18 fmt.Println(e.Age)19}20struct {21}22import "fmt"23func main() {24 p := struct {25 }{26 }27 fmt.Println(p.Name)28 fmt.Println(p.Age)29}30type structName struct {31}32type Person struct {33}34type Employee struct {35}36func main() {
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!