Best Syzkaller code snippet using main.NewInput
codemod_test.go
Source:codemod_test.go
...22 }23 }24`)25 t.Run("Has", func(t *testing.T) {26 file, _ := codemod.New(codemod.NewInput{SourceCode: sourceCode, FilePath: "path"})27 _, literal := file.FindMapLiteral("map[string]string")28 t.Run("returns true if map contains key", func(t *testing.T) {29 assert.True(t, literal.Has("transaction_isolation"))30 })31 t.Run("returns false if map does not contain key", func(t *testing.T) {32 assert.False(t, literal.Has("key_not_in_the_map"))33 })34 })35 t.Run("RenameKey", func(t *testing.T) {36 file, _ := codemod.New(codemod.NewInput{SourceCode: sourceCode, FilePath: "path"})37 _, literal := file.FindMapLiteral("map[string]string")38 t.Run("renames the key", func(t *testing.T) {39 expected := `map[string]string{"tx_isolation": "'READ-COMMITED'"}`40 literal.RenameKey("transaction_isolation", "tx_isolation")41 actual := codemod.SourceCode(literal.Expr.Node)42 check(t, expected, actual)43 })44 t.Run("if key is not in the map, does nothing", func(t *testing.T) {45 file, _ := codemod.New(codemod.NewInput{SourceCode: sourceCode, FilePath: "path"})46 _, literal := file.FindMapLiteral("map[string]string")47 expected := `map[string]string{"transaction_isolation": "'READ-COMMITED'"}`48 literal.RenameKey("a", "b")49 actual := codemod.SourceCode(literal.Expr.Node)50 check(t, expected, actual)51 })52 })53}54func Test_IfStatements(t *testing.T) {55 t.Parallel()56 t.Run("finds if statement", func(t *testing.T) {57 t.Parallel()58 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(`59 package main60 func main() {61 if true { }62 }63 `)})64 scopedStatements := file.IfStatements()65 assert.Equal(t, 1, len(scopedStatements))66 for _, statements := range scopedStatements {67 assert.Equal(t, 1, len(statements))68 for _, statement := range statements {69 check(t, "true", codemod.SourceCode(statement.Node.Cond))70 }71 }72 })73 t.Run("removal", func(t *testing.T) {74 sourceCode := []byte(`75 package main76 func main() {77 if true {78 println(2)79 }80 }81 `)82 t.Run("removes if statement", func(t *testing.T) {83 file, _ := codemod.New(codemod.NewInput{SourceCode: sourceCode, FilePath: "path"})84 for _, statements := range file.IfStatements() {85 for _, statement := range statements {86 statement.Remove()87 }88 }89 expected := "package main\n\nfunc main() {\n\n}\n"90 actual := string(file.SourceCode())91 check(t, expected, actual)92 })93 t.Run("removes only if statement condition", func(t *testing.T) {94 file, _ := codemod.New(codemod.NewInput{SourceCode: sourceCode, FilePath: "path"})95 for _, statements := range file.IfStatements() {96 for _, statement := range statements {97 statement.RemoveCondition()98 }99 }100 expected := "package main\n\nfunc main() {\n\n\tprintln(2)\n\n}\n"101 actual := string(file.SourceCode())102 check(t, expected, actual)103 })104 })105}106func Test_ReplaceDatabaseConnectionErrorIfStatement(t *testing.T) {107 t.Parallel()108 t.Skip()109 sourceCode := []byte(`110 package database111 import (112 "database/sql"113 "time"114 115 "github.com/go-sql-driver/mysql"116 "github.com/pkg/errors"117 )118 119 func Connect() (*sql.DB, error) {120 config := mysql.Config{121 User: "mysql",122 Passwd: "mysql",123 DBName: "db",124 Params: map[string]string{125 "tx_isolation": "'READ-COMMITTED'",126 },127 }128 129 db, err := sql.Open("mysql", config.FormatDSN())130 if err != nil {131 return db, errors.WithStack(err)132 }133 134 err = db.Ping()135 if err != nil {136 if mysqlErr, ok := err.(*mysql.MySQLError); ok && mysqlErr.Number == 1193 {137 config.Params["tx_isolation"], config.Params["transaction_isolation"] = config.Params["transaction_isolation"], config.Params["tx_isolation"]138 139 db, err = sql.Open("mysql", config.FormatDSN())140 if err != nil {141 return db, errors.WithStack(err)142 }143 }144 }145 if err != nil {146 return db, errors.WithStack(err)147 }148 149 db.SetConnMaxLifetime(time.Minute * 3)150 db.SetMaxOpenConns(10)151 db.SetMaxIdleConns(10)152 153 return db, nil154 } 155 `)156 file, _ := codemod.New(codemod.NewInput{SourceCode: sourceCode, FilePath: "path"})157 for _, statements := range file.IfStatements() {158 for _, statement := range statements {159 if !strings.HasSuffix(codemod.SourceCode(statement.Node.Cond), "Number == 1193") {160 continue161 }162 body := codemod.Ast(`163 config.Params["tx_isolation"], config.Params["transaction_isolation"] = config.Params["transaction_isolation"], config.Params["tx_isolation"]164 if config.Params["tx_isolation"] == "" {165 delete(config.Params, "tx_isolation")166 }167 if config.Params["transaction_isolation"] == "" {168 delete(config.Params, "transaction_isolation")169 }170 db, err = sql.Open("mysql", config.FormatDSN())171 if err != nil {172 return db, errors.WithStack(err)173 }174 err = db.Ping()175 if err != nil {176 return db, errors.WithStack(err)177 }178 `)179 statement.Node.Body = body.(*ast.BlockStmt)180 }181 }182 expected :=183 `package database184import (185 "database/sql"186 "time"187 "github.com/go-sql-driver/mysql"188 "github.com/pkg/errors"189)190func Connect() (*sql.DB, error) {191 config := mysql.Config{192 User: "mysql",193 Passwd: "mysql",194 DBName: "db",195 Params: map[string]string{196 "tx_isolation": "'READ-COMMITTED'",197 },198 }199 db, err := sql.Open("mysql", config.FormatDSN())200 if err != nil {201 return db, errors.WithStack(err)202 }203 err = db.Ping()204 if err != nil {205 if mysqlErr, ok := err.(*mysql.MySQLError); ok && mysqlErr.Number == 1193 {206 config.Params["tx_isolation"], config.Params["transaction_isolation"] = config.Params["transaction_isolation"], config.Params["tx_isolation"]207 if config.Params["tx_isolation"] == "" {208 delete(config.Params, "tx_isolation")209 }210 if config.Params["transaction_isolation"] == "" {211 delete(config.Params, "transaction_isolation")212 }213 db, err = sql.Open("mysql", config.FormatDSN())214 if err != nil {215 return db, errors.WithStack(err)216 }217 err = db.Ping()218 if err != nil {219 return db, errors.WithStack(err)220 }221 }222 }223 if err != nil {224 return db, errors.WithStack(err)225 }226 db.SetConnMaxLifetime(time.Minute * 3)227 db.SetMaxOpenConns(10)228 db.SetMaxIdleConns(10)229 return db, nil230}231`232 actual := string(file.SourceCode())233 check(t, expected, actual)234}235func Test_RewriteErrorsWrapfToFmtErrorf(t *testing.T) {236 t.Parallel()237 sourceCode := []byte(`238 package main239 import "errors"240 var errSomething = errors.New("oops")241 func foo() error {242 return errors.Wrapf(errSomething, "some context")243 }244 func main() {245 246 }247 `)248 file, _ := codemod.New(codemod.NewInput{SourceCode: sourceCode, FilePath: "path"})249 scopedCalls := file.FunctionCalls()250 for _, calls := range scopedCalls {251 for _, call := range calls {252 if call.FunctionName() != "errors.Wrapf" {253 continue254 }255 args := call.Node.Args256 args[0], args[len(args)-1] = args[len(args)-1], args[0]257 args[0].(*ast.BasicLit).Value = codemod.Quote(codemod.Unquote(args[0].(*ast.BasicLit).Value) + ": %w")258 call.Node.Fun = &ast.SelectorExpr{259 X: &ast.Ident{Name: "fmt"},260 Sel: &ast.Ident{Name: "Errorf"},261 }262 }263 }264 if len(scopedCalls) > 0 {265 file.Imports().Add("fmt")266 }267 expected :=268 `package main269import (270 "errors"271 "fmt"272)273var errSomething = errors.New("oops")274func foo() error {275 return fmt.Errorf("some context: %w", errSomething)276}277func main() {278}279`280 updatedSourceCode := string(file.SourceCode())281 assert.Equal(t, expected, updatedSourceCode)282}283func TestSourceFile_FunctionCalls(t *testing.T) {284 t.Parallel()285 t.Run("when there are no function calls", func(t *testing.T) {286 t.Run("returns the empty map", func(t *testing.T) {287 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(`288 package main 289 func a() {}290 func main() {}291 `)})292 assert.Empty(t, file.FunctionCalls())293 })294 })295 t.Run("when there are function calls", func(t *testing.T) {296 t.Run("returns them", func(t *testing.T) {297 t.Run("identifier call", func(t *testing.T) {298 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(`299 package main 300 301 func a() {}302 303 func main() {304 a()305 }306 `)})307 scopes := file.FunctionCalls()308 assert.Equal(t, 1, len(scopes))309 for _, calls := range scopes {310 for _, call := range calls {311 assert.Equal(t, "a", call.Node.Fun.(*ast.Ident).Name)312 }313 }314 })315 t.Run("selector call", func(t *testing.T) {316 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(`317 package main 318 import "errors"319 320 func main() {321 _ = errors.New("oops")322 }323 `)})324 scopes := file.FunctionCalls()325 assert.Equal(t, 1, len(scopes))326 for _, calls := range scopes {327 for _, call := range calls {328 selector := call.Node.Fun.(*ast.SelectorExpr)329 assert.Equal(t, "errors", selector.X.(*ast.Ident).Name)330 assert.Equal(t, "New", selector.Sel.Name)331 }332 }333 })334 })335 })336}337func Test_FunctionCall(t *testing.T) {338 t.Parallel()339 t.Run("returns function name", func(t *testing.T) {340 tests := []struct {341 code string342 expected string343 }{344 {345 code: `346 package helloworld347 348 func f() {}349 350 func g() {351 f()352 }353 `,354 expected: "f",355 },356 {357 code: `358 package main359 360 import "errors"361 362 func main() {363 _ = errors.New("oops")364 }365 `,366 expected: "errors.New",367 },368 }369 for _, tt := range tests {370 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(tt.code)})371 scopedCalls := file.FunctionCalls()372 assert.Equal(t, 1, len(scopedCalls))373 for _, calls := range scopedCalls {374 assert.Equal(t, 1, len(calls))375 assert.Equal(t, tt.expected, calls[0].FunctionName())376 }377 }378 })379 t.Run("inserts node before function call", func(t *testing.T) {380 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(`381 package main382 import "somepackage"383 func main() {384 somepackage.Foo()385 }386 `)})387 for _, calls := range file.FunctionCalls() {388 for _, call := range calls {389 if call.FunctionName() == "somepackage.Foo" {390 call.InsertBefore(codemod.Ast(`x := 1`))391 }392 }393 }394 expected :=395 `package main396import "somepackage"397func main() {398 x := 1399 somepackage.Foo()400}401`402 check(t, expected, string(file.SourceCode()))403 })404 t.Run("inserts node after function call", func(t *testing.T) {405 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(`406 package main407 import "somepackage"408 func main() {409 somepackage.Foo()410 }411 `)})412 for _, calls := range file.FunctionCalls() {413 for _, call := range calls {414 if call.FunctionName() == "somepackage.Foo" {415 node := codemod.Ast(`416 type S struct {}417 `)418 call.InsertAfter(node)419 }420 }421 }422 expected :=423 `package main424import "somepackage"425func main() {426 somepackage.Foo()427 type S struct {}428}429`430 actual := string(file.SourceCode())431 check(t, expected, actual)432 })433 t.Run("removes function call", func(t *testing.T) {434 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(`435 package main436 import "somepackage"437 func main() {438 somepackage.Foo()439 }440 `)})441 for _, calls := range file.FunctionCalls() {442 for _, call := range calls {443 if call.FunctionName() == "somepackage.Foo" {444 call.Remove()445 }446 }447 }448 expected :=449 `package main450import "somepackage"451func main() {452}453`454 actual := string(file.SourceCode())455 check(t, expected, actual)456 })457}458func TestSourceFile_Functions(t *testing.T) {459 t.Parallel()460 t.Run("when there are function declarations", func(t *testing.T) {461 t.Run("returns them", func(t *testing.T) {462 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(`463 package main 464 func inc(x int) int {465 return x + 1466 }467 func main() {}468 `)})469 functions := file.Functions()470 assert.Equal(t, 2, len(functions))471 assert.Equal(t, "inc", functions[0].Node.Name.Name)472 assert.Equal(t, "main", functions[1].Node.Name.Name)473 })474 })475 t.Run("when there are no function declarations", func(t *testing.T) {476 t.Run("returns nothing", func(t *testing.T) {477 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(`478 package foo479 var SomeConstant int64 = 1480 `)})481 assert.Empty(t, file.Functions())482 })483 })484}485func Test_TypeDeclarations(t *testing.T) {486 t.Parallel()487 t.Run("when there are no type declarations", func(t *testing.T) {488 t.Run("returns nothing", func(t *testing.T) {489 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(`490 package main491 func main(){}492 `)})493 assert.Empty(t, file.TypeDeclarations())494 })495 })496 t.Run("when there are type declarations", func(t *testing.T) {497 t.Run("returns interfaces", func(t *testing.T) {498 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(`499 package main500 type UserService interface {}501 func main(){}502 `)})503 declarations := file.TypeDeclarations()504 assert.Equal(t, 1, len(declarations))505 assert.Equal(t, "UserService", declarations[0].Node.Name.Name)506 })507 t.Run("returns structs", func(t *testing.T) {508 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(`509 package main510 type UserService struct {}511 func main(){}512 `)})513 declarations := file.TypeDeclarations()514 assert.Equal(t, 1, len(declarations))515 assert.Equal(t, "UserService", declarations[0].Node.Name.Name)516 })517 t.Run("returns type aliases", func(t *testing.T) {518 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(`519 package main520 type UserID int64521 func main(){}522 `)})523 declarations := file.TypeDeclarations()524 assert.Equal(t, 1, len(declarations))525 assert.Equal(t, "UserID", declarations[0].Node.Name.Name)526 })527 })528}529func TestTypeDeclaration_Methods(t *testing.T) {530 t.Parallel()531 tests := []struct {532 code string533 expected []string534 }{535 {536 code: `537 package foo538 type Interface interface {}539 type Struct struct {}540 type Foo int541 `,542 expected: []string{},543 },544 {545 code: `546 package main547 import "context"548 type Interface interface {549 Foo(int64, context.Context) error550 Bar()551 Baz(int) string552 }553 func main(){}554 `,555 expected: []string{"Foo", "Bar", "Baz"},556 },557 {558 code: `559 package foo560 type User struct {}561 func (user *User) IsAdmin() bool { return false }562 func (user User) Something() {}563 `,564 expected: []string{"IsAdmin", "Something"},565 },566 {567 code: `568 package foo569 type ID int64570 func (id *ID) A() string { return "hello" }571 func (id ID) B() error { return nil }572 `,573 expected: []string{"A", "B"},574 },575 }576 for _, tt := range tests {577 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(tt.code)})578 declarations := file.TypeDeclarations()579 assert.NotEmpty(t, declarations)580 for _, declaration := range declarations {581 for i := range tt.expected {582 assert.Equal(t, tt.expected[i], declaration.Methods()[i].Name())583 }584 }585 }586}587func TestTypeDeclaration_IsInterface(t *testing.T) {588 t.Parallel()589 tests := []struct {590 code string591 expected bool592 }{593 {594 code: `595 package main 596 type User struct{}597 `,598 expected: false,599 },600 {601 code: `602 package main 603 type UserID int64604 `,605 expected: false,606 },607 {608 code: `609 package main 610 type I interface {}611 `,612 expected: true,613 },614 }615 for _, tt := range tests {616 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(tt.code)})617 assert.Equal(t, tt.expected, file.TypeDeclarations()[0].IsInterface())618 }619}620func TestTypeDeclaration_IsStruct(t *testing.T) {621 t.Parallel()622 tests := []struct {623 code string624 expected bool625 }{626 {627 code: `628 package main 629 type User struct{}630 `,631 expected: true,632 },633 {634 code: `635 package main 636 type UserID int64637 `,638 expected: false,639 },640 {641 code: `642 package main 643 type I interface {}644 `,645 expected: false,646 },647 }648 for _, tt := range tests {649 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(tt.code)})650 assert.Equal(t, tt.expected, file.TypeDeclarations()[0].IsStruct())651 }652}653func TestTypeDeclaration_IsTypeAlias(t *testing.T) {654 t.Parallel()655 tests := []struct {656 code string657 expected bool658 }{659 {660 code: `661 package main662 type User struct{}663 `,664 expected: false,665 },666 {667 code: `668 package main 669 type UserID int64670 `,671 expected: true,672 },673 {674 code: `675 package main676 type I interface {}677 `,678 expected: false,679 },680 }681 for _, tt := range tests {682 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(tt.code)})683 assert.Equal(t, tt.expected, file.TypeDeclarations()[0].IsTypeAlias())684 }685}686func TestMethod_Name(t *testing.T) {687 t.Parallel()688 tests := []struct {689 code string690 expected string691 }{692 {693 code: `694 package main695 type I interface {696 Foo(int64) int64697 }698 `,699 expected: "Foo",700 },701 {702 code: `703 package main704 type S struct {}705 func (s *S) Bar() {}706 `,707 expected: "Bar",708 },709 {710 code: `711 package main712 type S struct {}713 func (s S) Bar() {}714 `,715 expected: "Bar",716 },717 {718 code: `719 package main 720 type T int64721 func (t T) Baz() {}722 `,723 expected: "Baz",724 },725 {726 code: `727 package main 728 type T int64729 func (t *T) Baz() {}730 `,731 expected: "Baz",732 },733 }734 for _, tt := range tests {735 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(tt.code)})736 declarations := file.TypeDeclarations()737 actual := declarations[0].Methods()[0].Name()738 assert.Equal(t, tt.expected, actual)739 }740}741func TestSourceFile_FindAssignments(t *testing.T) {742 t.Parallel()743 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(`744 package main745 func main() {746 a := 1747 b := make(map[string]string)748 b["tx_isolation"] = "'READ-COMMITTED'"749 c := struct{750 x int751 }{752 x: 0,753 }754 c.x = 1755 d := make([]int, 1)756 d[0] = 10757 d = append(d, 20)758 }759 `)})760 tests := []struct {761 target string762 expected string763 }{764 {target: "a", expected: "a := 1"},765 {target: "a := 1", expected: "a := 1"},766 {target: "a:=1", expected: "a := 1"},767 {target: "b := make(map[string]string)", expected: "b := make(map[string]string)"},768 {target: `b["tx_isolation"]`, expected: `b["tx_isolation"] = "'READ-COMMITTED'"`},769 {target: "c.x", expected: "c.x = 1"},770 {target: "c.x = 1", expected: "c.x = 1"},771 {target: "d[0]", expected: "d[0] = 10"},772 {target: "d[0] = 10", expected: "d[0] = 10"},773 {target: "d = append(d, 20)", expected: "d = append(d, 20)"},774 }775 for _, tt := range tests {776 scopedAssignments := file.FindAssignments(tt.target)777 assert.Equal(t, 1, len(scopedAssignments))778 for _, assignments := range scopedAssignments {779 assert.Equal(t, 1, len(assignments))780 assert.Equal(t, tt.expected, codemod.SourceCode(assignments[0].Node))781 }782 }783}784func Test_Assignments(t *testing.T) {785 t.Parallel()786 tests := []struct {787 code string788 expected []string789 }{790 {791 code: `792 package main793 func main() {}794 `,795 expected: []string{},796 },797 {798 code: `799 package main800 func main() {801 x := 1802 x = 2803 }804 `,805 expected: []string{"x := 1", "x = 2"},806 },807 }808 for _, tt := range tests {809 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(tt.code)})810 actual := file.Assignments()811 for _, assignments := range actual {812 assert.Equal(t, len(tt.expected), len(assignments))813 for i := range tt.expected {814 assert.Equal(t, tt.expected[i], codemod.SourceCode(assignments[i].Node))815 }816 }817 }818}819func TestAst(t *testing.T) {820 t.Parallel()821 tests := []struct {822 code string823 expected ast.Node824 }{825 {826 code: "x := 1",827 expected: &ast.AssignStmt{},828 },829 {830 code: `831 if config.Params["tx_isolation"] == "" {832 delete(config.Params, "tx_isolation")833 }834 `,835 expected: &ast.IfStmt{},836 },837 {838 code: "type I interface {}",839 expected: &ast.DeclStmt{},840 },841 {842 code: "type S struct {}",843 expected: &ast.DeclStmt{},844 },845 {846 code: `847 if a > 2 {848 }849 if b > 5 {850 }851 `,852 expected: &ast.BlockStmt{},853 },854 }855 for _, tt := range tests {856 actual := codemod.Ast(tt.code)857 assert.Equal(t, fmt.Sprintf("%T", tt.expected), fmt.Sprintf("%T", actual))858 }859}860func TestAssign_InsertAfter(t *testing.T) {861 t.Parallel()862 tests := []struct {863 code string864 expected string865 }{866 {867 code: "y := 2",868 expected: `package main869func main() {870 x := 1871 y := 2872}873`,874 },875 {876 code: `877 if config.Params["tx_isolation"] == "" {878 delete(config.Params, "tx_isolation")879 }880 `,881 expected: `package main882func main() {883 x := 1884 if config.Params["tx_isolation"] == "" {885 delete(config.Params, "tx_isolation")886 }887}888`,889 },890 }891 for _, tt := range tests {892 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(`893 package main894 func main() {895 x := 1896 }897 `)})898 for _, assignments := range file.FindAssignments("x") {899 for _, assignment := range assignments {900 assignment.InsertAfter(codemod.Ast(tt.code))901 }902 }903 actual := string(file.SourceCode())904 check(t, tt.expected, actual)905 }906}907func TestAssign_InsertBefore(t *testing.T) {908 t.Parallel()909 tests := []struct {910 code string911 expected string912 }{913 {914 code: "y := 2",915 expected: `package main916func main() {917 y := 2918 x := 1919}920`,921 },922 {923 code: `924 if config.Params["tx_isolation"] == "" {925 delete(config.Params, "tx_isolation")926 }927 `,928 expected: "package main\n\nfunc main() {\n\tif config.Params[\"tx_isolation\"] == \"\" {\n\t\tdelete(config.Params, \"tx_isolation\")\n\t}\n\n\tx := 1\n}\n",929 },930 }931 for _, tt := range tests {932 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(`933 package main934 func main() {935 x := 1936 }937 `)})938 for _, assignments := range file.FindAssignments("x") {939 for _, assignment := range assignments {940 assignment.InsertBefore(codemod.Ast(tt.code))941 }942 }943 actual := string(file.SourceCode())944 check(t, tt.expected, actual)945 }946}947func Test_IfStmt_Remove(t *testing.T) {948 t.Parallel()949 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(`950 package main951 func main() {952 if 2 == 2 {953 println("hello")954 }955 }956 `)})957 for _, statements := range file.IfStatements() {958 for _, statement := range statements {959 if codemod.SourceCode(statement.Node.Cond) == "2 == 2" {960 statement.Remove()961 }962 }963 }964 expected :=965 `package main966func main() {967}968`969 actual := string(file.SourceCode())970 check(t, expected, actual)971}972func Test_IfStmt_InsertBefore(t *testing.T) {973 t.Parallel()974 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(`975 package main976 func main() {977 if 2 == 2 {978 println("hello")979 }980 }981 `)})982 for _, statements := range file.IfStatements() {983 for _, statement := range statements {984 if codemod.SourceCode(statement.Node.Cond) == "2 == 2" {985 statement.InsertBefore(codemod.Ast(`println("before if statement")`))986 }987 }988 }989 expected :=990 `package main991func main() {992 println("before if statement")993 if 2 == 2 {994 println("hello")995 }996}997`998 actual := string(file.SourceCode())999 check(t, expected, actual)1000}1001func Test_IfStmt_InsertAfter(t *testing.T) {1002 t.Parallel()1003 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(`1004 package main1005 func main() {1006 if 2 == 2 {1007 println("hello")1008 }1009 }1010 `)})1011 for _, statements := range file.IfStatements() {1012 for _, statement := range statements {1013 if codemod.SourceCode(statement.Node.Cond) == "2 == 2" {1014 statement.InsertAfter(codemod.Ast(`println("after if statement")`))1015 }1016 }1017 }1018 expected :=1019 `package main1020func main() {1021 if 2 == 2 {1022 println("hello")1023 }1024 println("after if statement")1025}1026`1027 actual := string(file.SourceCode())1028 check(t, expected, actual)1029}1030func Test_Package(t *testing.T) {1031 t.Parallel()1032 sourceCode := []byte(`1033 package main1034 func main() {}1035`)1036 t.Run("returns package name", func(t *testing.T) {1037 t.Parallel()1038 file, _ := codemod.New(codemod.NewInput{SourceCode: sourceCode, FilePath: "path"})1039 pkg := file.Package()1040 assert.Equal(t, "main", pkg.Name())1041 })1042 t.Run("modifies package name", func(t *testing.T) {1043 t.Parallel()1044 file, _ := codemod.New(codemod.NewInput{SourceCode: sourceCode, FilePath: "path"})1045 pkg := file.Package()1046 pkg.SetName("newpackagename")1047 expected :=1048 `package newpackagename1049func main() {}1050`1051 assert.Equal(t, expected, string(file.SourceCode()))1052 })1053}1054func Test_TraverseAst(t *testing.T) {1055 t.Parallel()1056 found := false1057 file, _ := codemod.New(codemod.NewInput{SourceCode: []byte(`1058 package bar 1059 func z() {}1060 `)})1061 file.TraverseAst(func(node codemod.NodeWithParent) {1062 if fun, ok := node.Node.(*ast.FuncDecl); ok {1063 found = fun.Name.Name == "z"1064 }1065 })1066 assert.True(t, found)1067}1068func Test_SourceFile_Path(t *testing.T) {1069 t.Parallel()1070 filePath := "src/services/user.go"1071 file, _ := codemod.New(codemod.NewInput{1072 SourceCode: []byte(`1073 package main 1074 func main() {}1075 `),1076 FilePath: filePath,1077 })1078 assert.Equal(t, filePath, file.FilePath)1079}1080func Test_SourceFile_Imports(t *testing.T) {1081 t.Parallel()1082 sourceCode := []byte(`1083 package main 1084 import (1085 "errors"1086 "package_a"1087 "package_b"1088 )1089 func main() {}1090 `)1091 t.Run("user is able to get file imports", func(t *testing.T) {1092 file, _ := codemod.New(codemod.NewInput{SourceCode: sourceCode})1093 imports := file.Imports()1094 assert.Equal(t, []string{"errors", "package_a", "package_b"}, imports.Paths())1095 })1096 t.Run("same import path is not added more than once", func(t *testing.T) {1097 file, _ := codemod.New(codemod.NewInput{SourceCode: sourceCode})1098 imports := file.Imports()1099 imports.Add("new_import")1100 imports.Add("new_import")1101 imports.Add("new_import")1102 assert.Equal(t, []string{"errors", "package_a", "package_b", "new_import"}, imports.Paths())1103 })1104 t.Run("checks if file contains import path", func(t *testing.T) {1105 file, _ := codemod.New(codemod.NewInput{SourceCode: sourceCode})1106 imports := file.Imports()1107 assert.True(t, imports.Contains("errors"))1108 assert.True(t, imports.Contains("package_a"))1109 assert.True(t, imports.Contains("package_b"))1110 assert.False(t, imports.Contains("package_c"))1111 })1112 t.Run("removes import path from file imports", func(t *testing.T) {1113 file, _ := codemod.New(codemod.NewInput{SourceCode: sourceCode})1114 imports := file.Imports()1115 imports.Remove("package_a")1116 assert.Equal(t, []string{"errors", "package_b"}, imports.Paths())1117 })1118}1119func Test_SourceFile_SwitchStatements(t *testing.T) {1120 t.Parallel()1121 sourceCode := []byte(`1122 package p1123 func f(x string) {1124 switch x {1125 case "a":1126 println(1)1127 case "b":1128 println(2)1129 default:1130 println(3)1131 }1132 }1133 `)1134 file, _ := codemod.New(codemod.NewInput{SourceCode: sourceCode})1135 scopedStatements := file.SwitchStatements()1136 assert.Equal(t, 1, len(scopedStatements))1137 for _, statements := range scopedStatements {1138 for _, switchStmt := range statements {1139 if codemod.SourceCode(switchStmt.Node.Tag) != "x" {1140 continue1141 }1142 newSwitchStatementBody := make([]ast.Stmt, 0, len(switchStmt.Node.Body.List))1143 for _, caseClause := range switchStmt.Node.Body.List {1144 newSwitchStatementBody = append(newSwitchStatementBody, caseClause)1145 if !strings.Contains(codemod.SourceCode(caseClause), `"b"`) {1146 continue1147 }1148 newCaseClause := &ast.CaseClause{1149 List: []ast.Expr{1150 &ast.BasicLit{1151 Value: `"c"`,1152 },1153 },1154 Body: []ast.Stmt{1155 &ast.ExprStmt{1156 X: &ast.CallExpr{1157 Fun: &ast.Ident{1158 Name: "println",1159 },1160 Args: []ast.Expr{1161 &ast.BasicLit{1162 Kind: token.INT,1163 Value: "4",1164 },1165 },1166 },1167 },1168 },1169 }1170 newSwitchStatementBody = append(newSwitchStatementBody, newCaseClause)1171 }1172 switchStmt.Node.Body.List = newSwitchStatementBody1173 }1174 }1175 expected := `1176package p1177func f(x string) {1178 switch x {1179 case "a":1180 println(1)1181 case "b":1182 println(2)1183 case "c":1184 println(4)1185 default:1186 println(3)1187 }1188}1189`1190 check(t, expected, string(file.SourceCode()))1191}1192func Test_Codemod_New(t *testing.T) {1193 t.Parallel()1194 t.Run("when Go file cannot be parsed", func(t *testing.T) {1195 t.Run("returns error", func(t *testing.T) {1196 fileMissingPackage := []byte(`1197 func main() {}1198 `)1199 _, err := codemod.New(codemod.NewInput{SourceCode: fileMissingPackage})1200 assert.NotNil(t, err)1201 })1202 })1203 t.Run("when Go file can be parsed", func(t *testing.T) {1204 t.Run("returns no error", func(t *testing.T) {1205 sourceCode := []byte(`1206 package main1207 func main() {}1208 `)1209 _, err := codemod.New(codemod.NewInput{SourceCode: sourceCode})1210 assert.Nil(t, err)1211 })1212 })1213}1214func Test_Example_UpdateNewRelicDataStoreCalls(t *testing.T) {1215 t.Parallel()1216 sourceCode := []byte(`1217package repositories1218import (1219 "context"1220 newrelic "github.com/newrelic/go-agent"1221)1222func Create(ctx context.Context) {1223 s := newrelic.DatastoreSegment{1224 Product: newrelic.DatastoreMySQL,1225 Collection: "users",1226 Operation: "INSERT",1227 ParameterizedQuery: "INSERT INTO users (name, age) VALUES ($1, $2)",1228 QueryParameters: map[string]interface{}{1229 "name": "Dracula",1230 "age": 439,1231 },1232 Host: "mysql-server-1",1233 PortPathOrID: "3306",1234 DatabaseName: "my_database",1235 }1236 s = startSegment(ctx, s)1237 // ... make the datastore call1238 s.End()1239}1240`)1241 file, _ := codemod.New(codemod.NewInput{SourceCode: sourceCode})1242 for scope, assignments := range file.FindAssignments("s") {1243 s := assignments[0].Struct()1244 args := []ast.Expr{1245 s.Field("Collection").Expr,1246 s.Field("Operation").Expr,1247 s.Field("ParameterizedQuery").Expr,1248 }1249 newCall := &ast.DeferStmt{1250 Call: &ast.CallExpr{1251 Fun: &ast.SelectorExpr{1252 X: &ast.CallExpr{1253 Fun: &ast.Ident{Name: "StartDBSegment"},1254 Args: args,1255 },...
day12.go
Source:day12.go
1package main2import (3 "AoC2021/helpers"4 "fmt"5 "os"6 "strings"7)8const caveSize = 29func main() {10 input, err := helpers.ReadLinesToString("input.txt")11 if err != nil {12 fmt.Printf("Input read err: %s", err.Error())13 os.Exit(1)14 }15 newInput := make([]string, 0)16 for i := 0; i < len(input); i++ {17 newInput = append(newInput, input[i])18 splitInput := strings.Split(input[i], "-")19 newInput = append(newInput, splitInput[1]+"-"+splitInput[0])20 }21 paths := make([]string, 0)22 for i := 0; i < len(newInput); i++ {23 if strings.Split(newInput[i], "-")[0] == "start" {24 paths = append(paths, newInput[i])25 }26 }27 var continued = true28 for continued {29 continued = false30 tempPaths := make([]string, 0)31 for i := 0; i < len(paths); i++ {32 pathCaves := strings.Split(paths[i], "-")33 curCave := pathCaves[len(pathCaves)-1]34 if paths[i][len(paths[i])-3:] == "end" {35 tempPaths = append(tempPaths, paths[i])36 continue37 }38 for j := 0; j < len(newInput); j++ {39 adjoinCave := strings.Split(newInput[j], "-")[0]40 exitCave := strings.Split(newInput[j], "-")[1]41 if helpers.StringIsLower(adjoinCave) {42 if strings.Contains(paths[i][:len(paths[i])-caveSize], adjoinCave) { //adjoinCave already present in path. can't revisit.43 continue44 }45 }46 if helpers.StringIsLower(exitCave) {47 if strings.Contains(paths[i], exitCave) { //exitCave already present in path. can't revisit.48 continue49 }50 }51 if adjoinCave == curCave {52 continued = true53 tempPaths = append(tempPaths, paths[i]+newInput[j][caveSize:])54 }55 }56 }57 paths = make([]string, len(tempPaths))58 copy(paths, tempPaths)59 }60 fmt.Printf("Part 1: %d\n", len(paths))61 // Part 2 is quite similar to part 1, but I want both scores available so I copy/pasted the analyzing logic62 paths = make([]string, 0)63 for i := 0; i < len(newInput); i++ {64 if strings.Split(newInput[i], "-")[0] == "start" {65 paths = append(paths, newInput[i])66 }67 }68 continued = true69 for continued {70 continued = false71 tempPaths := make([]string, 0)72 for i := 0; i < len(paths); i++ {73 pathCaves := strings.Split(paths[i], "-")74 curCave := pathCaves[len(pathCaves)-1]75 if paths[i][len(paths[i])-3:] == "end" {76 tempPaths = append(tempPaths, paths[i])77 continue78 }79 for j := 0; j < len(newInput); j++ {80 adjoinCave := strings.Split(newInput[j], "-")[0]81 exitCave := strings.Split(newInput[j], "-")[1]82 if adjoinCave == "start" || adjoinCave == "end" || exitCave == "start" {83 continue84 }85 if helpers.StringIsLower(adjoinCave) {86 if strings.Contains(paths[i][:len(paths[i])-caveSize], adjoinCave) {87 if PathHasRevisitedSmallCave(paths[i][:len(paths[i])-caveSize]) {88 continue // adjoiningCave is small and path has already visited a small cave more than once. Can't revisit.89 }90 }91 }92 if helpers.StringIsLower(exitCave) {93 if strings.Contains(paths[i], exitCave) {94 if PathHasRevisitedSmallCave(paths[i]) {95 continue // exitCave is small and path has already visited a small cave more than once. Can't revisit.96 }97 }98 }99 if adjoinCave == curCave {100 continued = true101 tempPaths = append(tempPaths, paths[i]+"-"+newInput[j])102 }103 }104 }105 paths = make([]string, len(tempPaths))106 copy(paths, tempPaths)107 }108 fmt.Printf("Part 2: %d", len(paths))109}110func PathHasRevisitedSmallCave(path string) bool {111 caves := strings.Split(path, "-")112 for i := 0; i < len(caves); i++ {113 if !helpers.StringIsLower(caves[i]) {114 continue115 }116 if strings.Count(path, caves[i]) > 3 {117 return true118 }119 }120 return false121}...
Task19_1.go
Source:Task19_1.go
1package main2import "fmt"3func generalArray(input1 [4]int, input2 [5]int) (newinput [9]int) {4 result := 05 for i := 0; i < len(input1); i++ {6 newinput[i] = input1[i]7 }8 for i := 0; i < len(input2); i++ {9 newinput[i+len(input1)] = input2[i]10 }11 for i := 0; i < len(newinput); i++ {12 for i := 0; i < len(newinput); i++ {13 if newinput[i] == newinput[8] {14 break15 }16 if newinput[i] > newinput[i+1] {17 result = newinput[i]18 newinput[i] = newinput[i+1]19 newinput[i+1] = result20 }21 }22 }23 return newinput24}25func main() {26 number1 := [4]int{5, 7, 9, 6}27 number2 := [5]int{11, 10, 19, 10, 12}28 fmt.Println(number1, number2)29 fmt.Println(generalArray(number1, number2))30}...
NewInput
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello world")4}5import (6func main() {7 fmt.Println("Hello world")8}9import (10func main() {11 fmt.Println("Hello world")12}13import (14func main() {15 fmt.Println("Hello world")16}17import (18func main() {19 fmt.Println("Hello world")20}21import (22func main() {23 fmt.Println("Hello world")24}25import (26func main() {27 fmt.Println("Hello world")28}29import (30func main() {31 fmt.Println("Hello world")32}33import (34func main() {35 fmt.Println("Hello world")36}37import (38func main() {39 fmt.Println("Hello world")40}41import (42func main() {43 fmt.Println("Hello world")44}45import (46func main() {47 fmt.Println("Hello world")48}49import (50func main() {51 fmt.Println("Hello world")52}53import
NewInput
Using AI Code Generation
1import (2func main() {3 fmt.Println(morestrings.ReverseRunes("!oG ,olleH"))4}5import (6func main() {7 fmt.Println(morestrings.ReverseRunes("!oG ,olleH"))8}9import (10func main() {11 for _, b := range []byte(s) {12 fmt.Printf("%X ", b)13 }14 fmt.Println()15 fmt.Printf("(%d %X) ", i, ch)16 }17 fmt.Println()18 for i, ch := range []rune(s) {19 fmt.Printf("(%d %c) ", i, ch)20 }21 fmt.Println()22}
NewInput
Using AI Code Generation
1import (2func main() {3 fmt.Println("Enter a number")4 a = input.NewInput()5 fmt.Println("You entered", a)6}
NewInput
Using AI Code Generation
1import (2func main() {3 fmt.Println(second.NewInput(3, 4))4}5import "fmt"6func NewInput(a, b int) int {7}
NewInput
Using AI Code Generation
1import (2func main() {3 fmt.Println("Enter a number")4 input := main.NewInput()5 fmt.Println("You entered", input)6}7import (8func main() {9 fmt.Println("Enter a number")10 input := main.NewInput()11 fmt.Println("You entered", input)12}13import (14func main() {15 fmt.Println("Enter a number")16 input := main.NewInput()17 fmt.Println("You entered", input)18}19import (20func main() {21 fmt.Println("Enter a number")22 input := main.NewInput()23 fmt.Println("You entered", input)24}25import (26func main() {27 fmt.Println("Enter a number")28 input := main.NewInput()29 fmt.Println("You entered", input)30}31import (32func main() {33 fmt.Println("Enter a number")34 input := main.NewInput()35 fmt.Println("You entered", input)36}37import (38func main() {39 fmt.Println("Enter a number")40 input := main.NewInput()41 fmt.Println("You entered", input)42}43import (44func main() {45 fmt.Println("Enter a number")46 input := main.NewInput()47 fmt.Println("You entered", input)48}49import (50func main() {51 fmt.Println("Enter a number")52 input := main.NewInput()53 fmt.Println("You entered", input)54}
NewInput
Using AI Code Generation
1import (2func main() {3 fmt.Scanln(&input)4 fmt.Println(yourproject.NewInput(input))5}6import (7func main() {8 fmt.Scanln(&input)9 fmt.Println(yourproject.NewInput(input))10}11import (12func main() {13 fmt.Scanln(&input)14 fmt.Println(yourproject.NewInput(input))15}16import (17func main() {18 fmt.Scanln(&input)19 fmt.Println(yourproject.NewInput(input))20}21import (22func main() {23 fmt.Scanln(&input)24 fmt.Println(yourproject.NewInput(input))25}26import (27func main() {28 fmt.Scanln(&input)29 fmt.Println(yourproject.NewInput(input))30}31import (32func main() {33 fmt.Scanln(&input)34 fmt.Println(yourproject.NewInput(input))35}36import (37func main() {38 fmt.Scanln(&input
NewInput
Using AI Code Generation
1import (2func main() {3 udayangaac.NewInput()4 fmt.Println("Hello, playground")5}6import (7func main() {8 udayangaac.NewInput()9 fmt.Println("Hello, playground")10}11import (12func main() {13 udayangaac.NewInput()14 fmt.Println("Hello, playground")15}16import (17func main() {18 udayangaac.NewInput()19 fmt.Println("Hello, playground")20}21import (22func main() {23 udayangaac.NewInput()24 fmt.Println("Hello, playground")25}26import (27func main() {28 udayangaac.NewInput()29 fmt.Println("Hello, playground")30}31import (32func 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!!