How to use validateConfig method of cmd Package

Best K6 code snippet using cmd.validateConfig

keys.go

Source:keys.go Github

copy

Full Screen

...44 config, err := types.ReadInConfig(v)45 if err != nil {46 return err47 }48 validateConfig, err := cmd.Flags().GetBool(flagEnableConfigValidation)49 if err != nil {50 return err51 }52 if validateConfig {53 if err := config.Validate(); err != nil {54 return err55 }56 }57 account, err := cmd.Flags().GetUint32(flagAccount)58 if err != nil {59 return err60 }61 index, err := cmd.Flags().GetUint32(flagIndex)62 if err != nil {63 return err64 }65 recoverKey, err := cmd.Flags().GetBool(flagRecover)66 if err != nil {67 return err68 }69 var (70 name = config.Keyring.From71 reader = bufio.NewReader(cmd.InOrStdin())72 )73 if len(args) > 0 {74 name = args[0]75 }76 kr, err := keyring.New(sdk.KeyringServiceName(), config.Keyring.Backend, home, reader)77 if err != nil {78 return err79 }80 if _, err = kr.Key(name); err == nil {81 return fmt.Errorf("key already exists with name %s", name)82 }83 entropy, err := bip39.NewEntropy(256)84 if err != nil {85 return err86 }87 mnemonic, err := bip39.NewMnemonic(entropy)88 if err != nil {89 return err90 }91 if recoverKey {92 mnemonic, err = input.GetString("Enter your bip39 mnemonic", reader)93 if err != nil {94 return err95 }96 if !bip39.IsMnemonicValid(mnemonic) {97 return errors.New("invalid bip39 mnemonic")98 }99 }100 var (101 hdPath = hd.CreateHDPath(sdk.GetConfig().GetCoinType(), account, index)102 algorithms, _ = kr.SupportedAlgorithms()103 )104 algorithm, err := keyring.NewSigningAlgoFromString(string(hd.Secp256k1Type), algorithms)105 if err != nil {106 return err107 }108 key, err := kr.NewAccount(name, mnemonic, "", hdPath.String(), algorithm)109 if err != nil {110 return err111 }112 _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "operator: %s\n", key.GetAddress())113 _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "address: %s\n", hubtypes.NodeAddress(key.GetAddress()))114 _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "\n")115 _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "**Important** write this mnemonic phrase in a safe place\n")116 _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "%s\n", mnemonic)117 return nil118 },119 }120 cmd.Flags().Bool(flagEnableConfigValidation, true, "enable the validation of configuration")121 cmd.Flags().Bool(flagRecover, false, "provide mnemonic phrase to recover an existing key")122 cmd.Flags().Uint32(flagAccount, 0, "account number for HD derivation")123 cmd.Flags().Uint32(flagIndex, 0, "address index number for HD derivation")124 return cmd125}126func keysShow() *cobra.Command {127 cmd := &cobra.Command{128 Use: "show (name)",129 Short: "Show a key",130 Args: cobra.MaximumNArgs(1),131 RunE: func(cmd *cobra.Command, args []string) error {132 var (133 home = viper.GetString(flags.FlagHome)134 configPath = filepath.Join(home, types.ConfigFileName)135 )136 v := viper.New()137 v.SetConfigFile(configPath)138 config, err := types.ReadInConfig(v)139 if err != nil {140 return err141 }142 validateConfig, err := cmd.Flags().GetBool(flagEnableConfigValidation)143 if err != nil {144 return err145 }146 if validateConfig {147 if err := config.Validate(); err != nil {148 return err149 }150 }151 var (152 name = config.Keyring.From153 reader = bufio.NewReader(cmd.InOrStdin())154 )155 if len(args) > 0 {156 name = args[0]157 }158 kr, err := keyring.New(sdk.KeyringServiceName(), config.Keyring.Backend, home, reader)159 if err != nil {160 return err161 }162 key, err := kr.Key(name)163 if err != nil {164 return err165 }166 fmt.Printf("operator: %s\n", key.GetAddress())167 fmt.Printf("address: %s\n", hubtypes.NodeAddress(key.GetAddress()))168 return nil169 },170 }171 cmd.Flags().Bool(flagEnableConfigValidation, true, "enable the validation of configuration")172 return cmd173}174func keysList() *cobra.Command {175 cmd := &cobra.Command{176 Use: "list",177 Short: "List all the keys",178 RunE: func(cmd *cobra.Command, _ []string) error {179 var (180 home = viper.GetString(flags.FlagHome)181 configPath = filepath.Join(home, types.ConfigFileName)182 )183 v := viper.New()184 v.SetConfigFile(configPath)185 config, err := types.ReadInConfig(v)186 if err != nil {187 return err188 }189 validateConfig, err := cmd.Flags().GetBool(flagEnableConfigValidation)190 if err != nil {191 return err192 }193 if validateConfig {194 if err := config.Validate(); err != nil {195 return err196 }197 }198 var (199 reader = bufio.NewReader(cmd.InOrStdin())200 )201 kr, err := keyring.New(sdk.KeyringServiceName(), config.Keyring.Backend, home, reader)202 if err != nil {203 return err204 }205 keys, err := kr.List()206 if err != nil {207 return err208 }209 w := tabwriter.NewWriter(cmd.OutOrStdout(), 1, 1, 1, ' ', 0)210 for _, key := range keys {211 _, _ = fmt.Fprintf(w, "%s\t%s\t%s\n",212 key.GetName(),213 key.GetAddress(),214 hubtypes.NodeAddress(key.GetAddress().Bytes()),215 )216 }217 return w.Flush()218 },219 }220 cmd.Flags().Bool(flagEnableConfigValidation, true, "enable the validation of configuration")221 return cmd222}223func keysDelete() *cobra.Command {224 cmd := &cobra.Command{225 Use: "delete (name)",226 Short: "Delete a key",227 Args: cobra.MaximumNArgs(1),228 RunE: func(cmd *cobra.Command, args []string) error {229 var (230 home = viper.GetString(flags.FlagHome)231 configPath = filepath.Join(home, types.ConfigFileName)232 )233 v := viper.New()234 v.SetConfigFile(configPath)235 config, err := types.ReadInConfig(v)236 if err != nil {237 return err238 }239 validateConfig, err := cmd.Flags().GetBool(flagEnableConfigValidation)240 if err != nil {241 return err242 }243 if validateConfig {244 if err := config.Validate(); err != nil {245 return err246 }247 }248 var (249 name = config.Keyring.From250 reader = bufio.NewReader(cmd.InOrStdin())251 )252 if len(args) > 0 {253 name = args[0]254 }255 kr, err := keyring.New(sdk.KeyringServiceName(), config.Keyring.Backend, home, reader)256 if err != nil {257 return err...

Full Screen

Full Screen

usagereportingconfig_test.go

Source:usagereportingconfig_test.go Github

copy

Full Screen

1package config2import (3 "os"4 "strconv"5 "testing"6 "time"7 "github.com/Axway/agent-sdk/pkg/cmd/properties"8 "github.com/Axway/agent-sdk/pkg/util/exception"9 "github.com/spf13/cobra"10 "github.com/stretchr/testify/assert"11)12func validateUsageReporting(cfg UsageReportingConfig) (err error) {13 exception.Block{14 Try: func() {15 cfg.Validate()16 },17 Catch: func(e error) {18 err = e19 },20 }.Do()21 return22}23type expected struct {24 url string25 publish bool26 metric bool27 subscriptionMetric bool28 interval time.Duration29 offline bool30 schedule string31 reportSchedule string32 granularity int33 qaVars bool34}35var defaultExpected = expected{36 url: "https://lighthouse.admin.axway.com",37 publish: true,38 metric: true,39 subscriptionMetric: false,40 interval: 15 * time.Minute,41 offline: false,42 schedule: "@hourly",43 reportSchedule: "@monthly",44 granularity: 900000,45 qaVars: false,46}47func validateconfig(t *testing.T, expVals expected, cfg UsageReportingConfig) {48 assert.Equal(t, expVals.url, cfg.GetURL())49 assert.Equal(t, expVals.publish, cfg.CanPublishUsage())50 assert.Equal(t, expVals.metric, cfg.CanPublishMetric())51 assert.Equal(t, expVals.interval, cfg.GetInterval())52 assert.Equal(t, expVals.offline, cfg.IsOfflineMode())53 assert.Equal(t, expVals.schedule, cfg.GetSchedule())54 assert.Equal(t, expVals.reportSchedule, cfg.GetReportSchedule())55 assert.Equal(t, expVals.granularity, cfg.GetReportGranularity())56 assert.Equal(t, expVals.qaVars, cfg.UsingQAVars())57}58func TestUsageReportingConfigEnvVarMigration(t *testing.T) {59 rootCmd := &cobra.Command{60 Use: "test",61 }62 props := properties.NewProperties(rootCmd)63 AddUsageReportingProperties(props)64 // Test URL old env vars65 os.Setenv(oldUsageReportingURLEnvVar, "http://lighthouse-old.com")66 expected := defaultExpected67 expected.url = "http://lighthouse-old.com"68 cfg := ParseUsageReportingConfig(props)69 assert.NotNil(t, cfg)70 err := validateUsageReporting(cfg)71 assert.Nil(t, err)72 validateconfig(t, expected, cfg)73 // Test URL new env vars74 os.Setenv(newUsageReportingURLEnvVar, defaultExpected.url)75 expected = defaultExpected76 cfg = ParseUsageReportingConfig(props)77 assert.NotNil(t, cfg)78 err = validateUsageReporting(cfg)79 assert.Nil(t, err)80 validateconfig(t, expected, cfg)81 // Test Interval old env vars82 os.Setenv(oldUsageReportingIntervalEnvVar, "30m")83 expected = defaultExpected84 expected.interval = 30 * time.Minute85 cfg = ParseUsageReportingConfig(props)86 assert.NotNil(t, cfg)87 err = validateUsageReporting(cfg)88 assert.Nil(t, err)89 validateconfig(t, expected, cfg)90 // Test Interval new env vars91 os.Setenv(newUsageReportingIntervalEnvVar, defaultExpected.interval.String())92 expected = defaultExpected93 cfg = ParseUsageReportingConfig(props)94 assert.NotNil(t, cfg)95 err = validateUsageReporting(cfg)96 assert.Nil(t, err)97 validateconfig(t, expected, cfg)98 // Test Publish old env vars99 os.Setenv(oldUsageReportingPublishEnvVar, "false")100 expected = defaultExpected101 expected.publish = false102 cfg = ParseUsageReportingConfig(props)103 assert.NotNil(t, cfg)104 err = validateUsageReporting(cfg)105 assert.Nil(t, err)106 validateconfig(t, expected, cfg)107 // Test Publish new env vars108 os.Setenv(newUsageReportingPublishEnvVar, strconv.FormatBool(defaultExpected.publish))109 expected = defaultExpected110 cfg = ParseUsageReportingConfig(props)111 assert.NotNil(t, cfg)112 err = validateUsageReporting(cfg)113 assert.Nil(t, err)114 validateconfig(t, expected, cfg)115 // Test PublishMetric old env vars116 os.Setenv(oldUsageReportingPublishMetricEnvVar, "true")117 expected = defaultExpected118 expected.metric = true119 cfg = ParseUsageReportingConfig(props)120 assert.NotNil(t, cfg)121 err = validateUsageReporting(cfg)122 assert.Nil(t, err)123 validateconfig(t, expected, cfg)124 // Test PublishMetric new env vars125 os.Setenv(newUsageReportingPublishMetricEnvVar, strconv.FormatBool(defaultExpected.metric))126 expected = defaultExpected127 cfg = ParseUsageReportingConfig(props)128 assert.NotNil(t, cfg)129 err = validateUsageReporting(cfg)130 assert.Nil(t, err)131 validateconfig(t, expected, cfg)132}133func TestUsageReportingConfigProperties(t *testing.T) {134 rootCmd := &cobra.Command{135 Use: "test",136 }137 props := properties.NewProperties(rootCmd)138 // Test default config139 AddUsageReportingProperties(props)140 cfg := ParseUsageReportingConfig(props)141 assert.NotNil(t, cfg)142 err := validateUsageReporting(cfg)143 assert.Nil(t, err)144 validateconfig(t, defaultExpected, cfg)145 // invalid URL146 currentURL := cfg.GetURL()147 cfg.(*UsageReportingConfiguration).URL = "notAURL"148 err = validateUsageReporting(cfg)149 assert.NotNil(t, err)150 cfg.(*UsageReportingConfiguration).URL = currentURL151 // invalid Interval152 currentInterval := cfg.GetInterval()153 cfg.(*UsageReportingConfiguration).Interval = time.Millisecond154 err = validateUsageReporting(cfg)155 assert.NotNil(t, err)156 cfg.(*UsageReportingConfiguration).Interval = currentInterval157 // offline settings, valid158 cfg.(*UsageReportingConfiguration).Offline = true159 err = validateUsageReporting(cfg)160 assert.Nil(t, err)161 // invalid Schedule162 currentSchedule := cfg.GetSchedule()163 cfg.(*UsageReportingConfiguration).Schedule = "*/15 * * * *"164 err = validateUsageReporting(cfg)165 assert.NotNil(t, err)166 cfg.(*UsageReportingConfiguration).Schedule = currentSchedule167 // QA Schedule override168 os.Setenv(qaUsageReportingScheduleEnvVar, "*/1 * * * *")169 cfg.(*UsageReportingConfiguration).Schedule = "*/1 * * * *"170 err = validateUsageReporting(cfg)171 assert.Nil(t, err)172 // QA Report Schedule override173 os.Setenv(qaUsageReportingOfflineScheduleEnvVar, "*/5 * * * *")174 cfg.(*UsageReportingConfiguration).reportSchedule = "*/5 * * * *"175 err = validateUsageReporting(cfg)176 assert.Nil(t, err)177}178func TestNewUsageReporting(t *testing.T) {179 cfg := NewUsageReporting()180 assert.NotNil(t, cfg)181 validateconfig(t, defaultExpected, cfg)182}...

Full Screen

Full Screen

validateconfig.go

Source:validateconfig.go Github

copy

Full Screen

1// Copyright 2020 The Chromium OS Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4package validateconfig5import (6 "context"7 "encoding/json"8 "errors"9 "fmt"10 "io/ioutil"11 "go.chromium.org/luci/auth/client/authcli"12 "go.chromium.org/luci/common/cli"13 "infra/cmd/stable_version2/internal/cmd"14 "infra/cmd/stable_version2/internal/cmd/validateconfig/querygs"15 "infra/cmd/stable_version2/internal/site"16 "infra/cmd/stable_version2/internal/utils"17 vc "infra/cros/stableversion/validateconfig"18 gitlib "infra/libs/git"19 "github.com/maruel/subcommands"20)21// Cmd is the top-level runnable for the validate-config subcommand of stable_version222var Cmd = &subcommands.Command{23 UsageLine: `validate-config /path/to/stable_versions.cfg`,24 ShortDesc: "check that a stable_versions.cfg file is well-formed",25 LongDesc: `check that a stable_versions.cfg file is well-formed.26This command exists solely to validate a stable_versions.cfg file.27Its intended consumer is a submit hook that runs in the infra/config repo.28`,29 CommandRun: func() subcommands.CommandRun {30 c := &command{}31 c.authFlags.Register(&c.Flags, site.DefaultAuthOptions)32 c.Flags.BoolVar(&c.alwaysExitZero, "always-exit-zero", false, "exit successfully regardless of what errors occur.")33 c.Flags.BoolVar(&c.remoteFile, "remote-file", false, "get file from Gitiles instead of locally.")34 return c35 },36}37type command struct {38 subcommands.CommandRunBase39 authFlags authcli.Flags40 alwaysExitZero bool41 remoteFile bool42}43func (c *command) Run(a subcommands.Application, args []string, env subcommands.Env) int {44 failure := 145 if c.alwaysExitZero {46 failure = 047 }48 if err := c.innerRun(a, args, env); err != nil {49 cmd.PrintError(a.GetErr(), err)50 return failure51 }52 return 053}54func (c *command) innerRun(a subcommands.Application, args []string, env subcommands.Env) error {55 ctx := cli.GetContext(a, c, env)56 ctx = cmd.SetupLogging(ctx)57 var contents []byte58 if c.remoteFile {59 var err error60 if len(args) != 0 {61 return errors.New("cannot provide explicit file when using remote file")62 }63 contents, err = fetchGitPath(ctx, cmd.StableVersionConfigPath, &c.authFlags)64 if err != nil {65 return fmt.Errorf("getting remote file contents: %s", err)66 }67 } else {68 var err error69 if len(args) == 0 {70 return errors.New("need at least one file")71 }72 if len(args) > 1 {73 return errors.New("validating multiple files not yet supported")74 }75 contents, err = ioutil.ReadFile(args[0])76 if err != nil {77 return fmt.Errorf("reading local file: %s", err)78 }79 }80 sv, err := vc.InspectBuffer(contents)81 if err != nil {82 return fmt.Errorf("inspecting file: %s", err)83 }84 t, err := cmd.NewAuthenticatedTransport(ctx, &c.authFlags)85 if err != nil {86 return fmt.Errorf("creating authenticated transport: %s", err)87 }88 var r querygs.Reader89 if err := r.Init(ctx, t, utils.Unmarshaller, "validate-config"); err != nil {90 return fmt.Errorf("initializing Google Storage client: %s", err)91 }92 res, err := r.ValidateConfig(ctx, sv)93 if err != nil {94 return fmt.Errorf("valdating config using Google Storage: %s", err)95 }96 res.RemoveAllowedDUTs()97 msg, err := json.MarshalIndent(res, "", " ")98 if err != nil {99 panic("failed to marshal JSON")100 }101 if count := res.AnomalyCount(); count > 0 {102 fmt.Printf("%s\n", msg)103 return fmt.Errorf("(%d) errors detected", count)104 }105 fmt.Printf("%s\n", vc.FileSeemsLegit)106 return nil107}108func fetchGitPath(ctx context.Context, path string, f *authcli.Flags) ([]byte, error) {109 hc, err := cmd.NewHTTPClient(ctx, f)110 if err != nil {111 return nil, err112 }113 gc, err := gitlib.NewClient(ctx, hc, cmd.GerritHost, cmd.GitilesHost, cmd.Project, cmd.Branch)114 if err != nil {115 return nil, fmt.Errorf("creating client: %s", err.Error())116 }117 res, err := gc.GetFile(ctx, cmd.StableVersionConfigPath)118 if err != nil {119 return nil, fmt.Errorf("getting file: %s", err.Error())120 }121 return []byte(res), nil122}...

Full Screen

Full Screen

validateConfig

Using AI Code Generation

copy

Full Screen

1import (2var (3 configFile = flag.String("config", "", "path to config file")4func main() {5 flag.Parse()6 if *configFile == "" {7 fmt.Println("Config file not specified")8 os.Exit(1)9 }10 c := cmd.NewCmd()11 if err := c.ValidateConfig(*configFile); err != nil {12 fmt.Println(err)13 os.Exit(1)14 }15}16import (17var (18 configFile = flag.String("config", "", "path to config file")19func main() {20 flag.Parse()21 if *configFile == "" {22 fmt.Println("Config file not specified")23 os.Exit(1)24 }25 c := cmd.NewCmd()26 if err := c.ValidateConfig(*configFile); err != nil {27 fmt.Println(err)28 os.Exit(1)29 }30}

Full Screen

Full Screen

validateConfig

Using AI Code Generation

copy

Full Screen

1 import (2 func main() {3 fmt.Println(math.pi)4 }5 import (6 func validateConfig() {7 fmt.Println("config validated")8 }9 import (10 func main() {11 mypackage.validateConfig()12 }

Full Screen

Full Screen

validateConfig

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c := cmd.Cmd{}4 c.ValidateConfig()5 fmt.Println("Hello, playground")6}7import (8type Cmd struct {9}10func (c *Cmd) ValidateConfig() {11 fmt.Println("Validating config")12}13import (14type Config struct {15}16func (c *Config) Validate() {17 fmt.Println("Validating config")18}19import "testing"20func TestConfig_Validate(t *testing.T) {21 c := Config{}22 c.Validate()23}24import "testing"25func TestCmd_ValidateConfig(t *testing.T) {26 c := Cmd{}27 c.ValidateConfig()28}29cmd/cmd.go:10:7: c.ValidateConfig undefined (type *Cmd has no field or method ValidateConfig)30import (31func main() {32 tcpAddr, err := net.ResolveTCPAddr("tcp4", service)33 checkError(err)34 conn, err := net.DialTCP("tcp", nil, tcpAddr)35 checkError(err)36 _, err = conn.Write([]byte("HEAD / HTTP/1.0\r37 checkError(err)38 result, err := readFully(conn)39 checkError(err)40 fmt.Println(string(result))41 os.Exit(0)42}43func checkError(err error) {44 if err != nil {45 fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())46 os.Exit(1)47 }48}49func readFully(conn *net.TCPConn) ([]byte

Full Screen

Full Screen

validateConfig

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World!")4 cmd.ValidateConfig()5}6import (7type Cmd struct {8}9func ValidateConfig() {10 fmt.Println("ValidateConfig")11 config.ValidateConfig()12}13import (14type Config struct {15}16func ValidateConfig() {17 fmt.Println("ValidateConfig")18}

Full Screen

Full Screen

validateConfig

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World!")4 v := validate.NewCmd()5 v.ValidateConfig()6}

Full Screen

Full Screen

validateConfig

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 var cmd = flag.String("cmd", "", "command to be executed")4 flag.Parse()5 c := cmd{}6 c.validateConfig(*cmd)7}8import (9func (c *cmd) validateConfig(cmd string) {10 file, err := os.Open("config.txt")11 if err != nil {12 fmt.Println(err)13 }14 defer file.Close()15 scanner := bufio.NewScanner(file)16 for scanner.Scan() {17 line := strings.Split(scanner.Text(), ":")18 if key == "cmd" {19 if value == cmd {20 scanner.Scan()21 line := strings.Split(scanner.Text(), ":")22 if key == "cmd" {23 if value == cmd {24 scanner.Scan()25 line := strings.Split(scanner.Text(), ":")26 if key == "cmd" {27 if value == cmd {28 scanner.Scan()29 line := strings.Split(scanner.Text(), ":")

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 K6 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