From 0c4c6c47536a853cf1ac0bb3ff69261a380173e3 Mon Sep 17 00:00:00 2001 From: Jakub Roztocil Date: Wed, 11 Apr 2012 13:47:47 +0200 Subject: [PATCH] Added --auth-type and tests for basic/digest auth. Closes #38. --- httpie/__main__.py | 9 +++++---- httpie/cli.py | 9 ++++++++- tests/tests.py | 15 +++++++++++++++ 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/httpie/__main__.py b/httpie/__main__.py index 7854faa1..d7b12067 100644 --- a/httpie/__main__.py +++ b/httpie/__main__.py @@ -134,10 +134,11 @@ def main(args=None, # Fire the request. try: credentials = None - if args.auth and args.digest: - credentials = requests.auth.HTTPDigestAuth(args.auth.key, args.auth.value) - elif args.auth: - credentials = requests.auth.HTTPBasicAuth(args.auth.key, args.auth.value) + if args.auth: + auth_type = (requests.auth.HTTPDigestAuth + if args.auth_type == 'digest' + else requests.auth.HTTPBasicAuth) + credentials = auth_type(args.auth.key, args.auth.value) response = requests.request( method=args.method.lower(), diff --git a/httpie/cli.py b/httpie/cli.py index 48f512ea..32874546 100644 --- a/httpie/cli.py +++ b/httpie/cli.py @@ -100,6 +100,7 @@ class HTTPieArgumentParser(argparse.ArgumentParser): def parse_args(self, args=None, namespace=None): args = super(HTTPieArgumentParser, self).parse_args(args, namespace) self._validate_output_options(args) + self._validate_auth_options(args) return args def _validate_output_options(self, args): @@ -107,6 +108,11 @@ class HTTPieArgumentParser(argparse.ArgumentParser): if unknown_output_options: self.error('Unknown output options: %s' % ','.join(unknown_output_options)) + def _validate_auth_options(self, args): + if args.auth_type and not args.auth: + self.error('--auth-type can only be used with --auth') + + parser = HTTPieArgumentParser(description=doc.strip(),) parser.add_argument('--version', action='version', version=version) @@ -217,7 +223,8 @@ parser.add_argument( ) parser.add_argument( - '--digest', '-d', action='store_true', help=_('Use Digest authentication') + '--auth-type', choices=['basic', 'digest'], + help=_('The type of authentication ("basic" or "digest"). Defaults to "basic".') ) parser.add_argument( diff --git a/tests/tests.py b/tests/tests.py index a8504760..0570d446 100644 --- a/tests/tests.py +++ b/tests/tests.py @@ -139,5 +139,20 @@ class TestFileUpload(BaseTest): self.assertIn('"test-file": "__test_file_content__', r) +class TestAuth(BaseTest): + + def test_basic_auth(self): + r = http('--auth', 'user:password', + 'GET', 'httpbin.org/basic-auth/user/password') + self.assertIn('"authenticated": true', r) + self.assertIn('"user": "user"', r) + + def test_digest_auth(self): + r = http('--auth-type=digest', '--auth', 'user:password', + 'GET', 'httpbin.org/digest-auth/auth/user/password') + self.assertIn('"authenticated": true', r) + self.assertIn('"user": "user"', r) + + if __name__ == '__main__': unittest.main()