Best Selenoid code snippet using main.testConfig
terraform_binary_test.go
Source:terraform_binary_test.go
...47 }48 }49 buildEnvFile := "full-env"50 var params = StringMap{51 "Org": testConfig.VCD.Org,52 "Vdc": testConfig.VCD.Vdc,53 "ProviderVdc": testConfig.VCD.ProviderVdc.Name,54 "NetworkPool": testConfig.VCD.ProviderVdc.NetworkPool,55 "StorageProfile": testConfig.VCD.ProviderVdc.StorageProfile,56 "Catalog": testConfig.VCD.Catalog.Name,57 "CatalogItem": testConfig.VCD.Catalog.CatalogItem,58 "OvaPath": testConfig.Ova.OvaPath,59 "MediaPath": testConfig.Media.MediaPath,60 "MediaUploadPieceSize": testConfig.Media.UploadPieceSize,61 "MediaUploadProgress": testConfig.Media.UploadProgress,62 "OvaDownloadUrl": testConfig.Ova.OvaDownloadUrl,63 "OvaTestFileName": testConfig.Ova.OvaTestFileName,64 "OvaUploadProgress": testConfig.Ova.UploadProgress,65 "OvaUploadPieceSize": testConfig.Ova.UploadPieceSize,66 "OvaPreserve": testConfig.Ova.Preserve,67 "LoggingEnabled": testConfig.Logging.Enabled,68 "LoggingFileName": testConfig.Logging.LogFileName,69 "EdgeGateway": testConfig.Networking.EdgeGateway,70 "SharedSecret": testConfig.Networking.SharedSecret,71 "ExternalNetwork": testConfig.Networking.ExternalNetwork,72 "ExternalNetworkPortGroup": testConfig.Networking.ExternalNetworkPortGroup,73 "ExternalNetworkPortGroupType": testConfig.Networking.ExternalNetworkPortGroupType,74 "ExternalIp": testConfig.Networking.ExternalIp,75 "InternalIp": testConfig.Networking.InternalIp,76 "Vcenter": testConfig.Networking.Vcenter,77 "LocalIp": testConfig.Networking.Local.LocalIp,78 "LocalGateway": testConfig.Networking.Local.LocalSubnetGateway,79 "PeerIp": testConfig.Networking.Peer.PeerIp,80 "PeerGateway": testConfig.Networking.Peer.PeerSubnetGateway,81 "MaxRetryTimeout": testConfig.Provider.MaxRetryTimeout,82 "AllowInsecure": testConfig.Provider.AllowInsecure,83 "ProviderSysOrg": testConfig.Provider.SysOrg,84 "ProviderUrl": testConfig.Provider.Url,85 "ProviderUser": testConfig.Provider.User,86 "ProviderPassword": testConfig.Provider.Password,87 "ProviderSamlUser": testConfig.Provider.SamlUser,88 "ProviderSamlPassword": testConfig.Provider.SamlPassword,89 "ProviderSamlRptId": testConfig.Provider.SamlCustomRptId,90 "Tags": "custom",91 "Prefix": "cust",92 "CallerFileName": "",93 // The following properties are used to create a full environment94 "MainGateway": testConfig.TestEnvBuild.Gateway,95 "MainNetmask": testConfig.TestEnvBuild.Netmask,96 "MainDns1": testConfig.TestEnvBuild.Dns1,97 "MainDns2": testConfig.TestEnvBuild.Dns2,98 "MediaTestName": testConfig.TestEnvBuild.MediaName,99 "StorageProfile2": testConfig.VCD.ProviderVdc.StorageProfile2,100 "ExternalNetworkStartIp": testConfig.TestEnvBuild.ExternalNetworkStartIp,101 "ExternalNetworkEndIp": testConfig.TestEnvBuild.ExternalNetworkEndIp,102 "RoutedNetwork": testConfig.TestEnvBuild.RoutedNetwork,103 "IsolatedNetwork": testConfig.TestEnvBuild.IsolatedNetwork,104 "DirectNetwork": testConfig.TestEnvBuild.DirectNetwork,105 "OrgUser": testConfig.TestEnvBuild.OrgUser,106 "OrgUserPassword": testConfig.TestEnvBuild.OrgUserPassword,107 }108 // optional fields109 if testConfig.TestEnvBuild.MediaName == "" {110 delete(params, "MediaTestName")111 }112 if testConfig.VCD.ProviderVdc.StorageProfile2 == "" {113 delete(params, "StorageProfile2")114 }115 if testConfig.TestEnvBuild.RoutedNetwork == "" {116 delete(params, "RoutedNetwork")117 }118 if testConfig.TestEnvBuild.IsolatedNetwork == "" {119 delete(params, "IsolatedNetwork")120 }121 if testConfig.TestEnvBuild.DirectNetwork == "" {122 delete(params, "DirectNetwork")123 }124 // If either the org user or the password fields are blank, we remove both125 if testConfig.TestEnvBuild.OrgUser == "" || testConfig.TestEnvBuild.OrgUserPassword == "" {126 delete(params, "OrgUser")127 delete(params, "OrgUserPassword")128 }129 for _, fileName := range binaryTestList {130 baseName := strings.Replace(path.Base(fileName), ".tf", "", -1)131 usingBuildFile := baseName == buildEnvFile132 targetScript := path.Join(testArtifactsDirectory, params["Prefix"].(string)+"."+baseName+".tf")133 // It the target file exists, we remove it, as we need a fresh one to be generated134 if fileExists(targetScript) {135 err := os.Remove(targetScript)136 if err != nil {137 t.Logf("error removing %s\n", targetScript)138 panic("can't remove essential file")139 }140 }141 sourceFile := path.Join(getCurrentDir(), customTemplatesDirectory, fileName)142 templateText, err := readFile(sourceFile)143 if err != nil {144 t.Logf("error reading from %s: %s", fileName, err)145 }146 params["FuncName"] = baseName147 reHasProvider := regexp.MustCompile(`(?m)^\s*provider\s+"`)148 // If there is already a provider in the template, we exit149 if reHasProvider.MatchString(templateText) {150 fmt.Printf("File %s has already a provider: remove it and try again\n", sourceFile)151 fmt.Println("The provider will be generated using data from configuration file")152 continue153 }154 setEnvValues()155 params["CallerFileName"] = sourceFile156 if usingBuildFile {157 extraPieces := map[string]string{158 "Routed": buildEnvRoutedNetwork,159 "Isolated": buildEnvIsolatedNetwork,160 "Direct": buildEnvDirectNetwork,161 }162 // If any of the optional network names are filled,163 // the corresponding creation template is added164 // to the main one165 for key, value := range extraPieces {166 _, ok := params[key+"Network"]167 if ok {168 templateText = fmt.Sprintf("%s\n%s", templateText, value)169 }170 }171 // If a second storage profile was defined, we add the corresponding172 // text inside the VDC definition173 secondStorageProfileText := ""174 secondStorageParam, ok := params["StorageProfile2"]175 if ok && secondStorageParam != "" {176 secondStorageProfileText = secondStorageProfile177 }178 reSecondStorage := regexp.MustCompile(`#_SECOND_STORAGE_PROFILE_`)179 templateText = reSecondStorage.ReplaceAllString(templateText, secondStorageProfileText)180 // The media item will only be created if its name was defined in the configuration file181 mediaTestText := ""182 mediaTestParam, ok := params["MediaTestName"]183 if ok && mediaTestParam != "" {184 mediaTestText = mediaTest185 }186 reMediaTest := regexp.MustCompile(`#_MEDIA_TEST_`)187 templateText = reMediaTest.ReplaceAllString(templateText, mediaTestText)188 // The Org user will be created only if both user name and password were defined189 orgUserText := ""190 orgUserParam, ok := params["OrgUser"]191 if ok && orgUserParam != "" {192 orgUserText = buildEnvOrgUser193 }194 reOrgUserTest := regexp.MustCompile(`#_ORG_USER_`)195 templateText = reOrgUserTest.ReplaceAllString(templateText, orgUserText)196 // For some items, we want a different value for testing and for building197 // For example, the Ova for testing might be a tiny one, while the one for198 // building the environment would be a beefier one, which can also run the199 // VMware tools.200 if testConfig.TestEnvBuild.ExternalNetworkStartIp == "" {201 params["ExternalNetworkStaticStartIp"] = testConfig.Networking.ExternalIp202 if testConfig.TestEnvBuild.ExternalNetworkEndIp == "" {203 params["ExternalNetworkStaticEndIp"] = testConfig.Networking.ExternalIp204 }205 }206 if testConfig.TestEnvBuild.MediaPath != "" {207 params["MediaPath"] = testConfig.TestEnvBuild.MediaPath208 }209 if testConfig.TestEnvBuild.OvaPath != "" {210 params["OvaPath"] = testConfig.TestEnvBuild.OvaPath211 }212 if testConfig.TestEnvBuild.ExternalNetworkPortGroupType != "" {213 params["ExternalNetworkPortGroupType"] = testConfig.TestEnvBuild.ExternalNetworkPortGroupType214 }215 if testConfig.TestEnvBuild.ExternalNetworkPortGroup != "" {216 params["ExternalNetworkPortGroup"] = testConfig.TestEnvBuild.ExternalNetworkPortGroup217 }218 essentialData := []string{219 "Org", "Vdc", "Catalog", "CatalogItem", "ExternalNetwork", "EdgeGateway",220 "ProviderVdc", "NetworkPool", "StorageProfile", "Vcenter",221 "MainGateway", "MainNetmask", "MainDns1", "ExternalNetworkStartIp", "ExternalNetworkEndIp"}222 for _, essentialItem := range essentialData {223 _, ok := params[essentialItem]224 if ok {225 // By deleting the empty item, we will make sure that the226 // filled script will contain a warning227 if params[essentialItem] == "" {228 delete(params, essentialItem)229 }230 }231 }232 } else {233 params["MediaPath"] = testConfig.Media.MediaPath234 params["OvaPath"] = testConfig.Ova.OvaPath235 params["ExternalNetworkPortGroupType"] = testConfig.Networking.ExternalNetworkPortGroupType236 params["ExternalNetworkPortGroup"] = testConfig.Networking.ExternalNetworkPortGroup237 }238 // We create the configuration text only for the side effect of it being239 // written to the test-artifacts folder240 configText := templateFill(templateText, params)241 // Restore original values in env variables242 restoreEnvValues()243 debugPrintf("%s\n", configText)244 if !fileExists(targetScript) {245 panic(fmt.Sprintf("error: file %s was not generated\n", targetScript))246 }247 fmt.Printf("File: %s\n", targetScript)248 }249}250func init() {...
main_test.go
Source:main_test.go
1package main2import (3 "bufio"4 "context"5 "fmt"6 "net/http"7 "os"8 "strconv"9 "strings"10 "syscall"11 "testing"12 "time"13 "github.com/gin-gonic/gin"14 cmap "github.com/orcaman/concurrent-map"15 "github.com/spf13/viper"16 "github.com/stretchr/testify/assert"17 "github.com/stretchr/testify/require"18)19func clear() {20 viper.Reset()21 pwd, _ := os.Getwd()22 test_folder := strings.ReplaceAll(BACKUP_TEST_FOLDER, HOME, pwd)23 err := RemoveContents(test_folder)24 if err != nil {25 fmt.Println("Error cleaning up: ", err.Error())26 }27 test_folder = strings.ReplaceAll(GIT_TEST_FOLDER, HOME, pwd)28 err = RemoveContents(test_folder)29 if err != nil {30 fmt.Println("Error cleaning up: ", err.Error())31 }32 os.Remove(test_folder)33 test_folder = strings.ReplaceAll(GIT_TEST_FOLDER_VIMRC, HOME, pwd)34 err = RemoveContents(test_folder)35 if err != nil {36 fmt.Println("Error cleaning up: ", err.Error())37 }38 os.Remove(test_folder)39 forbidden = false40 os.Remove("AGENT_ADDRESS")41 os.Remove("AGENT_DURATION")42 os.Remove("AGENT_PATHDB")43 os.Remove("AGENT_MOUNT_DURATION")44 os.Remove("AGENT_MOUNT_ALLOW")45 os.Remove("AGENT_VAULT_ROLE_ID")46 os.Remove("AGENT_VAULT_SECRET_ID")47}48func TestMainInit(t *testing.T) {49 fmt.Println("running: TestMainInit")50 t.Cleanup(clear)51 testconfig := readConfig(t)52 hostname, err := os.Hostname()53 require.NoError(t, err)54 // Test with flags55 var args []string56 args = append(args, "--address="+MAIN_TEST_ADDRESS)57 args = append(args, "--pathdb="+MAIN_TEST_PATHDB)58 args = append(args, "--duration="+MAIN_TEST_DURATION)59 args = append(args, "--mount_duration="+MAIN_TEST_MOUNT_DURATION)60 args = append(args, "--mount_allow="+MAIN_TEST_MOUNT_ALLOW)61 args = append(args, "--vault_role_id="+VAULT_TEST_ROLE_ID)62 args = append(args, "--vault_secret_id="+VAULT_TEST_SECRET_ID)63 err = Init(testconfig.config, args)64 require.NoError(t, err)65 assert.Equal(t, hostname, AgentConfiguration.Hostname)66 assert.Equal(t, MAIN_TEST_ADDRESS, AgentConfiguration.Address)67 assert.Equal(t, MAIN_TEST_PATHDB, AgentConfiguration.PathDB)68 assert.Equal(t, false, AgentConfiguration.MountAllow)69 assert.Equal(t, MAIN_TEST_MOUNT_DURATION, AgentConfiguration.MountDuration)70 assert.Equal(t, VAULT_TEST_SECRET_ID, AgentConfiguration.SecretID)71 assert.Equal(t, VAULT_TEST_ROLE_ID, AgentConfiguration.RoleID)72 assert.True(t, AgentConfiguration.useLogin)73 dur, err := time.ParseDuration("1h30m")74 assert.NoError(t, err)75 assert.Equal(t, AgentConfiguration.TimeBetweenStart, dur)76 length := len(os.Args)77 os.Args = os.Args[:length-1]78 // Test with Environment variables79 os.Setenv("AGENT_ADDRESS", MAIN_TEST_ADDRESS)80 os.Setenv("AGENT_PATHDB", MAIN_TEST_PATHDB)81 os.Setenv("AGENT_DURATION", MAIN_TEST_DURATION)82 os.Setenv("AGENT_MOUNT_DURATION", MAIN_TEST_MOUNT_DURATION)83 os.Setenv("AGENT_MOUNT_ALLOW", MAIN_TEST_MOUNT_ALLOW)84 os.Setenv("AGENT_VAULT_ROLE_ID", VAULT_TEST_ROLE_ID)85 os.Setenv("AGENT_VAULT_SECRET_ID", VAULT_TEST_SECRET_ID)86 err = Init(testconfig.config, nil)87 require.NoError(t, err)88 assert.Equal(t, hostname, AgentConfiguration.Hostname)89 assert.Equal(t, MAIN_TEST_ADDRESS, AgentConfiguration.Address)90 assert.Equal(t, MAIN_TEST_PATHDB, AgentConfiguration.PathDB)91 assert.Equal(t, dur, AgentConfiguration.TimeBetweenStart)92 assert.Equal(t, false, AgentConfiguration.MountAllow)93 assert.Equal(t, MAIN_TEST_MOUNT_DURATION, AgentConfiguration.MountDuration)94 assert.Equal(t, VAULT_TEST_SECRET_ID, AgentConfiguration.SecretID)95 assert.Equal(t, VAULT_TEST_ROLE_ID, AgentConfiguration.RoleID)96 assert.True(t, AgentConfiguration.useLogin)97}98func TestMainStart(t *testing.T) {99 fmt.Println("running: TestMainStart")100 t.Cleanup(clear)101 jobmap = cmap.New()102 gin.SetMode(gin.TestMode)103 testconfig := readConfig(t)104 os.Setenv("AGENT_ADDRESS", MAIN_TEST_ADDRESS)105 os.Setenv("AGENT_DURATION", testconfig.Duration)106 os.Setenv("AGENT_PATHDB", "./test/DB")107 os.Setenv("AGENT", MAIN_TEST_MOUNT_DURATION)108 os.Setenv("AGENT", MAIN_TEST_MOUNT_ALLOW)109 os.Setenv("AGENT_VAULT_ROLE_ID", VAULT_TEST_ROLE_ID)110 os.Setenv("AGENT_VAULT_SECRET_ID", VAULT_TEST_SECRET_ID)111 err := Init(testconfig.config, os.Args)112 require.NoError(t, err)113 _, err = Unseal(testconfig.config, testconfig.secret)114 require.NoError(t, err)115 AgentConfiguration.DB = InitDB("", "", true)116 server, fun := RunRestServer(MAIN_TEST_ADDRESS)117 go fun()118 Start()119 time.Sleep(1 * time.Millisecond)120 assert.Eventually(t, func() bool { return checkJobmap("check") },121 time.Duration(20*time.Second), time.Duration(1*time.Second))122 err = server.Shutdown(context.Background())123 assert.NoError(t, err)124 AgentConfiguration.DB.Close()125 assert.NoError(t, err)126 err = RemoveContents("./test/DB/")127 assert.NoError(t, err)128 assert.NoFileExists(t, "./test/DB/MANIFEST")129 time.Sleep(1 * time.Millisecond)130}131func TestMainMain(t *testing.T) {132 fmt.Println("running: TestMainMain")133 t.Cleanup(func() {134 os.Remove(MAIN_TEST_KEYFILE_PATH)135 clear()136 })137 gin.SetMode(gin.TestMode)138 testconfig := readConfig(t)139 os.Setenv("AGENT_ADDRESS", MAIN_TEST_ADDRESS)140 os.Setenv("AGENT_DURATION", testconfig.Duration)141 os.Setenv("AGENT_PATHDB", "./test/DB")142 os.Setenv("AGENT_MOUNT_DURATION", MAIN_TEST_MOUNT_DURATION)143 os.Setenv("AGENT_MOUNT_ALLOW", MAIN_TEST_MOUNT_ALLOW)144 os.Setenv("AGENT_VAULT_ROLE_ID", VAULT_TEST_ROLE_ID)145 os.Setenv("AGENT_VAULT_SECRET_ID", VAULT_TEST_SECRET_ID)146 os.Setenv("AGENT_VAULT_KEY_FILE", MAIN_TEST_KEYFILE_PATH)147 multipleKey = true148 sealStatus = true149 Progress = 0150 home, err := os.Getwd()151 require.NoError(t, err)152 f, err := os.Create(MAIN_TEST_KEYFILE_PATH)153 require.NoError(t, err)154 w := bufio.NewWriter(f)155 key := "test"156 for i := 1; i < 6; i++ {157 _, err := w.WriteString(key + strconv.Itoa(i) + "\n")158 assert.NoError(t, err)159 }160 err = w.Flush()161 assert.NoError(t, err)162 require.FileExists(t, MAIN_TEST_KEYFILE_PATH)163 go main()164 time.Sleep(1 * time.Second)165 AgentConfiguration.VaultConfig = testconfig.config166 sendingGet(t, REST_TEST_PING, http.StatusOK)167 time.Sleep(10 * time.Second)168 assert.Eventually(t, checkContents, 120*time.Second, 1*time.Second)169 assert.Eventually(t, func() bool { return checkJobmap("check") },170 120*time.Second, 1*time.Second)171 stopChan <- syscall.SIGINT172 time.Sleep(10 * time.Second)173 test_mountpath := strings.ReplaceAll(GOCRYPT_TEST_MOUNTPATH, "~", home)174 err = IsEmpty(home, test_mountpath)175 assert.NoError(t, err)176 assert.False(t, sealStatus)177 err = server.Shutdown(context.Background())178 assert.NoError(t, err)179 err = RemoveContents("./test/DB/")180 assert.NoError(t, err)181 assert.NoFileExists(t, "./test/DB/MANIFEST")182 time.Sleep(1 * time.Millisecond)183 multipleKey = false184}185func TestMainCheckKeyFile(t *testing.T) {186 fmt.Println("Running: TestMainCheckKeyFile")187 t.Cleanup(func() {188 os.Remove(MAIN_TEST_KEYFILE_PATH)189 clear()190 })191 AgentConfiguration.DB = InitDB("", "", true)192 require.NotNil(t, AgentConfiguration.DB)193 require.NoFileExists(t, MAIN_TEST_KEYFILE_PATH)194 err := CheckKeyFile(MAIN_TEST_KEYFILE_PATH)195 assert.Error(t, err)196 f, err := os.Create(MAIN_TEST_KEYFILE_PATH)197 require.NoError(t, err)198 w := bufio.NewWriter(f)199 key := "test"200 for i := 1; i < 6; i++ {201 _, err := w.WriteString(key + strconv.Itoa(i) + "\n")202 assert.NoError(t, err)203 }204 err = w.Flush()205 assert.NoError(t, err)206 require.FileExists(t, MAIN_TEST_KEYFILE_PATH)207 err = CheckKeyFile(MAIN_TEST_KEYFILE_PATH)208 assert.NoError(t, err)209 ok := CheckSealKey(AgentConfiguration.DB, 5)210 assert.True(t, ok)211}212func TestMainBackupRepositoryExists(t *testing.T) {213 fmt.Println("running: TestMainBackupRepositoryExists")214 t.Cleanup(clear)215 jobmap = cmap.New()216 gin.SetMode(gin.TestMode)217 testconfig := readConfig(t)218 os.Setenv("AGENT_ADDRESS", MAIN_TEST_ADDRESS)219 os.Setenv("AGENT_DURATION", testconfig.Duration)220 os.Setenv("AGENT_PATHDB", "./test/DB")221 os.Setenv("AGENT_MOUNT_DURATION", MAIN_TEST_MOUNT_DURATION)222 os.Setenv("AGENT_VAULT_ROLE_ID", VAULT_TEST_ROLE_ID)223 os.Setenv("AGENT_VAULT_SECRET_ID", VAULT_TEST_SECRET_ID)224 os.Setenv("AGENT_MOUNT_ALLOW", MAIN_TEST_MOUNT_ALLOW)225 err := Init(testconfig.config, os.Args)226 require.NoError(t, err)227 _, err = Unseal(testconfig.config, testconfig.secret)228 require.NoError(t, err)229 pwd, err := os.Getwd()230 require.NoError(t, err)231 AgentConfiguration.DB = InitDB("", "", true)232 server, fun := RunRestServer(MAIN_TEST_ADDRESS)233 go fun()234 time.Sleep(1 * time.Millisecond)235 BackupRepositoryExists(VAULT_TEST_TOKEN)236 assert.Eventually(t, func() bool {237 path := strings.ReplaceAll(BACKUP_TEST_CONF_FILE, HOME, pwd)238 stat, err := os.Stat(path)239 if err != nil {240 return false241 }242 return !stat.IsDir()243 },244 time.Duration(20*time.Second), time.Duration(1*time.Second))245 err = server.Shutdown(context.Background())246 assert.NoError(t, err)247 AgentConfiguration.DB.Close()248 assert.NoError(t, err)249 err = RemoveContents("./test/DB/")250 assert.NoError(t, err)251 assert.NoFileExists(t, "./test/DB/MANIFEST")252 time.Sleep(1 * time.Millisecond)253}254func TestMainCheckBackupRepository(t *testing.T) {255 fmt.Println("running: TestMainCheckBackupRepository")256 t.Cleanup(clear)257 jobmap = cmap.New()258 gin.SetMode(gin.TestMode)259 testconfig := readConfig(t)260 os.Setenv("AGENT_ADDRESS", MAIN_TEST_ADDRESS)261 os.Setenv("AGENT_DURATION", testconfig.Duration)262 os.Setenv("AGENT_PATHDB", "./test/DB")263 os.Setenv("AGENT_MOUNT_DURATION", MAIN_TEST_MOUNT_DURATION)264 os.Setenv("AGENT_MOUNT_ALLOW", MAIN_TEST_MOUNT_ALLOW)265 os.Setenv("AGENT_VAULT_ROLE_ID", VAULT_TEST_ROLE_ID)266 os.Setenv("AGENT_VAULT_SECRET_ID", VAULT_TEST_SECRET_ID)267 err := Init(testconfig.config, os.Args)268 require.NoError(t, err)269 _, err = Unseal(testconfig.config, testconfig.secret)270 require.NoError(t, err)271 AgentConfiguration.DB = InitDB("", "", true)272 time.Sleep(1 * time.Millisecond)273 CheckBackupRepository()274 assert.Eventually(t, func() bool {275 timestamp, err := GetTimestamp(AgentConfiguration.DB)276 if err != nil {277 return false278 }279 return timestamp != time.Unix(0, 0)280 },281 time.Duration(20*time.Second), time.Duration(1*time.Second))282 err = server.Shutdown(context.Background())283 assert.NoError(t, err)284 AgentConfiguration.DB.Close()285 assert.NoError(t, err)286 err = RemoveContents("./test/DB/")287 assert.NoError(t, err)288 assert.NoFileExists(t, "./test/DB/MANIFEST")289 time.Sleep(1 * time.Millisecond)290}291func TestMainGitCheckout(t *testing.T) {292 fmt.Println("Running: TestMainGitCheckout")293 t.Cleanup(clear)294 jobmap = cmap.New()295 gin.SetMode(gin.TestMode)296 testconfig := readConfig(t)297 os.Setenv("AGENT_ADDRESS", MAIN_TEST_ADDRESS)298 os.Setenv("AGENT_DURATION", testconfig.Duration)299 os.Setenv("AGENT_PATHDB", "./test/DB")300 os.Setenv("AGENT_MOUNT_DURATION", MAIN_TEST_MOUNT_DURATION)301 os.Setenv("AGENT_VAULT_ROLE_ID", VAULT_TEST_ROLE_ID)302 os.Setenv("AGENT_VAULT_SECRET_ID", VAULT_TEST_SECRET_ID)303 os.Setenv("AGENT_MOUNT_ALLOW", MAIN_TEST_MOUNT_ALLOW)304 err := Init(testconfig.config, os.Args)305 require.NoError(t, err)306 _, err = Unseal(testconfig.config, testconfig.secret)307 require.NoError(t, err)308 pwd, err := os.Getwd()309 require.NoError(t, err)310 AgentConfiguration.DB = InitDB("", "", true)311 server, fun := RunRestServer(MAIN_TEST_ADDRESS)312 go fun()313 time.Sleep(1 * time.Millisecond)314 GitCheckout()315 assert.Eventually(t, func() bool {316 path := strings.ReplaceAll(GIT_TEST_FOLDER, HOME, pwd)317 f, err := os.Stat(path + "/.git")318 if err != nil {319 return false320 }321 return f.IsDir()322 },323 time.Duration(20*time.Second), time.Duration(1*time.Second))324 GitCheckout()325 assert.Eventually(t, func() bool { return checkJobmap("pull") },326 time.Duration(20*time.Second), time.Duration(1*time.Second))327 err = server.Shutdown(context.Background())328 assert.NoError(t, err)329 AgentConfiguration.DB.Close()330 assert.NoError(t, err)331 err = RemoveContents("./test/DB/")332 assert.NoError(t, err)333 assert.NoFileExists(t, "./test/DB/MANIFEST")334 time.Sleep(1 * time.Millisecond)335}336func checkJobmap(jobname string) bool {337 for item := range jobmap.IterBuffered() {338 if strings.Contains(item.Key, jobname) {339 j := item.Val.(*Job)340 return j.IsFinished()341 }342 }343 return false344}345func checkContents() bool {346 home, err := os.Getwd()347 if err != nil {348 return false349 }350 err = IsEmpty(home, GOCRYPT_TEST_MOUNTPATH)351 if err != nil {352 return false353 }354 err = IsEmpty(home, BACKUP_TEST_FOLDER)355 if err != nil {356 return false357 }358 return true359}...
d18n_test.go
Source:d18n_test.go
1/*2 * Copyright(c) 2021 Lianjia, Inc. All Rights Reserved3 * Licensed under the Apache License, Version 2.0 (the "License");4 * you may not use this file except in compliance with the License.5 * You may obtain a copy of the License at6 * http://www.apache.org/licenses/LICENSE-2.07 * Unless required by applicable law or agreed to in writing, software8 * distributed under the License is distributed on an "AS IS" BASIS,9 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10 * See the License for the specific language governing permissions and11 * limitations under the License.12 */13package main14import (15 "os"16 "testing"17 "github.com/LianjiaTech/d18n/common"18)19func init() {20 common.InitTestEnv()21}22func TestMainSave(t *testing.T) {23 orgCfg := common.TestConfig24 orgArgs := os.Args25 args := []string{26 "--defaults-extra-file", common.TestPath + "/test/my.cnf",27 "--query", common.TestConfig.Query,28 }29 os.Args = append(os.Args[:1], args...)30 main()31 os.Args = orgArgs32 common.TestConfig = orgCfg33}34func TestMainEmport(t *testing.T) {35 orgCfg := common.TestConfig36 orgArgs := os.Args37 args := []string{38 "--file", common.TestPath + "/test/actor.csv", "--import",39 "--table", "actor",40 "--limit", "10",41 "--extended-insert", "3",42 "--schema", common.TestPath + "/test/schema.txt",43 "--database", "sakila",44 "--replace", "--disable-foreign-key-checks",45 }46 os.Args = append(os.Args[:1], args...)47 main()48 os.Args = orgArgs49 common.TestConfig = orgCfg50}51func Example_lint() {52 orgCfg := common.TestConfig53 orgArgs := os.Args54 args := []string{55 "--file", common.TestPath + "/test/actor.csv", "--lint",56 }57 os.Args = append(os.Args[:1], args...)58 main()59 os.Args = orgArgs60 common.TestConfig = orgCfg61 // Output:62 // ok63}64func TestMainDetect(t *testing.T) {65 orgCfg := common.TestConfig66 orgArgs := os.Args67 args := []string{68 "--defaults-extra-file", common.TestPath + "/test/my.cnf",69 "--query", `select * from sakila.actor limit 10`, "--detect",70 }71 os.Args = append(os.Args[:1], args...)72 main()73 os.Args = orgArgs74 common.TestConfig = orgCfg75}76func TestMainPrintConfig(t *testing.T) {77 orgCfg := common.TestConfig78 orgArgs := os.Args79 args := []string{80 "--print-config",81 }82 os.Args = append(os.Args[:1], args...)83 main()84 os.Args = orgArgs85 common.TestConfig = orgCfg86}87func TestMainPrintCipher(t *testing.T) {88 orgCfg := common.TestConfig89 orgArgs := os.Args90 args := []string{91 "--print-cipher",92 }93 os.Args = append(os.Args[:1], args...)94 main()95 os.Args = orgArgs96 common.TestConfig = orgCfg97}98func Example_preview() {99 orgCfg := common.TestConfig100 orgArgs := os.Args101 args := []string{102 "--preview", "2",103 "--file", common.TestPath + "/test/actor.csv",104 }105 os.Args = append(os.Args[:1], args...)106 main()107 os.Args = orgArgs108 common.TestConfig = orgCfg109 // Output:110 // actor_id,first_name,last_name,last_update111 // 1,PENELOPE,GUINESS,2006-02-15 04:34:33112}...
testConfig
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 var a = testConfig()5 fmt.Println(a)6}
testConfig
Using AI Code Generation
1import (2func main() {3 fmt.Println("Main Package")4 main.TestConfig()5 one.TestConfig()6}
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!!