@@ -671,6 +671,76 @@ func TestOptLookups(t *testing.T) {
671671 }()
672672 }
673673 }
674+
675+ in = NewCmd ("program" ).
676+ Opt (NewOpt ("a" ).Default ("A" )).
677+ Opt (NewOpt ("b" ).Default ("B" ))
678+
679+ // with both options present
680+ {
681+ c := in .ParseOrExit ("-ahello" , "-bworld" )
682+ // straight getting the opts
683+ {
684+ optA := Get [string ](c , "a" )
685+ if optA != "hello" {
686+ t .Errorf (`expected "hello" for option a, got "%s"` , optA )
687+ }
688+ optB := Get [string ](c , "b" )
689+ if optB != "world" {
690+ t .Errorf (`expected "world" for option b, got "%s"` , optB )
691+ }
692+ }
693+ // above should be identical with lookups
694+ {
695+ optA , ok := Lookup [string ](c , "a" )
696+ if optA != "hello" || ! ok {
697+ t .Errorf (`expected ("hello", true) for option a lookup, got ("%s", %v)` , optA , ok )
698+ }
699+ optB , ok := Lookup [string ](c , "b" )
700+ if optB != "world" || ! ok {
701+ t .Errorf (`expected ("world", true) for option b lookup, got ("%s", %v)` , optB , ok )
702+ }
703+ }
704+ }
705+
706+ // with only the first option 'a' provided
707+ {
708+ c := in .ParseOrExit ("-ahello" )
709+ // first one should be there, second one default
710+ {
711+ optA , ok := Lookup [string ](c , "a" )
712+ if optA != "hello" || ! ok {
713+ t .Errorf (`expected ("hello", true) for option 'a' lookup, got ("%s", %v)` , optA , ok )
714+ }
715+ optB , ok := Lookup [string ](c , "b" )
716+ if optB != "B" || ! ok {
717+ t .Errorf (`expected ("B", true) for option 'b' lookup, got (%s, %v)` , optB , ok )
718+ }
719+ }
720+ // based on the above assertions, we should get the right fallback for option 'b'
721+ {
722+ optA := GetOr (c , "a" , "hey" )
723+ if optA != "hello" {
724+ t .Errorf (`expected "hello" for option 'a', got "%s"` , optA )
725+ }
726+ optB := GetOr (c , "b" , "earth" )
727+ if optB != "B" {
728+ t .Errorf (`expected to not use fallback for option 'b' and get "B", got "%s"` , optB )
729+ }
730+ }
731+ // trying to cast the first one to anything but a string should panic
732+ {
733+ func () {
734+ defer func () {
735+ gotPanicVal := recover ()
736+ if gotPanicVal == nil {
737+ t .Fatalf ("didn't panic when trying to cast a string arg to an int" )
738+ }
739+ }()
740+ _ = Get [int ](c , "a" )
741+ }()
742+ }
743+ }
674744}
675745
676746func TestArgLookups (t * testing.T ) {
0 commit comments