Last active
August 29, 2015 14:06
-
-
Save whosaysni/b6acadedbb0571f079a5 to your computer and use it in GitHub Desktop.
Doctesting argparse with multiprocessing / multiprocessing で argparse の doctest を書く
This file contains hidden or 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
""" | |
>>> from argparse import ArgumentParser | |
>>> from multiprocessing import Process, Queue | |
>>> def build_parser(): | |
... parser = ArgumentParser() | |
... parser.add_argument('-e', '--engage', action='store_true') | |
... parser.add_argument('-b', '--beam-me-up', action='store_true') | |
... parser.add_argument('-d', '--good-day-to-die', action='store_true') | |
... # blah blah blah | |
... return parser | |
... | |
>>> def task(args, tx_queue, ns_queue): | |
... parser = build_parser() | |
... def queue_message(message, file=None): | |
... tx_queue.put(message) | |
... parser._print_message = queue_message | |
... ns = parser.parse_args(args) | |
... ns_queue.put(ns._get_args()) | |
... ns_queue.put(ns._get_kwargs()) | |
... | |
>>> def do_forked_test(args): | |
... tx_queue, ns_queue = Queue(), Queue() | |
... proc = Process(target=task, args=(args, tx_queue, ns_queue)) | |
... proc.start(); proc.join() | |
... while not tx_queue.empty(): | |
... print tx_queue.get() | |
... args = [] if ns_queue.empty() else ns_queue.get() | |
... kwargs = [] if ns_queue.empty() else ns_queue.get() | |
... tx_queue.close(), ns_queue.close() | |
... return (proc.exitcode, args, kwargs) | |
... | |
>>> do_forked_test([]) | |
(0, [], [('beam_me_up', False), ('engage', False), ('good_day_to_die', False)]) | |
>>> do_forked_test(['-h']) | |
usage: [-h] [-e] [-b] [-d] | |
<BLANKLINE> | |
optional arguments: | |
-h, --help show this help message and exit | |
-e, --engage | |
-b, --beam-me-up | |
-d, --good-day-to-die | |
<BLANKLINE> | |
(0, [], []) | |
>>> do_forked_test(['-x']) | |
usage: [-h] [-e] [-b] [-d] | |
<BLANKLINE> | |
: error: unrecognized arguments: -x | |
<BLANKLINE> | |
(2, [], []) | |
""" | |
if __name__=='__main__': | |
from doctest import testmod | |
testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment