-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Support enum types as option arguments
Special case passing an Enum subclass as the type for an option argument, converting it internally into a "choice" style optparse flag.
- Loading branch information
Showing
2 changed files
with
81 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
# noqa: INP001 | ||
# | ||
# -*- coding: utf-8 -*- | ||
# | ||
# Copyright © 2022 Adrian Perez de Castro <aperez@igalia.com> | ||
# | ||
# Distributed under terms of the MIT license. | ||
|
||
from cmdcmd import cmd | ||
from enum import Enum | ||
|
||
|
||
class Protocol(Enum): | ||
UDP = "udp" | ||
TCP = "tcp" | ||
ICMP = "icmp" | ||
ARP = "arp" | ||
|
||
|
||
class cmd_foo(cmd.Command): | ||
takes_options = ( | ||
cmd.Option("protocol", short_name="p", help="Protocol", type=Protocol), | ||
) | ||
|
||
def run(self, protocol=Protocol.ARP): | ||
assert isinstance(protocol, Protocol) | ||
return protocol | ||
|
||
|
||
def test_enum_option(): | ||
cli = cmd.CLI("foobar", commands=(cmd_foo,)) | ||
assert cli.run(["foo"]) == Protocol.ARP | ||
assert cli.run(["foo", "-p", "tcp"]) == Protocol.TCP | ||
assert cli.run(["foo", "--protocol=udp"]) == Protocol.UDP | ||
assert cli.run(["foo", "--protocol", "udp"]) == Protocol.UDP | ||
|
||
|
||
def test_enum_option_invalid_value(): | ||
cli = cmd.CLI("foobar", commands=(cmd_foo,)) | ||
assert "invalid choice" in cli.run(["foo", "-p", "bananas"]) | ||
assert "invalid choice" in cli.run(["foo", "--protocol=bananas"]) | ||
assert "invalid choice" in cli.run(["foo", "--protocol", "bananas"]) |