How to use init method of td Package

Best Go-testdeep code snippet using td.init

init_test.go

Source:init_test.go Github

copy

Full Screen

...59 Ui: ui,60 },61 }62 args := []string{63 "-from-module=" + testFixturePath("init"),64 dir,65 }66 if code := c.Run(args); code != 0 {67 t.Fatalf("bad: \n%s", ui.ErrorWriter.String())68 }69 if _, err := os.Stat(filepath.Join(dir, "hello.tf")); err != nil {70 t.Fatalf("err: %s", err)71 }72}73func TestInit_fromModule_cwdDest(t *testing.T) {74 // Create a temporary working directory that is empty75 td := tempDir(t)76 os.MkdirAll(td, os.ModePerm)77 defer os.RemoveAll(td)78 defer testChdir(t, td)()79 ui := new(cli.MockUi)80 c := &InitCommand{81 Meta: Meta{82 testingOverrides: metaOverridesForProvider(testProvider()),83 Ui: ui,84 },85 }86 args := []string{87 "-from-module=" + testFixturePath("init"),88 }89 if code := c.Run(args); code != 0 {90 t.Fatalf("bad: \n%s", ui.ErrorWriter.String())91 }92 if _, err := os.Stat(filepath.Join(td, "hello.tf")); err != nil {93 t.Fatalf("err: %s", err)94 }95}96// https://github.com/hashicorp/terraform/issues/51897func TestInit_fromModule_dstInSrc(t *testing.T) {98 dir := tempDir(t)99 if err := os.MkdirAll(dir, 0755); err != nil {100 t.Fatalf("err: %s", err)101 }102 // Change to the temporary directory103 cwd, err := os.Getwd()104 if err != nil {105 t.Fatalf("err: %s", err)106 }107 if err := os.Chdir(dir); err != nil {108 t.Fatalf("err: %s", err)109 }110 defer os.Chdir(cwd)111 if _, err := os.Create("issue518.tf"); err != nil {112 t.Fatalf("err: %s", err)113 }114 ui := new(cli.MockUi)115 c := &InitCommand{116 Meta: Meta{117 testingOverrides: metaOverridesForProvider(testProvider()),118 Ui: ui,119 },120 }121 args := []string{122 "-from-module=.",123 "foo",124 }125 if code := c.Run(args); code != 0 {126 t.Fatalf("bad: \n%s", ui.ErrorWriter.String())127 }128 if _, err := os.Stat(filepath.Join(dir, "foo", "issue518.tf")); err != nil {129 t.Fatalf("err: %s", err)130 }131}132func TestInit_get(t *testing.T) {133 // Create a temporary working directory that is empty134 td := tempDir(t)135 copy.CopyDir(testFixturePath("init-get"), td)136 defer os.RemoveAll(td)137 defer testChdir(t, td)()138 ui := new(cli.MockUi)139 c := &InitCommand{140 Meta: Meta{141 testingOverrides: metaOverridesForProvider(testProvider()),142 Ui: ui,143 },144 }145 args := []string{}146 if code := c.Run(args); code != 0 {147 t.Fatalf("bad: \n%s", ui.ErrorWriter.String())148 }149 // Check output150 output := ui.OutputWriter.String()151 if !strings.Contains(output, "Getting source") {152 t.Fatalf("doesn't look like get: %s", output)153 }154}155func TestInit_getUpgradeModules(t *testing.T) {156 // Create a temporary working directory that is empty157 td := tempDir(t)158 os.MkdirAll(td, 0755)159 // copy.CopyDir(testFixturePath("init-get"), td)160 defer os.RemoveAll(td)161 defer testChdir(t, td)()162 ui := new(cli.MockUi)163 c := &InitCommand{164 Meta: Meta{165 testingOverrides: metaOverridesForProvider(testProvider()),166 Ui: ui,167 },168 }169 args := []string{170 "-get=true",171 "-get-plugins=false",172 "-upgrade",173 testFixturePath("init-get"),174 }175 if code := c.Run(args); code != 0 {176 t.Fatalf("command did not complete successfully:\n%s", ui.ErrorWriter.String())177 }178 // Check output179 output := ui.OutputWriter.String()180 if !strings.Contains(output, "Updating source") {181 t.Fatalf("doesn't look like get upgrade: %s", output)182 }183}184func TestInit_backend(t *testing.T) {185 // Create a temporary working directory that is empty186 td := tempDir(t)187 copy.CopyDir(testFixturePath("init-backend"), td)188 defer os.RemoveAll(td)189 defer testChdir(t, td)()190 ui := new(cli.MockUi)191 c := &InitCommand{192 Meta: Meta{193 testingOverrides: metaOverridesForProvider(testProvider()),194 Ui: ui,195 },196 }197 args := []string{}198 if code := c.Run(args); code != 0 {199 t.Fatalf("bad: \n%s", ui.ErrorWriter.String())200 }201 if _, err := os.Stat(filepath.Join(DefaultDataDir, DefaultStateFilename)); err != nil {202 t.Fatalf("err: %s", err)203 }204}205func TestInit_backendUnset(t *testing.T) {206 // Create a temporary working directory that is empty207 td := tempDir(t)208 copy.CopyDir(testFixturePath("init-backend"), td)209 defer os.RemoveAll(td)210 defer testChdir(t, td)()211 {212 ui := new(cli.MockUi)213 c := &InitCommand{214 Meta: Meta{215 testingOverrides: metaOverridesForProvider(testProvider()),216 Ui: ui,217 },218 }219 // Init220 args := []string{}221 if code := c.Run(args); code != 0 {222 t.Fatalf("bad: \n%s", ui.ErrorWriter.String())223 }224 if _, err := os.Stat(filepath.Join(DefaultDataDir, DefaultStateFilename)); err != nil {225 t.Fatalf("err: %s", err)226 }227 }228 {229 // Unset230 if err := ioutil.WriteFile("main.tf", []byte(""), 0644); err != nil {231 t.Fatalf("err: %s", err)232 }233 ui := new(cli.MockUi)234 c := &InitCommand{235 Meta: Meta{236 testingOverrides: metaOverridesForProvider(testProvider()),237 Ui: ui,238 },239 }240 args := []string{"-force-copy"}241 if code := c.Run(args); code != 0 {242 t.Fatalf("bad: \n%s", ui.ErrorWriter.String())243 }244 s := testStateRead(t, filepath.Join(245 DefaultDataDir, DefaultStateFilename))246 if !s.Backend.Empty() {247 t.Fatal("should not have backend config")248 }249 }250}251func TestInit_backendConfigFile(t *testing.T) {252 // Create a temporary working directory that is empty253 td := tempDir(t)254 copy.CopyDir(testFixturePath("init-backend-config-file"), td)255 defer os.RemoveAll(td)256 defer testChdir(t, td)()257 ui := new(cli.MockUi)258 c := &InitCommand{259 Meta: Meta{260 testingOverrides: metaOverridesForProvider(testProvider()),261 Ui: ui,262 },263 }264 args := []string{"-backend-config", "input.config"}265 if code := c.Run(args); code != 0 {266 t.Fatalf("bad: \n%s", ui.ErrorWriter.String())267 }268 // Read our saved backend config and verify we have our settings269 state := testStateRead(t, filepath.Join(DefaultDataDir, DefaultStateFilename))270 if v := state.Backend.Config["path"]; v != "hello" {271 t.Fatalf("bad: %#v", v)272 }273}274func TestInit_backendConfigFileChange(t *testing.T) {275 // Create a temporary working directory that is empty276 td := tempDir(t)277 copy.CopyDir(testFixturePath("init-backend-config-file-change"), td)278 defer os.RemoveAll(td)279 defer testChdir(t, td)()280 // Ask input281 defer testInputMap(t, map[string]string{282 "backend-migrate-to-new": "no",283 })()284 ui := new(cli.MockUi)285 c := &InitCommand{286 Meta: Meta{287 testingOverrides: metaOverridesForProvider(testProvider()),288 Ui: ui,289 },290 }291 args := []string{"-backend-config", "input.config"}292 if code := c.Run(args); code != 0 {293 t.Fatalf("bad: \n%s", ui.ErrorWriter.String())294 }295 // Read our saved backend config and verify we have our settings296 state := testStateRead(t, filepath.Join(DefaultDataDir, DefaultStateFilename))297 if v := state.Backend.Config["path"]; v != "hello" {298 t.Fatalf("bad: %#v", v)299 }300}301func TestInit_backendConfigKV(t *testing.T) {302 // Create a temporary working directory that is empty303 td := tempDir(t)304 copy.CopyDir(testFixturePath("init-backend-config-kv"), td)305 defer os.RemoveAll(td)306 defer testChdir(t, td)()307 ui := new(cli.MockUi)308 c := &InitCommand{309 Meta: Meta{310 testingOverrides: metaOverridesForProvider(testProvider()),311 Ui: ui,312 },313 }314 args := []string{"-backend-config", "path=hello"}315 if code := c.Run(args); code != 0 {316 t.Fatalf("bad: \n%s", ui.ErrorWriter.String())317 }318 // Read our saved backend config and verify we have our settings319 state := testStateRead(t, filepath.Join(DefaultDataDir, DefaultStateFilename))320 if v := state.Backend.Config["path"]; v != "hello" {321 t.Fatalf("bad: %#v", v)322 }323}324func TestInit_targetSubdir(t *testing.T) {325 // Create a temporary working directory that is empty326 td := tempDir(t)327 os.MkdirAll(td, 0755)328 defer os.RemoveAll(td)329 defer testChdir(t, td)()330 // copy the source into a subdir331 copy.CopyDir(testFixturePath("init-backend"), filepath.Join(td, "source"))332 ui := new(cli.MockUi)333 c := &InitCommand{334 Meta: Meta{335 testingOverrides: metaOverridesForProvider(testProvider()),336 Ui: ui,337 },338 }339 args := []string{340 "source",341 }342 if code := c.Run(args); code != 0 {343 t.Fatalf("bad: \n%s", ui.ErrorWriter.String())344 }345 if _, err := os.Stat(filepath.Join(td, DefaultDataDir, DefaultStateFilename)); err != nil {346 t.Fatalf("err: %s", err)347 }348 // a data directory should not have been added to out working dir349 if _, err := os.Stat(filepath.Join(td, "source", DefaultDataDir)); !os.IsNotExist(err) {350 t.Fatalf("err: %s", err)351 }352}353func TestInit_backendReinitWithExtra(t *testing.T) {354 td := tempDir(t)355 copy.CopyDir(testFixturePath("init-backend-empty"), td)356 defer os.RemoveAll(td)357 defer testChdir(t, td)()358 m := testMetaBackend(t, nil)359 opts := &BackendOpts{360 ConfigExtra: map[string]interface{}{"path": "hello"},361 Init: true,362 }363 b, err := m.backendConfig(opts)364 if err != nil {365 t.Fatal(err)366 }367 ui := new(cli.MockUi)368 c := &InitCommand{369 Meta: Meta{370 testingOverrides: metaOverridesForProvider(testProvider()),371 Ui: ui,372 },373 }374 args := []string{"-backend-config", "path=hello"}375 if code := c.Run(args); code != 0 {376 t.Fatalf("bad: \n%s", ui.ErrorWriter.String())377 }378 // Read our saved backend config and verify we have our settings379 state := testStateRead(t, filepath.Join(DefaultDataDir, DefaultStateFilename))380 if v := state.Backend.Config["path"]; v != "hello" {381 t.Fatalf("bad: %#v", v)382 }383 if state.Backend.Hash != b.Hash {384 t.Fatal("mismatched state and config backend hashes")385 }386 if state.Backend.Rehash() != b.Rehash() {387 t.Fatal("mismatched state and config re-hashes")388 }389 // init again and make sure nothing changes390 if code := c.Run(args); code != 0 {391 t.Fatalf("bad: \n%s", ui.ErrorWriter.String())392 }393 state = testStateRead(t, filepath.Join(DefaultDataDir, DefaultStateFilename))394 if v := state.Backend.Config["path"]; v != "hello" {395 t.Fatalf("bad: %#v", v)396 }397 if state.Backend.Hash != b.Hash {398 t.Fatal("mismatched state and config backend hashes")399 }400}401// move option from config to -backend-config args402func TestInit_backendReinitConfigToExtra(t *testing.T) {403 td := tempDir(t)404 copy.CopyDir(testFixturePath("init-backend"), td)405 defer os.RemoveAll(td)406 defer testChdir(t, td)()407 ui := new(cli.MockUi)408 c := &InitCommand{409 Meta: Meta{410 testingOverrides: metaOverridesForProvider(testProvider()),411 Ui: ui,412 },413 }414 if code := c.Run([]string{"-input=false"}); code != 0 {415 t.Fatalf("bad: \n%s", ui.ErrorWriter.String())416 }417 // Read our saved backend config and verify we have our settings418 state := testStateRead(t, filepath.Join(DefaultDataDir, DefaultStateFilename))419 if v := state.Backend.Config["path"]; v != "foo" {420 t.Fatalf("bad: %#v", v)421 }422 backendHash := state.Backend.Hash423 // init again but remove the path option from the config424 cfg := "terraform {\n backend \"local\" {}\n}\n"425 if err := ioutil.WriteFile("main.tf", []byte(cfg), 0644); err != nil {426 t.Fatal(err)427 }428 args := []string{"-input=false", "-backend-config=path=foo"}429 if code := c.Run(args); code != 0 {430 t.Fatalf("bad: \n%s", ui.ErrorWriter.String())431 }432 state = testStateRead(t, filepath.Join(DefaultDataDir, DefaultStateFilename))433 if state.Backend.Hash == backendHash {434 t.Fatal("state.Backend.Hash was not updated")435 }436}437// make sure inputFalse stops execution on migrate438func TestInit_inputFalse(t *testing.T) {439 td := tempDir(t)440 copy.CopyDir(testFixturePath("init-backend"), td)441 defer os.RemoveAll(td)442 defer testChdir(t, td)()443 ui := new(cli.MockUi)444 c := &InitCommand{445 Meta: Meta{446 testingOverrides: metaOverridesForProvider(testProvider()),447 Ui: ui,448 },449 }450 args := []string{"-input=false", "-backend-config=path=foo"}451 if code := c.Run([]string{"-input=false"}); code != 0 {452 t.Fatalf("bad: \n%s", ui.ErrorWriter)453 }454 // write different states for foo and bar455 s := terraform.NewState()456 s.Lineage = "foo"457 if err := (&state.LocalState{Path: "foo"}).WriteState(s); err != nil {458 t.Fatal(err)459 }460 s.Lineage = "bar"461 if err := (&state.LocalState{Path: "bar"}).WriteState(s); err != nil {462 t.Fatal(err)463 }464 ui = new(cli.MockUi)465 c = &InitCommand{466 Meta: Meta{467 testingOverrides: metaOverridesForProvider(testProvider()),468 Ui: ui,469 },470 }471 args = []string{"-input=false", "-backend-config=path=bar"}472 if code := c.Run(args); code == 0 {473 t.Fatal("init should have failed", ui.OutputWriter)474 }475 errMsg := ui.ErrorWriter.String()476 if !strings.Contains(errMsg, "input disabled") {477 t.Fatal("expected input disabled error, got", errMsg)478 }479 ui = new(cli.MockUi)480 c = &InitCommand{481 Meta: Meta{482 testingOverrides: metaOverridesForProvider(testProvider()),483 Ui: ui,484 },485 }486 // A missing input=false should abort rather than loop infinitely487 args = []string{"-backend-config=path=bar"}488 if code := c.Run(args); code == 0 {489 t.Fatal("init should have failed", ui.OutputWriter)490 }491}492func TestInit_getProvider(t *testing.T) {493 // Create a temporary working directory that is empty494 td := tempDir(t)495 copy.CopyDir(testFixturePath("init-get-providers"), td)496 defer os.RemoveAll(td)497 defer testChdir(t, td)()498 overrides := metaOverridesForProvider(testProvider())499 ui := new(cli.MockUi)500 m := Meta{501 testingOverrides: overrides,502 Ui: ui,503 }504 installer := &mockProviderInstaller{505 Providers: map[string][]string{506 // looking for an exact version507 "exact": []string{"1.2.3"},508 // config requires >= 2.3.3509 "greater_than": []string{"2.3.4", "2.3.3", "2.3.0"},510 // config specifies511 "between": []string{"3.4.5", "2.3.4", "1.2.3"},512 },513 Dir: m.pluginDir(),514 }515 c := &InitCommand{516 Meta: m,517 providerInstaller: installer,518 }519 args := []string{520 "-backend=false", // should be possible to install plugins without backend init521 }522 if code := c.Run(args); code != 0 {523 t.Fatalf("bad: \n%s", ui.ErrorWriter.String())524 }525 if !installer.PurgeUnusedCalled {526 t.Errorf("init didn't purge providers, but should have")527 }528 // check that we got the providers for our config529 exactPath := filepath.Join(c.pluginDir(), installer.FileName("exact", "1.2.3"))530 if _, err := os.Stat(exactPath); os.IsNotExist(err) {531 t.Fatal("provider 'exact' not downloaded")532 }533 greaterThanPath := filepath.Join(c.pluginDir(), installer.FileName("greater_than", "2.3.4"))534 if _, err := os.Stat(greaterThanPath); os.IsNotExist(err) {535 t.Fatal("provider 'greater_than' not downloaded")536 }537 betweenPath := filepath.Join(c.pluginDir(), installer.FileName("between", "2.3.4"))538 if _, err := os.Stat(betweenPath); os.IsNotExist(err) {539 t.Fatal("provider 'between' not downloaded")540 }541 t.Run("future-state", func(t *testing.T) {542 // getting providers should fail if a state from a newer version of543 // terraform exists, since InitCommand.getProviders needs to inspect that544 // state.545 s := terraform.NewState()546 s.TFVersion = "100.1.0"547 local := &state.LocalState{548 Path: local.DefaultStateFilename,549 }550 if err := local.WriteState(s); err != nil {551 t.Fatal(err)552 }553 ui := new(cli.MockUi)554 m.Ui = ui555 c := &InitCommand{556 Meta: m,557 providerInstaller: installer,558 }559 if code := c.Run(nil); code == 0 {560 t.Fatal("expected error, got:", ui.OutputWriter)561 }562 errMsg := ui.ErrorWriter.String()563 if !strings.Contains(errMsg, "future Terraform version") {564 t.Fatal("unexpected error:", errMsg)565 }566 })567}568// make sure we can locate providers in various paths569func TestInit_findVendoredProviders(t *testing.T) {570 // Create a temporary working directory that is empty571 td := tempDir(t)572 configDirName := "init-get-providers"573 copy.CopyDir(testFixturePath(configDirName), filepath.Join(td, configDirName))574 defer os.RemoveAll(td)575 defer testChdir(t, td)()576 ui := new(cli.MockUi)577 m := Meta{578 testingOverrides: metaOverridesForProvider(testProvider()),579 Ui: ui,580 }581 c := &InitCommand{582 Meta: m,583 providerInstaller: &mockProviderInstaller{},584 }585 // make our plugin paths586 if err := os.MkdirAll(c.pluginDir(), 0755); err != nil {587 t.Fatal(err)588 }589 if err := os.MkdirAll(DefaultPluginVendorDir, 0755); err != nil {590 t.Fatal(err)591 }592 // add some dummy providers593 // the auto plugin directory594 exactPath := filepath.Join(c.pluginDir(), "terraform-provider-exact_v1.2.3_x4")595 if err := ioutil.WriteFile(exactPath, []byte("test bin"), 0755); err != nil {596 t.Fatal(err)597 }598 // the vendor path599 greaterThanPath := filepath.Join(DefaultPluginVendorDir, "terraform-provider-greater_than_v2.3.4_x4")600 if err := ioutil.WriteFile(greaterThanPath, []byte("test bin"), 0755); err != nil {601 t.Fatal(err)602 }603 // Check the current directory too604 betweenPath := filepath.Join(".", "terraform-provider-between_v2.3.4_x4")605 if err := ioutil.WriteFile(betweenPath, []byte("test bin"), 0755); err != nil {606 t.Fatal(err)607 }608 args := []string{configDirName}609 if code := c.Run(args); code != 0 {610 t.Fatalf("bad: \n%s", ui.ErrorWriter.String())611 }612}613// make sure we can locate providers defined in the legacy rc file614func TestInit_rcProviders(t *testing.T) {615 // Create a temporary working directory that is empty616 td := tempDir(t)617 configDirName := "init-legacy-rc"618 copy.CopyDir(testFixturePath(configDirName), filepath.Join(td, configDirName))619 defer os.RemoveAll(td)620 defer testChdir(t, td)()621 pluginDir := filepath.Join(td, "custom")622 pluginPath := filepath.Join(pluginDir, "terraform-provider-legacy")623 ui := new(cli.MockUi)624 m := Meta{625 Ui: ui,626 PluginOverrides: &PluginOverrides{627 Providers: map[string]string{628 "legacy": pluginPath,629 },630 },631 }632 c := &InitCommand{633 Meta: m,634 providerInstaller: &mockProviderInstaller{},635 }636 // make our plugin paths637 if err := os.MkdirAll(pluginDir, 0755); err != nil {638 t.Fatal(err)639 }640 if err := ioutil.WriteFile(pluginPath, []byte("test bin"), 0755); err != nil {641 t.Fatal(err)642 }643 args := []string{configDirName}644 if code := c.Run(args); code != 0 {645 t.Fatalf("bad: \n%s", ui.ErrorWriter.String())646 }647}648func TestInit_getUpgradePlugins(t *testing.T) {649 // Create a temporary working directory that is empty650 td := tempDir(t)651 copy.CopyDir(testFixturePath("init-get-providers"), td)652 defer os.RemoveAll(td)653 defer testChdir(t, td)()654 ui := new(cli.MockUi)655 m := Meta{656 testingOverrides: metaOverridesForProvider(testProvider()),657 Ui: ui,658 }659 installer := &mockProviderInstaller{660 Providers: map[string][]string{661 // looking for an exact version662 "exact": []string{"1.2.3"},663 // config requires >= 2.3.3664 "greater_than": []string{"2.3.4", "2.3.3", "2.3.0"},665 // config specifies666 "between": []string{"3.4.5", "2.3.4", "1.2.3"},667 },668 Dir: m.pluginDir(),669 }670 err := os.MkdirAll(m.pluginDir(), os.ModePerm)671 if err != nil {672 t.Fatal(err)673 }674 exactUnwanted := filepath.Join(m.pluginDir(), installer.FileName("exact", "0.0.1"))675 err = ioutil.WriteFile(exactUnwanted, []byte{}, os.ModePerm)676 if err != nil {677 t.Fatal(err)678 }679 greaterThanUnwanted := filepath.Join(m.pluginDir(), installer.FileName("greater_than", "2.3.3"))680 err = ioutil.WriteFile(greaterThanUnwanted, []byte{}, os.ModePerm)681 if err != nil {682 t.Fatal(err)683 }684 betweenOverride := installer.FileName("between", "2.3.4") // intentionally directly in cwd, and should override auto-install685 err = ioutil.WriteFile(betweenOverride, []byte{}, os.ModePerm)686 if err != nil {687 t.Fatal(err)688 }689 c := &InitCommand{690 Meta: m,691 providerInstaller: installer,692 }693 args := []string{694 "-upgrade=true",695 }696 if code := c.Run(args); code != 0 {697 t.Fatalf("command did not complete successfully:\n%s", ui.ErrorWriter.String())698 }699 files, err := ioutil.ReadDir(m.pluginDir())700 if err != nil {701 t.Fatal(err)702 }703 if !installer.PurgeUnusedCalled {704 t.Errorf("init -upgrade didn't purge providers, but should have")705 }706 gotFilenames := make([]string, len(files))707 for i, info := range files {708 gotFilenames[i] = info.Name()709 }710 sort.Strings(gotFilenames)711 wantFilenames := []string{712 "lock.json",713 // no "between" because the file in cwd overrides it714 // The mock PurgeUnused doesn't actually purge anything, so the dir715 // includes both our old and new versions.716 "terraform-provider-exact_v0.0.1_x4",717 "terraform-provider-exact_v1.2.3_x4",718 "terraform-provider-greater_than_v2.3.3_x4",719 "terraform-provider-greater_than_v2.3.4_x4",720 }721 if !reflect.DeepEqual(gotFilenames, wantFilenames) {722 t.Errorf("wrong directory contents after upgrade\ngot: %#v\nwant: %#v", gotFilenames, wantFilenames)723 }724}725func TestInit_getProviderMissing(t *testing.T) {726 // Create a temporary working directory that is empty727 td := tempDir(t)728 copy.CopyDir(testFixturePath("init-get-providers"), td)729 defer os.RemoveAll(td)730 defer testChdir(t, td)()731 ui := new(cli.MockUi)732 m := Meta{733 testingOverrides: metaOverridesForProvider(testProvider()),734 Ui: ui,735 }736 installer := &mockProviderInstaller{737 Providers: map[string][]string{738 // looking for exact version 1.2.3739 "exact": []string{"1.2.4"},740 // config requires >= 2.3.3741 "greater_than": []string{"2.3.4", "2.3.3", "2.3.0"},742 // config specifies743 "between": []string{"3.4.5", "2.3.4", "1.2.3"},744 },745 Dir: m.pluginDir(),746 }747 c := &InitCommand{748 Meta: m,749 providerInstaller: installer,750 }751 args := []string{}752 if code := c.Run(args); code == 0 {753 t.Fatalf("expceted error, got output: \n%s", ui.OutputWriter.String())754 }755 if !strings.Contains(ui.ErrorWriter.String(), "no suitable version for provider") {756 t.Fatalf("unexpected error output: %s", ui.ErrorWriter)757 }758}759func TestInit_getProviderHaveLegacyVersion(t *testing.T) {760 // Create a temporary working directory that is empty761 td := tempDir(t)762 copy.CopyDir(testFixturePath("init-providers-lock"), td)763 defer os.RemoveAll(td)764 defer testChdir(t, td)()765 if err := ioutil.WriteFile("terraform-provider-test", []byte("provider bin"), 0755); err != nil {766 t.Fatal(err)767 }768 // provider test has a version constraint in the config, which should769 // trigger the getProvider error below.770 ui := new(cli.MockUi)771 c := &InitCommand{772 Meta: Meta{773 testingOverrides: metaOverridesForProvider(testProvider()),774 Ui: ui,775 },776 providerInstaller: callbackPluginInstaller(func(provider string, req discovery.Constraints) (discovery.PluginMeta, error) {777 return discovery.PluginMeta{}, fmt.Errorf("EXPECTED PROVIDER ERROR %s", provider)778 }),779 }780 args := []string{}781 if code := c.Run(args); code == 0 {782 t.Fatalf("expceted error, got output: \n%s", ui.OutputWriter.String())783 }784 if !strings.Contains(ui.ErrorWriter.String(), "EXPECTED PROVIDER ERROR test") {785 t.Fatalf("unexpected error output: %s", ui.ErrorWriter)786 }787}788func TestInit_getProviderCheckRequiredVersion(t *testing.T) {789 // Create a temporary working directory that is empty790 td := tempDir(t)791 copy.CopyDir(testFixturePath("init-check-required-version"), td)792 defer os.RemoveAll(td)793 defer testChdir(t, td)()794 ui := new(cli.MockUi)795 c := &InitCommand{796 Meta: Meta{797 testingOverrides: metaOverridesForProvider(testProvider()),798 Ui: ui,799 },800 }801 args := []string{}802 if code := c.Run(args); code != 1 {803 t.Fatalf("bad: \n%s", ui.ErrorWriter.String())804 }805}806func TestInit_providerLockFile(t *testing.T) {807 // Create a temporary working directory that is empty808 td := tempDir(t)809 copy.CopyDir(testFixturePath("init-provider-lock-file"), td)810 defer os.RemoveAll(td)811 defer testChdir(t, td)()812 ui := new(cli.MockUi)813 m := Meta{814 testingOverrides: metaOverridesForProvider(testProvider()),815 Ui: ui,816 }817 installer := &mockProviderInstaller{818 Providers: map[string][]string{819 "test": []string{"1.2.3"},820 },821 Dir: m.pluginDir(),822 }823 c := &InitCommand{824 Meta: m,825 providerInstaller: installer,826 }827 args := []string{}828 if code := c.Run(args); code != 0 {829 t.Fatalf("bad: \n%s", ui.ErrorWriter.String())830 }831 providersLockFile := fmt.Sprintf(832 ".terraform/plugins/%s_%s/lock.json",833 runtime.GOOS, runtime.GOARCH,834 )835 buf, err := ioutil.ReadFile(providersLockFile)836 if err != nil {837 t.Fatalf("failed to read providers lock file %s: %s", providersLockFile, err)838 }839 // The hash in here is for the empty files that mockGetProvider produces840 wantLockFile := strings.TrimSpace(`841{842 "test": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"843}844`)845 if string(buf) != wantLockFile {846 t.Errorf("wrong provider lock file contents\ngot: %s\nwant: %s", buf, wantLockFile)847 }848}849func TestInit_pluginDirReset(t *testing.T) {850 td, err := ioutil.TempDir("", "tf")851 if err != nil {852 t.Fatal(err)853 }854 defer os.RemoveAll(td)855 defer testChdir(t, td)()856 ui := new(cli.MockUi)857 c := &InitCommand{858 Meta: Meta{859 testingOverrides: metaOverridesForProvider(testProvider()),860 Ui: ui,861 },862 providerInstaller: &mockProviderInstaller{},863 }864 // make our vendor paths865 pluginPath := []string{"a", "b", "c"}866 for _, p := range pluginPath {867 if err := os.MkdirAll(p, 0755); err != nil {868 t.Fatal(err)869 }870 }871 // run once and save the -plugin-dir872 args := []string{"-plugin-dir", "a"}873 if code := c.Run(args); code != 0 {874 t.Fatalf("bad: \n%s", ui.ErrorWriter)875 }876 pluginDirs, err := c.loadPluginPath()877 if err != nil {878 t.Fatal(err)879 }880 if len(pluginDirs) != 1 || pluginDirs[0] != "a" {881 t.Fatalf(`expected plugin dir ["a"], got %q`, pluginDirs)882 }883 ui = new(cli.MockUi)884 c = &InitCommand{885 Meta: Meta{886 testingOverrides: metaOverridesForProvider(testProvider()),887 Ui: ui,888 },889 providerInstaller: &mockProviderInstaller{},890 }891 // make sure we remove the plugin-dir record892 args = []string{"-plugin-dir="}893 if code := c.Run(args); code != 0 {894 t.Fatalf("bad: \n%s", ui.ErrorWriter)895 }896 pluginDirs, err = c.loadPluginPath()897 if err != nil {898 t.Fatal(err)899 }900 if len(pluginDirs) != 0 {901 t.Fatalf("expected no plugin dirs got %q", pluginDirs)902 }903}904// Test user-supplied -plugin-dir905func TestInit_pluginDirProviders(t *testing.T) {906 td := tempDir(t)907 copy.CopyDir(testFixturePath("init-get-providers"), td)908 defer os.RemoveAll(td)909 defer testChdir(t, td)()910 ui := new(cli.MockUi)911 m := Meta{912 testingOverrides: metaOverridesForProvider(testProvider()),913 Ui: ui,914 }915 c := &InitCommand{916 Meta: m,917 providerInstaller: &mockProviderInstaller{},918 }919 // make our vendor paths920 pluginPath := []string{"a", "b", "c"}921 for _, p := range pluginPath {922 if err := os.MkdirAll(p, 0755); err != nil {923 t.Fatal(err)924 }925 }926 // add some dummy providers in our plugin dirs927 for i, name := range []string{928 "terraform-provider-exact_v1.2.3_x4",929 "terraform-provider-greater_than_v2.3.4_x4",930 "terraform-provider-between_v2.3.4_x4",931 } {932 if err := ioutil.WriteFile(filepath.Join(pluginPath[i], name), []byte("test bin"), 0755); err != nil {933 t.Fatal(err)934 }935 }936 args := []string{937 "-plugin-dir", "a",938 "-plugin-dir", "b",939 "-plugin-dir", "c",940 }941 if code := c.Run(args); code != 0 {942 t.Fatalf("bad: \n%s", ui.ErrorWriter)943 }944}945// Test user-supplied -plugin-dir doesn't allow auto-install946func TestInit_pluginDirProvidersDoesNotGet(t *testing.T) {947 td := tempDir(t)948 copy.CopyDir(testFixturePath("init-get-providers"), td)949 defer os.RemoveAll(td)950 defer testChdir(t, td)()951 ui := new(cli.MockUi)952 m := Meta{953 testingOverrides: metaOverridesForProvider(testProvider()),954 Ui: ui,955 }956 c := &InitCommand{957 Meta: m,958 providerInstaller: callbackPluginInstaller(func(provider string, req discovery.Constraints) (discovery.PluginMeta, error) {959 t.Fatalf("plugin installer should not have been called for %q", provider)960 return discovery.PluginMeta{}, nil961 }),962 }963 // make our vendor paths964 pluginPath := []string{"a", "b"}965 for _, p := range pluginPath {966 if err := os.MkdirAll(p, 0755); err != nil {967 t.Fatal(err)968 }969 }970 // add some dummy providers in our plugin dirs971 for i, name := range []string{972 "terraform-provider-exact_v1.2.3_x4",973 "terraform-provider-greater_than_v2.3.4_x4",974 } {975 if err := ioutil.WriteFile(filepath.Join(pluginPath[i], name), []byte("test bin"), 0755); err != nil {976 t.Fatal(err)977 }978 }979 args := []string{980 "-plugin-dir", "a",981 "-plugin-dir", "b",982 }983 if code := c.Run(args); code == 0 {984 // should have been an error985 t.Fatalf("bad: \n%s", ui.OutputWriter)986 }987}988// Verify that plugin-dir doesn't prevent discovery of internal providers989func TestInit_pluginWithInternal(t *testing.T) {990 td := tempDir(t)991 copy.CopyDir(testFixturePath("init-internal"), td)992 defer os.RemoveAll(td)993 defer testChdir(t, td)()994 ui := new(cli.MockUi)995 m := Meta{996 testingOverrides: metaOverridesForProvider(testProvider()),997 Ui: ui,998 }999 c := &InitCommand{1000 Meta: m,1001 }1002 args := []string{"-plugin-dir", "./"}1003 //args := []string{}1004 if code := c.Run(args); code != 0 {1005 t.Fatalf("error: %s", ui.ErrorWriter)...

Full Screen

Full Screen

timer.go

Source:timer.go Github

copy

Full Screen

...5 "go-common/library/log"6)7const (8 timerFormat = "2006-01-02 15:04:05"9 infiniteDuration = itime.Duration(1<<63 - 1)10)11var (12 timerLazyDelay = 300 * itime.Millisecond13)14// TimerData timer data.15type TimerData struct {16 Key string17 expire itime.Time18 fn func()19 index int20 next *TimerData21}22// Delay delay duration.23func (td *TimerData) Delay() itime.Duration {24 return td.expire.Sub(itime.Now())25}26// ExpireString expire string.27func (td *TimerData) ExpireString() string {28 return td.expire.Format(timerFormat)29}30// Timer timer.31type Timer struct {32 lock sync.Mutex33 free *TimerData34 timers []*TimerData35 signal *itime.Timer36 num int37}38// NewTimer new a timer.39// A heap must be initialized before any of the heap operations40// can be used. Init is idempotent with respect to the heap invariants41// and may be called whenever the heap invariants may have been invalidated.42// Its complexity is O(n) where n = h.Len().43//44func NewTimer(num int) (t *Timer) {45 t = new(Timer)46 t.init(num)47 return t48}49// Init init the timer.50func (t *Timer) Init(num int) {51 t.init(num)52}53func (t *Timer) init(num int) {54 t.signal = itime.NewTimer(infiniteDuration)55 t.timers = make([]*TimerData, 0, num)56 t.num = num57 t.grow()58 go t.start()59}60func (t *Timer) grow() {61 var (62 i int63 td *TimerData64 tds = make([]TimerData, t.num)65 )66 t.free = &(tds[0])67 td = t.free68 for i = 1; i < t.num; i++ {69 td.next = &(tds[i])70 td = td.next71 }72 td.next = nil73}74// get get a free timer data.75func (t *Timer) get() (td *TimerData) {76 if td = t.free; td == nil {77 t.grow()78 td = t.free79 }80 t.free = td.next81 return82}83// put put back a timer data.84func (t *Timer) put(td *TimerData) {85 td.fn = nil86 td.next = t.free87 t.free = td88}89// Add add the element x onto the heap. The complexity is90// O(log(n)) where n = h.Len().91func (t *Timer) Add(expire itime.Duration, fn func()) (td *TimerData) {92 t.lock.Lock()93 td = t.get()94 td.expire = itime.Now().Add(expire)95 td.fn = fn96 t.add(td)97 t.lock.Unlock()98 return99}100// Del removes the element at index i from the heap.101// The complexity is O(log(n)) where n = h.Len().102func (t *Timer) Del(td *TimerData) {103 t.lock.Lock()104 t.del(td)105 t.put(td)106 t.lock.Unlock()107}108// Push pushes the element x onto the heap. The complexity is109// O(log(n)) where n = h.Len().110func (t *Timer) add(td *TimerData) {111 var d itime.Duration112 td.index = len(t.timers)113 // add to the minheap last node114 t.timers = append(t.timers, td)115 t.up(td.index)116 if td.index == 0 {117 // if first node, signal start goroutine118 d = td.Delay()119 t.signal.Reset(d)120 if Debug {121 log.Info("timer: add reset delay %d ms", int64(d)/int64(itime.Millisecond))122 }123 }124 if Debug {125 log.Info("timer: push item key: %s, expire: %s, index: %d", td.Key, td.ExpireString(), td.index)126 }127}128func (t *Timer) del(td *TimerData) {129 var (130 i = td.index131 last = len(t.timers) - 1132 )133 if i < 0 || i > last || t.timers[i] != td {134 // already remove, usually by expire135 if Debug {136 log.Info("timer del i: %d, last: %d, %p", i, last, td)137 }138 return139 }140 if i != last {141 t.swap(i, last)142 t.down(i, last)143 t.up(i)144 }145 // remove item is the last node146 t.timers[last].index = -1 // for safety147 t.timers = t.timers[:last]148 if Debug {149 log.Info("timer: remove item key: %s, expire: %s, index: %d", td.Key, td.ExpireString(), td.index)150 }151}152// Set update timer data.153func (t *Timer) Set(td *TimerData, expire itime.Duration) {154 t.lock.Lock()155 t.del(td)156 td.expire = itime.Now().Add(expire)157 t.add(td)158 t.lock.Unlock()159}160// start start the timer.161func (t *Timer) start() {162 for {163 t.expire()164 <-t.signal.C165 }166}167// expire removes the minimum element (according to Less) from the heap.168// The complexity is O(log(n)) where n = max.169// It is equivalent to Del(0).170func (t *Timer) expire() {171 var (172 fn func()173 td *TimerData174 d itime.Duration175 )176 t.lock.Lock()177 for {178 if len(t.timers) == 0 {179 d = infiniteDuration180 if Debug {181 log.Info("timer: no other instance")182 }183 break184 }185 td = t.timers[0]186 if d = td.Delay(); d > 0 {187 break188 }189 fn = td.fn190 // let caller put back191 t.del(td)192 t.lock.Unlock()193 if fn == nil {...

Full Screen

Full Screen

create_actor.go

Source:create_actor.go Github

copy

Full Screen

...78 WithDefaultGasFeeCap(200).79 WithDefaultGasPremium(1).80 WithActorState(drivers.DefaultBuiltinActorsState...).Build(t)81 defer td.Complete()82 var initialBal = abi_spec.NewTokenAmount(1_000_000_000_000)83 var toSend = abi_spec.NewTokenAmount(10_000)84 sender, _ := td.NewAccountActor(drivers.SECP, initialBal)85 receiver, receiverID := td.NewAccountActor(drivers.SECP, initialBal)86 firstPaychAddr := utils.NewIDAddr(t, utils.IdFromAddress(receiverID)+1)87 secondPaychAddr := utils.NewIDAddr(t, utils.IdFromAddress(receiverID)+2)88 firstInitRet := td.ComputeInitActorExecReturn(sender, 0, 0, firstPaychAddr)89 secondInitRet := td.ComputeInitActorExecReturn(sender, 1, 0, secondPaychAddr)90 td.ApplyExpect(91 td.MessageProducer.CreatePaymentChannelActor(sender, receiver, chain.Value(toSend), chain.Nonce(0)),92 chain.MustSerialize(&firstInitRet),93 )94 td.ApplyExpect(95 td.MessageProducer.CreatePaymentChannelActor(sender, receiver, chain.Value(toSend), chain.Nonce(1)),96 chain.MustSerialize(&secondInitRet),97 )98}...

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1func main() {2 td := td{}3 td.init()4 td.print()5}6func main() {7 td := td{}8 td.init()9 td.print()10}11The init() me

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, World!")4 td := new(TD)5 td.init()6 td.print()7}8import (9func main() {10 fmt.Println("Hello, World!")11 td := TD{}12 td.init()13 td.print()14}15import (16func main() {17 fmt.Println("Hello, World!")18 td := TD{}19 td.print()20}21import (22func main() {23 fmt.Println("Hello, World!")24 td := TD{}25 td.init()26 td.print()27 td.print()28}29import (30func main() {31 fmt.Println("Hello, World!")32 td := TD{}33 td.print()34 td.init()35 td.print()36}37import (38func main() {39 fmt.Println("Hello, World!")40 td := TD{}41 td.print()42 td.print()43 td.init()44 td.print()45}46import (47func main() {48 fmt.Println("Hello, World!")49 td := TD{}50 td.print()51 td.print()52 td.print()53 td.init()54 td.print()55}56import (57func main() {58 fmt.Println("Hello, World!")59 td := TD{}60 td.print()61 td.print()62 td.print()63 td.print()64 td.init()65 td.print()66}67import (68func main() {69 fmt.Println("Hello, World!")70 td := TD{}71 td.print()

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("main method")4 test.Td()5}6It is not possible to call init() function from

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(td.Td)4}5Go - init() method6Go - init() method 27Go - init() method 38Go - init() method 49Go - init() method 510Go - init() method 611Go - init() method 712Go - init() method 813Go - init() method 914Go - init() method 1015Go - init() method 1116Go - init() method 1217Go - init() method 1318Go - init() method 1419Go - init() method 1520Go - init() method 1621Go - init() method 1722Go - init() method 1823Go - init() method 1924Go - init() method 2025Go - init() method 2126Go - init() method 2227Go - init() method 2328Go - init() method 2429Go - init() method 2530Go - init() method 2631Go - init() method 2732Go - init() method 2833Go - init() method 2934Go - init() method 3035Go - init() method 3136Go - init() method 3237Go - init() method 3338Go - init() method 3439Go - init() method 3540Go - init() method 3641Go - init() method 3742Go - init() method 3843Go - init() method 3944Go - init() method 4045Go - init() method 4146Go - init() method 4247Go - init() method 4348Go - init() method 4449Go - init() method 4550Go - init() method 4651Go - init() method 4752Go - init() method 4853Go - init() method 4954Go - init() method 5055Go - init() method 5156Go - init() method 5257Go - init() method 53

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1func main() {2 td.Init()3 fmt.Println("Hello World")4}5import (6func init() {7 fmt.Println("I am in init method")8}9func main() {10 fmt.Println("Hello World")11}12import (13func init() {14 fmt.Println("I am in init method")15}16func init() {17 fmt.Println("I am in init method 2")18}19func main() {20 fmt.Println("Hello World")21}22import (23func init() {24 fmt.Println("I am in init method")25}26func init() {27 fmt.Println("I am in init method 2")28}29func init() {30 fmt.Println("I am in init method 3")31}32func main() {33 fmt.Println("Hello World")34}35import (36func init() {37 fmt.Println("I am in init method")38}39func init() {40 fmt.Println("I am in init method 2")41}42func init() {43 fmt.Println("I am in init method 3")44}45func main() {46 fmt.Println("Hello World")47}48import (49func init() {50 fmt.Println("I am in init method")51}52func init() {53 fmt.Println("I am in init method 2")54}

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main(){3 fmt.Println("Hello World")4 td1 := td{"Hello","World"}5 td1.print()6 td1.print1()7}8import "fmt"9type td struct {10}11func (t td) print(){12 fmt.Println(t.a,t.b)13}14func (t td) print1(){15 fmt.Println(t.a,t.b)16}17func init(){18 fmt.Println("Init method called")19}

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1func main() {2 td := new(TD)3 td.init()4 td.print()5 td.print()6 td.print()7}

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, world.")4 td.Print()5}6The init method will be executed when the package is imported. The init method can be used to initialize variables, and the main method can be used to call the init method. The init method can be used to initialize variables. The init method i

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 Go-testdeep 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