From 40fb0ee57bd94ddb4e4eff6a04b2bb275e36b02f Mon Sep 17 00:00:00 2001 From: Ian Cordasco Date: Sat, 26 Jul 2014 11:26:55 -0500 Subject: [PATCH] Add merge_paths function and tests for it --- rfc3986/misc.py | 11 +++++++++++ tests/test_misc.py | 47 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 tests/test_misc.py diff --git a/rfc3986/misc.py b/rfc3986/misc.py index b89269b..7cc02a9 100644 --- a/rfc3986/misc.py +++ b/rfc3986/misc.py @@ -197,3 +197,14 @@ hier_part = '(//%s%s|%s|%s|%s)' % ( ABSOLUTE_URI_MATCHER = re.compile('^%s:%s(\?%s)$' % ( component_pattern_dict['scheme'], hier_part, QUERY_MATCHER.pattern )) + + +# Path merger as defined in http://tools.ietf.org/html/rfc3986#section-5.2.3 +def merge_paths(base_uri, relative_path): + """Merge a base URI's path with a relative URI's path.""" + if base_uri.path is None and base_uri.authority is not None: + return '/' + relative_path + else: + path = base_uri.path or '' + index = path.rfind('/') + return path[:index] + '/' + relative_path diff --git a/tests/test_misc.py b/tests/test_misc.py new file mode 100644 index 0000000..eced326 --- /dev/null +++ b/tests/test_misc.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +from rfc3986.uri import URIReference +from rfc3986.misc import merge_paths + + +def test_merge_paths_with_base_path_without_base_authority(): + """Demonstrate merging with a base URI without an authority.""" + base = URIReference(scheme=None, + authority=None, + path='/foo/bar/bogus', + query=None, + fragment=None) + expected = '/foo/bar/relative' + assert merge_paths(base, 'relative') == expected + + +def test_merge_paths_with_base_authority_and_path(): + """Demonstrate merging with a base URI with an authority and path.""" + base = URIReference(scheme=None, + authority='authority', + path='/foo/bar/bogus', + query=None, + fragment=None) + expected = '/foo/bar/relative' + assert merge_paths(base, 'relative') == expected + + +def test_merge_paths_without_base_authority_or_path(): + """Demonstrate merging with a base URI without an authority or path.""" + base = URIReference(scheme=None, + authority=None, + path=None, + query=None, + fragment=None) + expected = '/relative' + assert merge_paths(base, 'relative') == expected + + +def test_merge_paths_with_base_authority_without_path(): + """Demonstrate merging with a base URI without an authority or path.""" + base = URIReference(scheme=None, + authority='authority', + path=None, + query=None, + fragment=None) + expected = '/relative' + assert merge_paths(base, 'relative') == expected