How to use isDir method of testcontainers Package

Best Testcontainers-go code snippet using testcontainers.isDir

integration_test.go

Source:integration_test.go Github

copy

Full Screen

1//go:build integration_test2// +build integration_test3package util4import (5 "context"6 "fmt"7 "io"8 "io/ioutil"9 "os"10 "strings"11 "testing"12 "github.com/stretchr/testify/suite"13 "github.com/testcontainers/testcontainers-go"14)15const echoWithVersion = "github.com/labstack/echo/v4 v4.9.1"16var (17 dependencies = []string{18 echoWithVersion,19 "github.com/spf13/viper",20 }21)22type ZippingTestSuite struct {23 suite.Suite24 c testcontainers.Container25 mountPath string26 containerWorkingDir string27 folderName string28}29func TestUnzipping(t *testing.T) {30 suite.Run(t, new(ZippingTestSuite))31}32func (z *ZippingTestSuite) SetupSuite() {33 z.folderName = "testapp"34 err := os.Chdir("../../")35 z.Nil(err, "could not change directory")36}37func (z *ZippingTestSuite) SetupTest() {38 z.containerWorkingDir = "/go/test"39 temp, uuidErr := ioutil.TempDir("", "gotouch-test*")40 z.Nil(uuidErr, "could not create directory")41 z.mountPath = temp42 z.T().Log("mount:", z.mountPath)43 getwd := getWorkingDirectory()44 binaryName := "gotouch-linux-test"45 sourcePath := fmt.Sprintf("%s/%s", getwd, binaryName)46 targetPath := fmt.Sprintf("%s/gotouch", z.mountPath)47 _, err := z.copy(sourcePath, targetPath)48 z.Nil(err, "could not copy the binary")49 request := testcontainers.ContainerRequest{50 Image: "golang:latest",51 Cmd: []string{"sleep", "600000"},52 Mounts: testcontainers.ContainerMounts{53 {54 Source: testcontainers.GenericBindMountSource{55 HostPath: z.mountPath,56 },57 Target: testcontainers.ContainerMountTarget(z.containerWorkingDir),58 ReadOnly: false,59 },60 },61 }62 cnt, uuidErr := testcontainers.GenericContainer(context.Background(), testcontainers.GenericContainerRequest{63 ContainerRequest: request,64 Started: true,65 })66 z.NotNil(cnt, "Make sure docker is running")67 z.T().Log("commander:", fmt.Sprintf("docker exec -it %s /bin/bash", cnt.GetContainerID()))68 z.c = cnt69}70func getWorkingDirectory() string {71 getwd, _ := os.Getwd()72 return getwd73}74func (z *ZippingTestSuite) TestUnzipping() {75 z.moveToDirectory("testapp.txt")76 z.executeCommand()77 z.checkDefaultProjectStructure()78 z.checkModuleName("module testapp", dependencies)79}80func (z *ZippingTestSuite) TestGithub() {81 z.moveToDirectory("github-full-name.txt")82 z.executeCommand()83 z.checkDefaultProjectStructure()84 z.checkModuleName("module g.c/dg/testapp", dependencies)85}86func (z *ZippingTestSuite) checkDefaultProjectStructure() {87 directories := make([]string, 0)88 directories = append(directories, "api", "build", "cmd", "configs", "deployments", "web")89 directories = append(directories, "init", "internal", "pkg", "configs", "test", "vendor", "cmd/testapp/")90 z.checkDirectoriesExist(directories)91 files := make([]string, 0)92 files = append(files, "cmd/testapp/main.go", "go.mod", "Dockerfile")93 z.checkFilesExist(files)94 z.checkFileContent("Dockerfile", "Dockerfile")95 z.checkFileContent("test.txt", "test.txt")96}97func (z *ZippingTestSuite) checkFileContent(fileName, expectedFile string) {98 actualFilePath := fmt.Sprintf("%s/%s/%s", z.mountPath, z.folderName, fileName)99 actualFileContent, err := ioutil.ReadFile(actualFilePath)100 z.Nil(err)101 expectedFilePath := fmt.Sprintf("%s/internal/testdata/%s", getWorkingDirectory(), expectedFile)102 expectedFileContent, err := ioutil.ReadFile(expectedFilePath)103 z.Nil(err)104 z.EqualValues(expectedFileContent, actualFileContent)105}106func (z *ZippingTestSuite) checkModuleName(expectedModuleName string, dependencies []string) {107 open, err := os.ReadFile(fmt.Sprintf("%s/%s/go.mod", z.mountPath, z.folderName))108 z.Nil(err, "go module file not found")109 moduleContent := string(open)110 split := strings.Split(moduleContent, "\n")111 z.EqualValues(expectedModuleName, split[0], "Module name did not change: expected: %s, actual: %s", expectedModuleName, split[0])112 for _, dependency := range dependencies {113 z.True(strings.Contains(moduleContent, dependency))114 }115}116func (z *ZippingTestSuite) checkDirectoriesExist(directories []string) {117 for _, directory := range directories {118 directoryPath := fmt.Sprintf("%s/%s/%s", z.mountPath, z.folderName, directory)119 stat, err := os.Stat(directoryPath)120 z.Nil(err, "%s does not exists", directory)121 z.True(stat.IsDir(), "%s does not exists", directory)122 }123}124func (z *ZippingTestSuite) checkFilesExist(files []string) {125 for _, file := range files {126 stat, err := os.Stat(fmt.Sprintf("%s/%s/%s", z.mountPath, z.folderName, file))127 z.Nil(err, "%s does not exists", file)128 z.False(stat.IsDir(), "%s does not exists", file)129 }130}131func (z *ZippingTestSuite) executeCommand() {132 sprintf := fmt.Sprintf("%s/gotouch", z.containerWorkingDir)133 commander := []string{sprintf}134 i, err := z.c.Exec(context.Background(), commander)135 z.Nil(err, "could not execute commander", err, i)136}137func (z *ZippingTestSuite) moveToDirectory(fileName string) {138 source := fmt.Sprintf("%s/internal/testdata/%s", getWorkingDirectory(), fileName)139 target := fmt.Sprintf("%s/input.txt", z.mountPath)140 i, err := z.copy(source, target)141 z.Nil(err, i)142}143func (z *ZippingTestSuite) copy(src, dst string) (int64, error) {144 sourceFileStat, err := os.Stat(src)145 if err != nil {146 return 0, err147 }148 if !sourceFileStat.Mode().IsRegular() {149 return 0, fmt.Errorf("%s is not a regular file", src)150 }151 source, err := os.Open(src)152 if err != nil {153 return 0, err154 }155 defer source.Close()156 destination, err := os.Create(dst)157 if err != nil {158 return 0, err159 }160 defer destination.Close()161 nBytes, err := io.Copy(destination, source)162 err = os.Chmod(dst, os.ModePerm)163 return nBytes, err164}...

Full Screen

Full Screen

testutils.go

Source:testutils.go Github

copy

Full Screen

1// +build test2package testutils3import (4 "bufio"5 "context"6 "fmt"7 "os"8 "path/filepath"9 "strings"10 "time"11 "github.com/jackc/pgx/v4/pgxpool"12 "github.com/testcontainers/testcontainers-go"13 "github.com/testcontainers/testcontainers-go/wait"14)15func GetTestDb() (*pgxpool.Pool, error) {16 dsn := fmt.Sprintf("host=localhost port=%s dbname=space user=space password=secure pool_max_conns=99", os.Getenv("DB_TEST_PORT"))17 ctx := context.Background()18 db, err := pgxpool.Connect(ctx, dsn)19 if err != nil {20 return db, err21 }22 if err := db.Ping(ctx); err != nil {23 return db, err24 }25 return db, err26}27func SpinPostgresContainer(ctx context.Context, rootDir string) testcontainers.Container {28 mountFrom := mergeMigrations(rootDir)29 defer func() {30 if strings.HasSuffix(mountFrom, "test-db.init.sql") {31 os.Remove(mountFrom)32 }33 }()34 mountTo := "/docker-entrypoint-initdb.d/init.sql"35 req := testcontainers.ContainerRequest{36 Image: "postgres:13-alpine",37 ExposedPorts: []string{"5432/tcp"},38 BindMounts: map[string]string{mountFrom: mountTo},39 Env: map[string]string{40 "POSTGRES_DB": "space",41 "POSTGRES_USER": "space",42 "POSTGRES_PASSWORD": "secure",43 },44 WaitingFor: wait.ForLog("database system is ready to accept connections"),45 }46 postgresContainer, err := testcontainers.GenericContainer(47 ctx,48 testcontainers.GenericContainerRequest{ContainerRequest: req, Started: true},49 )50 if err != nil {51 panic(err)52 }53 p, _ := postgresContainer.MappedPort(ctx, "5432")54 os.Setenv("DB_TEST_PORT", p.Port())55 // added this sleep here :(56 // better to find a way to proper wait57 time.Sleep(5 * time.Second)58 return postgresContainer59}60func mergeMigrations(root string) string {61 var alllines []string62 err := filepath.Walk(root+"migrations/", func(path string, info os.FileInfo, err error) error {63 if info.IsDir() {64 return nil65 }66 lines, err := readLines(path)67 if err != nil {68 return err69 }70 for _, l := range lines {71 if !strings.HasPrefix(l, "----") {72 alllines = append(alllines, l)73 } else {74 break75 }76 }77 return nil78 })79 if err != nil {80 panic(err)81 }82 resultPath := root + "test-db.init.sql"83 if err := writeLines(alllines, resultPath); err != nil {84 panic(err)85 }86 return resultPath87}88func readLines(path string) ([]string, error) {89 file, err := os.Open(path)90 if err != nil {91 return nil, err92 }93 defer file.Close()94 var lines []string95 scanner := bufio.NewScanner(file)96 for scanner.Scan() {97 lines = append(lines, scanner.Text())98 }99 return lines, scanner.Err()100}101func writeLines(lines []string, path string) error {102 file, err := os.Create(path)103 if err != nil {104 return err105 }106 defer file.Close()107 w := bufio.NewWriter(file)108 for _, line := range lines {109 fmt.Fprintln(w, line)110 }111 return w.Flush()112}...

Full Screen

Full Screen

common.go

Source:common.go Github

copy

Full Screen

1package tc2import (3 "database/sql"4 "fmt"5 "github.com/GoncharovMikhail/go-sql/const/test"6 "github.com/GoncharovMikhail/go-sql/pkg/db/sql/util"7 "github.com/docker/go-connections/nat"8 "github.com/gofrs/uuid"9 "github.com/testcontainers/testcontainers-go"10 "github.com/testcontainers/testcontainers-go/wait"11 "log"12 "os"13 "path/filepath"14 "time"15)16const (17 version = "14.1-alpine"18 postgres = "postgres"19 pgUsername = postgres20 pgPassword = "password"21 pgPort = "5432"22)23var (24 randomUuid uuid.UUID25 container testcontainers.Container26 db *sql.DB27)28func InitUuid() uuid.UUID {29 var err error30 randomUuid, err = uuid.NewV1()31 if err != nil {32 log.Panicf("couln't generate random uuid. err: %s", err)33 }34 return randomUuid35}36func getInitDbScriptsDir() string {37 goModDir, err := util.GetGoModDir()38 if err != nil {39 log.Panic(err)40 }41 initDbFiles, errors := util.ListAllFilesMatchingPatternsAllOverOsFromSpecifiedDir(42 goModDir,43 func(info os.FileInfo) bool { return !info.IsDir() },44 util.Conjunction,45 ".*/resources/migrations.*", "up.sql",46 )47 if errors != nil {48 log.Panic(errors)49 }50 //todo51 return filepath.Dir(initDbFiles[0])52}53func InitContainer() testcontainers.Container {54 initDbScriptsDir := getInitDbScriptsDir()55 var err error56 req := testcontainers.GenericContainerRequest{57 ContainerRequest: testcontainers.ContainerRequest{58 Image: postgres + ":" + version,59 ExposedPorts: []string{pgPort},60 Cmd: []string{"postgres", "-c", "fsync=off"},61 Env: map[string]string{62 "POSTGRES_DB": postgres,63 "POSTGRES_USER": pgUsername,64 "POSTGRES_PASSWORD": pgPassword,65 },66 BindMounts: map[string]string{67 "/docker-entrypoint-initdb.d": initDbScriptsDir,68 },69 WaitingFor: wait.ForSQL(pgPort, postgres, func(port nat.Port) string {70 return fmt.Sprintf("%s://%s:%s@localhost:%s/%s?sslmode=disable", postgres, pgUsername, pgPassword, port.Port(), postgres)71 }).Timeout(time.Second * 5),72 AutoRemove: true,73 },74 Started: true,75 }76 container, err = testcontainers.GenericContainer(test.CTX, req)77 if err != nil {78 log.Panicf("failed to start container: %s", err)79 }80 return container81}82func getMappedPort() nat.Port {83 if container == nil {84 log.Panicf("container is nil")85 }86 mappedPort, err := container.MappedPort(test.CTX, pgPort)87 if err != nil {88 log.Panicf("failed to get container external pgPort: %s", err)89 }90 return mappedPort91}92func InitDb() *sql.DB {93 mappedPort := getMappedPort()94 var err error95 url := fmt.Sprintf("%s://%s:%s@localhost:%s/%s?sslmode=disable", postgres, pgUsername, pgPassword, mappedPort.Port(), postgres)96 db, err = sql.Open("postgres", url)97 if err != nil {98 log.Panicf("failed to oped db: %s", err)99 }100 return db101}...

Full Screen

Full Screen

isDir

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 Cmd: []string{"tail", "-f", "/dev/null"},6 WaitingFor: wait.ForLog("ready"),7 }8 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer container.Terminate(ctx)14 ip, err := container.Host(ctx)15 if err != nil {16 panic(err)17 }18 fmt.Printf("Container IP: %s", ip)19}20require (

Full Screen

Full Screen

isDir

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"5432/tcp"},6 WaitingFor: wait.ForLog("database system is ready to accept connections"),7 }8 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer postgresContainer.Terminate(ctx)14 postgresPort, err := postgresContainer.MappedPort(ctx, "5432")15 if err != nil {16 panic(err)17 }18 postgresHost, err := postgresContainer.Host(ctx)19 if err != nil {20 panic(err)21 }22}

Full Screen

Full Screen

isDir

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"6379/tcp"},6 WaitingFor: wait.ForListeningPort("6379/tcp"),7 }8 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer container.Terminate(ctx)14 ip, err := container.Host(ctx)15 if err != nil {16 panic(err)17 }18 port, err := container.MappedPort(ctx, "6379/tcp")19 if err != nil {20 panic(err)21 }22 fmt.Println(ip, port.Int())23}

Full Screen

Full Screen

isDir

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(testcontainers.IsDir("/home/"))4 fmt.Println(testcontainers.IsDir("/home"))5 fmt.Println(testcontainers.IsDir("/home/test"))6}7import (8func main() {9 fmt.Println(testcontainers.IsFile("/home/"))10 fmt.Println(testcontainers.IsFile("/home"))11 fmt.Println(testcontainers.IsFile("/home/test"))12}13import (14func main() {15 fmt.Println(testcontainers.IsSocket("/home/"))16 fmt.Println(testcontainers.IsSocket("/home"))17 fmt.Println(testcontainers.IsSocket("/home/test"))18}19import (20func main() {21 fmt.Println(testcontainers.IsSymlink("/home/"))22 fmt.Println(testcontainers.IsSymlink("/home"))23 fmt.Println(testcontainers.IsSymlink("/home/test"))24}

Full Screen

Full Screen

isDir

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 wd, err := os.Getwd()4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println("Current working directory:", wd)8 dirExists := testcontainers.IsDir(wd)9 fmt.Println("Directory exists:", dirExists)10 parentDir := filepath.Dir(wd)11 fmt.Println("Parent directory:", parentDir)12 parentDirExists := testcontainers.IsDir(parentDir)13 fmt.Println("Parent directory exists:", parentDirExists)14}15import (16func main() {17 tempDir, err := ioutil.TempDir("", "testcontainers")18 if err != nil {19 fmt.Println(err)20 }21 fmt.Println("Temporary directory:", tempDir)22 tempDirExists := testcontainers.IsDir(tempDir)23 fmt.Println("Temporary directory exists:", tempDirExists)24 err = os.RemoveAll(tempDir)25 if err != nil {26 fmt.Println(err)27 }28 tempDirExists = testcontainers.IsDir(tempDir)29 fmt.Println("Temporary directory exists:", tempDirExists)30 parentDir := filepath.Dir(tempDir)31 fmt.Println("Parent directory:", parentDir)32 parentDirExists := testcontainers.IsDir(parentDir)33 fmt.Println("Parent directory exists:", parentDirExists)34}

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testcontainers-go automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful