Best Testcontainers-go code snippet using testcontainers.Format
suite.go
Source:suite.go
...23 containerRequests []testcontainers.StartGenericContainerRequest24 featureFilesLocation string25 databaseDriver string26 databaseDSN string27 databasePlaceholderFormat squirrel.PlaceholderFormat28 customerRepositoryConstructor CustomerRepositoryConstructor29}30func (s suite) startContainers(runID string, log logger, requests ...testcontainers.StartGenericContainerRequest) ([]testcontainers.Container, error) {31 if len(requests) == 0 {32 return nil, nil33 }34 for i := range requests {35 requests[i].Options = append(requests[i].Options,36 testcontainers.WithNamePrefix("otelsql"),37 testcontainers.WithNameSuffix(runID),38 )39 }40 containers, err := testcontainers.StartGenericContainers(context.Background(), requests...)41 if err != nil {42 log(err.Error())43 }44 return containers, err45}46func (s suite) stopContainers(tb testing.TB, containers ...testcontainers.Container) {47 tb.Helper()48 if err := testcontainers.StopGenericContainers(context.Background(), containers...); err != nil {49 tb.Log(err.Error())50 }51}52func (s suite) getFeatureFiles(location string, log func(format string, args ...interface{})) ([]string, error) {53 entries, err := os.ReadDir(location)54 if err != nil {55 log("could not read feature files location: %s", err.Error())56 return nil, err57 }58 result := make([]string, 0)59 for _, f := range entries {60 if f.IsDir() || !strings.HasSuffix(f.Name(), ".feature") {61 continue62 }63 result = append(result, filepath.Join(location, f.Name()))64 }65 return result, nil66}67func (s suite) runTests(tb testing.TB, sc suiteContext) error {68 tb.Helper()69 db, err := openDBxWithoutInstrumentation(sc.databaseDriver, sc.databaseDSN)70 if err != nil {71 tb.Logf("could not init database with sqlx: %s", err.Error())72 return err73 }74 out := bytes.NewBuffer(nil)75 clock := clocksteps.New()76 otelsqlTests := newObservabilityTests()77 customerTests := newCustomerTests(sc.databaseDriver, sc.databaseDSN, sc.customerRepositoryConstructor, clock)78 dbm := makeDBManager(db, sc.databasePlaceholderFormat)79 suite := godog.TestSuite{80 Name: "Integration",81 ScenarioInitializer: func(sc *godog.ScenarioContext) {82 clock.RegisterContext(sc)83 dbm.RegisterSteps(sc)84 otelsqlTests.RegisterContext(sc)85 customerTests.RegisterContext(sc)86 },87 Options: &godog.Options{88 Format: "pretty",89 Strict: true,90 Output: out,91 Randomize: time.Now().UTC().UnixNano(),92 Paths: sc.featureFiles,93 },94 }95 // Run the suite.96 if status := suite.Run(); status != 0 {97 tb.Fatal(out.String())98 }99 return nil100}101func (s suite) start(tb testing.TB) (suiteContext, error) {102 tb.Helper()103 var (104 sc suiteContext105 err error106 )107 // Start containers.108 sc.containers, err = s.startContainers(randomString(8), tb.Logf, s.containerRequests...)109 if err != nil {110 return sc, err111 }112 // Setup.113 sc.databaseDriver = s.databaseDriver114 sc.databaseDSN = os.ExpandEnv(s.databaseDSN)115 sc.databasePlaceholderFormat = s.databasePlaceholderFormat116 sc.customerRepositoryConstructor = s.customerRepositoryConstructor117 sc.featureFiles, err = s.getFeatureFiles(s.featureFilesLocation, tb.Logf)118 if err != nil {119 return sc, err120 }121 if err := s.runTests(tb, sc); err != nil {122 return sc, err123 }124 return sc, nil125}126func (s suite) stop(tb testing.TB, sc suiteContext) suiteContext {127 tb.Helper()128 defer s.stopContainers(tb, sc.containers...)129 return sc130}131func (s suite) Run(tb testing.TB) {132 tb.Helper()133 sc, err := s.start(tb)134 defer s.stop(tb, sc)135 require.NoError(tb, err)136}137// New creates a new test suite.138func New(opts ...Option) Suite {139 s := suite{140 databasePlaceholderFormat: squirrel.Question,141 }142 for _, opt := range opts {143 opt(&s)144 }145 return s146}147// Run creates a new test suite and run it.148func Run(tb testing.TB, opts ...Option) {149 tb.Helper()150 New(opts...).Run(tb)151}...
pg_testcontainer.go
Source:pg_testcontainer.go
...12var (13 ErrFailedToStartTestcontainer = func(args TestContainerArgs) error {14 return fmt.Errorf("failed to start testcontainer `%s`", args.Image)15 }16 ErrUnexpectedPortFormat = errors.New("unexpected port format")17 expectedPortPartsLen = 218)19type TestContainerArgs struct {20 Image string21 Env map[string]string22 Port string23 WaitForLog string24 AutoRemove bool25}26func NewPGTestContainer(ctx context.Context, args TestContainerArgs) testcontainers.Container {27 req := testcontainers.ContainerRequest{28 Image: args.Image,29 Env: args.Env,30 ExposedPorts: []string{args.Port},31 WaitingFor: wait.ForLog(args.WaitForLog),32 AutoRemove: args.AutoRemove,33 AlwaysPullImage: true,34 }35 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{36 ContainerRequest: req,37 Started: true,38 })39 if err != nil {40 panic(errwrap.Wrap(ErrFailedToStartTestcontainer(args), err))41 }42 return container43}44func PortFromContainer(ctx context.Context, args TestContainerArgs, container testcontainers.Container) (port nat.Port, err error) { //nolint:lll45 portParts := strings.Split(args.Port, "/")46 if len(portParts) != expectedPortPartsLen {47 err = ErrUnexpectedPortFormat48 return49 }50 port, err = nat.NewPort(portParts[1], portParts[0])51 if err != nil {52 err = errwrap.Wrap(ErrUnexpectedPortFormat, err)53 return54 }55 port, err = container.MappedPort(ctx, port)56 return57}...
Format
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"6379/tcp"},6 WaitingFor: wait.ForLog("Ready to accept connections"),7 }8 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer redisContainer.Terminate(ctx)14}15import (16func main() {17 ctx := context.Background()18 req := testcontainers.ContainerRequest{19 ExposedPorts: []string{"6379/tcp"},20 WaitingFor: wait.ForLog("Ready to accept connections"),21 }22 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{23 })24 if err != nil {25 panic(err)26 }27 defer redisContainer.Terminate(ctx)28}29import (30func main() {31 ctx := context.Background()32 req := testcontainers.ContainerRequest{33 ExposedPorts: []string{"6379/tcp"},34 WaitingFor: wait.ForLog("Ready to accept connections"),35 }36 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{37 })38 if err != nil {39 panic(err)40 }41 defer redisContainer.Terminate(ctx)42}
Format
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"6379/tcp"},6 WaitingFor: wait.ForListeningPort("6379/tcp"),7 }8 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer redisContainer.Terminate(ctx)14 ip, err := redisContainer.Host(ctx)15 if err != nil {16 panic(err)17 }18 port, err := redisContainer.MappedPort(ctx, "6379/tcp")19 if err != nil {20 panic(err)21 }22 fmt.Println(ip, port.Int())23}
Format
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"3306/tcp"},6 WaitingFor: wait.ForLog("port: 3306 MySQL Community Server - GPL"),7 }8 mysqlContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer mysqlContainer.Terminate(ctx)14 ip, err := mysqlContainer.Host(ctx)15 if err != nil {16 log.Fatal(err)17 }18 port, err := mysqlContainer.MappedPort(ctx, "3306")19 if err != nil {20 log.Fatal(err)21 }22 dsn := fmt.Sprintf("root:password@tcp(%s:%s)/", ip, port.Port())23 db, err := sql.Open("mysql", dsn)24 if err != nil {25 log.Fatal(err)26 }27 _, err = db.Exec("CREATE DATABASE test_db")28 if err != nil {29 log.Fatal(err)30 }31 db.Close()32 dsn = fmt.Sprintf("root:password@tcp(%s:%s)/test_db", ip, port.Port())33 db, err = sql.Open("mysql", dsn)34 if err != nil {35 log.Fatal(err)36 }37 _, err = db.Exec("CREATE TABLE IF NOT EXISTS test_table (id INTEGER AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))")38 if err != nil {39 log.Fatal(err)40 }41 _, err = db.Exec("INSERT INTO test_table (name) VALUES ('test')")42 if err != nil {43 log.Fatal(err)44 }45 rows, err := db.Query("SELECT * FROM test_table")46 if err != nil {47 log.Fatal(err)48 }
Format
Using AI Code Generation
1import (2func main() {3ctx := context.Background()4req := testcontainers.ContainerRequest{5ExposedPorts: []string{"3306/tcp"},6WaitingFor: wait.ForLog("port: 3306 MySQL Community Server - GPL"),7}8mysqlContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9})10if err != nil {11panic(err)12}13defer mysqlContainer.Terminate(ctx)14ip, err := mysqlContainer.Host(ctx)15if err != nil {16panic(err)17}18port, err := mysqlContainer.MappedPort(ctx, "3306/tcp")19if err != nil {20panic(err)21}22fmt.Printf("mysql is available on %s:%s", ip, port.Port())23}
Format
Using AI Code Generation
1import (2func main() {3 fmt.Println(testcontainers.Format())4}5import (6func main() {7 fmt.Println(testcontainers.Format())8}9import (10func main() {11 fmt.Println(testcontainers.Format())12}13import (14func main() {15 fmt.Println(testcontainers.Format())16}17import (18func main() {19 fmt.Println(testcontainers.Format())20}21import (22func main() {23 fmt.Println(testcontainers.Format())24}25import (26func main() {27 fmt.Println(testcontainers.Format())28}29import (30func main() {31 fmt.Println(testcontainers.Format())32}33import (34func main() {35 fmt.Println(testcontainers.Format())36}37import (38func main() {39 fmt.Println(testcontainers.Format())40}41import (42func main() {43 fmt.Println(testcontainers.Format())44}45import (46func main() {47 fmt.Println(testcontainers.Format())48}
Format
Using AI Code Generation
1import (2func main() {3 fmt.Println(testcontainers.Format("test"))4}5import (6func main() {7 fmt.Println(testcontainers.Format("test"))8}9import (10func main() {11 fmt.Println(testcontainers.Format("test"))12}13import (14func main() {15 fmt.Println(testcontainers.Format("test"))16}17import (18func main() {19 fmt.Println(testcontainers.Format("test"))20}21import (22func main() {23 fmt.Println(testcontainers.Format("test"))24}25import (26func main() {27 fmt.Println(testcontainers.Format("test"))28}29import (30func main() {31 fmt.Println(testcontainers.Format("test"))32}33import (34func main() {35 fmt.Println(testcontainers.Format("test"))36}37import (38func main() {39 fmt.Println(testcontainers.Format("test"))40}41import (
Format
Using AI Code Generation
1import ( "fmt" "testcontainers" )2func main() {3fmt.Println(testcontainers.Format("Hello %s", "World"))4}5import ( "fmt" "testcontainers" )6func main() {7fmt.Println(testcontainers.Format("Hello %s", "World"))8}9import ( "fmt" "testcontainers" )10func main() {11fmt.Println(testcontainers.Format("Hello %s", "World"))12}13import ( "fmt" "testcontainers" )14func main() {15fmt.Println(testcontainers.Format("Hello %s", "World"))16}17import ( "fmt" "testcontainers" )18func main() {19fmt.Println(testcontainers.Format("Hello %s", "World"))20}21import ( "fmt" "testcontainers" )22func main() {23fmt.Println(testcontainers.Format("Hello %s", "World"))24}25import ( "fmt" "testcontainers" )26func main() {27fmt.Println(testcontainers.Format("Hello %s", "World"))28}29import ( "fmt" "testcontainers" )30func main() {31fmt.Println(testcontainers.Format("Hello %s", "World"))32}33import ( "fmt" "testcontainers" )34func main() {35fmt.Println(testcontainers.Format("Hello %s", "World"))36}37import ( "fmt" "testcontainers" )38func main() {39fmt.Println(testcontainers
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!!