Skip to content

Latest commit

 

History

History
40 lines (37 loc) · 1.36 KB

validator.md

File metadata and controls

40 lines (37 loc) · 1.36 KB

Validator

Validator can be used for testing and controlling many aspects of cobra commands. It provides many rules out of the box for validating the commands.

Rules provided by validator

  • LengthRule
  • MustExistRule
  • UseMatchesRule

We are working on the validator library to provide more rules

How to use

It is recommended to use the validator while writing unit tests for cobra commands.

  1. Create a configuration of type rules.ValidatorConfig. You can provide your own ValidatorConfig or use the default one by leaving it empty
var ruleCfg rules.ValidatorConfig

or overriding default config

ruleCfg := rules.ValidatorConfig{
	ValidatorRules: rules.ValidatorRules{
		Length: rules.Length{Limits: map[string]rules.Limit{"Use": {Min: 1}}},
		MustExist: rules.MustExist{Fields: map[string]bool{"Args": true}},
	},
}
  1. Generate the validation errors by using ExecuteRules function over the ruleCfg
validationErr := rules.ExecuteRules(cmd, &ruleCfg)

ExecuteRules function will return a slice of ValidationError object, which can be efficiently used for testing purposes.

if len(validationErr) != 0 {
	t.Errorf("validationErr was not empty, got length: %d; want %d", len(validationErr), 0)
}
for _, errs := range validationErr {
	if errs.Err != nil {
		t.Errorf("%s: cmd %s: %s", errs.Rule, errs.Cmd.CommandPath(), errs.Name)
	}
}