Adds parser tests using the class attributes. Classes of this type should specify the following attributes: argument_signatures -- a list of Sig objects which specify the signatures of Argument objects to be created failures -- a list of args lists that should cause the parser
| 200 | |
| 201 | |
| 202 | class ParserTesterMetaclass(type): |
| 203 | """Adds parser tests using the class attributes. |
| 204 | |
| 205 | Classes of this type should specify the following attributes: |
| 206 | |
| 207 | argument_signatures -- a list of Sig objects which specify |
| 208 | the signatures of Argument objects to be created |
| 209 | failures -- a list of args lists that should cause the parser |
| 210 | to fail |
| 211 | successes -- a list of (initial_args, options, remaining_args) tuples |
| 212 | where initial_args specifies the string args to be parsed, |
| 213 | options is a dict that should match the vars() of the options |
| 214 | parsed out of initial_args, and remaining_args should be any |
| 215 | remaining unparsed arguments |
| 216 | """ |
| 217 | |
| 218 | def __init__(cls, name, bases, bodydict): |
| 219 | if name == 'ParserTestCase': |
| 220 | return |
| 221 | |
| 222 | # default parser signature is empty |
| 223 | if not hasattr(cls, 'parser_signature'): |
| 224 | cls.parser_signature = Sig() |
| 225 | if not hasattr(cls, 'parser_class'): |
| 226 | cls.parser_class = ErrorRaisingArgumentParser |
| 227 | |
| 228 | # --------------------------------------- |
| 229 | # functions for adding optional arguments |
| 230 | # --------------------------------------- |
| 231 | def no_groups(parser, argument_signatures): |
| 232 | """Add all arguments directly to the parser""" |
| 233 | for sig in argument_signatures: |
| 234 | parser.add_argument(*sig.args, **sig.kwargs) |
| 235 | |
| 236 | def one_group(parser, argument_signatures): |
| 237 | """Add all arguments under a single group in the parser""" |
| 238 | group = parser.add_argument_group('foo') |
| 239 | for sig in argument_signatures: |
| 240 | group.add_argument(*sig.args, **sig.kwargs) |
| 241 | |
| 242 | def many_groups(parser, argument_signatures): |
| 243 | """Add each argument in its own group to the parser""" |
| 244 | for i, sig in enumerate(argument_signatures): |
| 245 | group = parser.add_argument_group('foo:%i' % i) |
| 246 | group.add_argument(*sig.args, **sig.kwargs) |
| 247 | |
| 248 | # -------------------------- |
| 249 | # functions for parsing args |
| 250 | # -------------------------- |
| 251 | def listargs(parser, args): |
| 252 | """Parse the args by passing in a list""" |
| 253 | return parser.parse_args(args) |
| 254 | |
| 255 | def sysargs(parser, args): |
| 256 | """Parse the args by defaulting to sys.argv""" |
| 257 | old_sys_argv = sys.argv |
| 258 | sys.argv = [old_sys_argv[0]] + args |
| 259 | try: |