예제 #1
0
def test_HALNavigator__init_accept_schemaless():
    uri = 'www.example.com'
    N = HN.HALNavigator(uri)
    assert N.uri == 'http://' + uri
    uri2 = 'http://example.com'
    N_first = HN.HALNavigator(uri2)
    assert N_first.uri == uri2
예제 #2
0
def test_HALNavigator__authenticate(random_string):
    with httprettify() as HTTPretty:
        index_uri = 'http://www.example.com/api/'
        auth_uri = 'http://www.example.com/api/auth'
        index_links = {'start': {'href': auth_uri}}
        username = next(random_string)
        password = next(random_string)

        def auth_callback(r, uri, headers):
            username_ok = r.headers.get('Username') == username
            password_ok = r.headers.get('Password') == password
            if username_ok and password_ok:
                return (200, headers, json.dumps({'authenticated': True}))
            else:
                return (401, headers, json.dumps({'authenticated': False}))

        register_hal(index_uri, index_links)
        HTTPretty.register_uri('GET', auth_uri, body=auth_callback)

        def toy_auth(req):
            req.headers['Username'] = username
            req.headers['Password'] = password
            return req

        N = HN.HALNavigator(index_uri, apiname='N1', auth=toy_auth)
        assert N['start']()['authenticated']

        N2 = HN.HALNavigator(index_uri, apiname='N2', auth=None)
        N2_auth = N2['start']
        N2_auth(raise_exc=False)
        assert N2_auth.status == (401, 'Unauthorized')
        N2.authenticate(toy_auth)
        assert N2_auth.fetch()['authenticated']
예제 #3
0
def test_HALNAvigator__repr():
    with httprettify():
        index_uri = 'http://www.example.com/api/'
        first_uri = 'http://www.example.com/api/first'
        next_uri = 'http://www.example.com/api/foos/123f/bars/234'
        user_uri = 'http://www.example.com/api/users/ko%C5%BEu%C5%A1%C4%8Dek'
        last_uri = 'http://www.example.com/api/last'
        register_hal(
            index_uri, {
                'first': {
                    'href': first_uri
                },
                'next': {
                    'href': next_uri
                },
                'last': {
                    'href': last_uri
                },
                'describes': {
                    'href': user_uri
                }
            })

        N_1 = HN.HALNavigator(index_uri)
        assert repr(N_1) == "HALNavigator(ExampleAPI)"
        N = HN.HALNavigator(index_uri, apiname='exampleAPI')
        assert repr(N) == "HALNavigator(exampleAPI)"
        assert repr(N['first']) == "HALNavigator(exampleAPI.first)"
        assert repr(N['next']) == \
            "HALNavigator(exampleAPI.foos.123f.bars[234])"
        assert repr(N['last']) == "HALNavigator(exampleAPI.last)"
        assert repr(N['describes']) == \
          "HALNavigator(exampleAPI.users.kozuscek)"
예제 #4
0
def test_HALNavigator__eq__(name1, uri1, name2, uri2, equal):
    N1 = HN.HALNavigator(uri1, apiname=name1)
    N2 = HN.HALNavigator(uri2, apiname=name2)
    if equal:
        assert N1 == N2
        assert N2 == N1
    else:
        assert N1 != N2
        assert N2 != N1
예제 #5
0
def test_HALNavigator__boolean_fetched():
    with httprettify():
        register_hal(status=200)

        N = HN.HALNavigator('http://www.example.com/')
        N()
        assert N

        register_hal(status=500)
        N = HN.HALNavigator('http://www.example.com/')
        N(raise_exc=False)
        assert not N
예제 #6
0
def test_HALNavigator__links():
    with httprettify():
        register_hal(
            'http://www.example.com/',
            links={'ht:users': {
                'href': 'http://www.example.com/users'
            }})
        N = HN.HALNavigator('http://www.example.com')
        expected = {
            'ht:users': HN.HALNavigator('http://www.example.com')['ht:users']
        }
        assert N.links == expected
예제 #7
0
def test_HALNavigator__fetch():
    with httprettify() as HTTPretty:
        index_uri = r'http://www.example.com'
        index_re = re.compile(index_uri)
        index_links = {'self': {'href': index_uri}}
        body1 = {'name': 'body1', '_links': index_links}
        body2 = {'name': 'body2', '_links': index_links}
        responses = [
            httpretty.Response(body=json.dumps(body1)),
            httpretty.Response(body=json.dumps(body2))
        ]
        HTTPretty.register_uri(method='GET',
                               uri=index_re,
                               headers={
                                   'content_type': 'application/hal+json',
                                   'server': 'HTTPretty 0.6.0'
                               },
                               responses=responses)
        N = HN.HALNavigator(index_uri)
        fetch1 = N()
        fetch2 = N()
        fetch3 = N.fetch()
        assert fetch1['name'] == 'body1'
        assert fetch2['name'] == 'body1'
        assert fetch3['name'] == 'body2'
예제 #8
0
def test_HALNavigator__create_response_with_new_resource_location(
        status_code, post_body):
    with httprettify() as HTTPretty:
        index_uri = 'http://www.example.com/api/'
        hosts_uri = index_uri + 'hosts'
        new_resource_uri = index_uri + 'new_resource'
        index_links = {'hosts': {'href': hosts_uri}}
        register_hal(index_uri, index_links)
        register_hal(new_resource_uri)
        HTTPretty.register_uri(
            'POST',
            uri=hosts_uri,
            location=new_resource_uri,
            status=status_code,
        )
        N = HN.HALNavigator(index_uri)
        N2 = N['hosts'].create(post_body)
        assert HTTPretty.last_request.method == 'POST'
        last_content_type = HTTPretty.last_request.headers['content-type']
        assert last_content_type == 'application/json'
        if status_code == 201:
            assert HTTPretty.last_request.body == ''
        else:
            assert HTTPretty.last_request.body == '{"name":"foo"}'
        assert N2.uri == new_resource_uri
        assert not N2.fetched
예제 #9
0
def test_HALNavigator__iteration():
    r'''Test that a navigator with 'next' links can be used for iteration'''
    with httprettify():
        index_uri = 'http://www.example.com/'
        index_links = {'first': {'href': index_uri + '1'}}
        register_hal(index_uri, index_links)
        for i in xrange(1, 11):
            page_uri = index_uri + str(i)
            if i < 10:
                page_links = {'next': {'href': index_uri + str(i + 1)}}
            else:
                page_links = {}
            register_hal(page_uri, page_links)

        N = HN.HALNavigator(index_uri)
        Nitems = N['first']
        captured = []
        for i, nav in enumerate(Nitems, start=1):
            if i == 0:
                assert nav is Nitems
            else:
                assert isinstance(nav, HN.HALNavigator)
                assert nav.uri == index_uri + str(i)
            captured.append(nav)
        assert len(captured) == 10
예제 #10
0
def test_HALNavigator__getitem_self_link():
    with httprettify():
        uri = 'http://www.example.com/index'
        title = 'Some kinda title'
        register_hal(uri, title=title)

        N = HN.HALNavigator(uri)
        N()  # fetch it
        assert N.title == title
예제 #11
0
def test_HALNavigator__status(status, reason):
    with httprettify():
        index_uri = 'http://www.example.com/'
        register_hal(index_uri, status=status)

        N = HN.HALNavigator(index_uri)
        assert N.status is None
        N()
        assert N.status == (status, reason)
예제 #12
0
def test_HALNavigator__default_curie_iana_conflict(reltest_links):
    with httprettify() as HTTPretty:
        index_uri = "http://example.com/api"
        del reltest_links['next']
        register_hal(index_uri, links=reltest_links)

        N = HN.HALNavigator(index_uri, curie="xx")

        assert N['next'] is N['xx:next']
예제 #13
0
def test_HALNavigator__custom_headers():
    with httprettify() as HTTPretty:
        index_uri = 'http://www.example.com/'
        register_hal(index_uri, {})

        custom_headers = {'X-Pizza': 'true'}
        N = HN.HALNavigator(index_uri, headers=custom_headers)
        N()
        assert HTTPretty.last_request.headers.get('X-Pizza')
예제 #14
0
def test_HALNavigator__boolean(status, boolean):
    with httprettify():
        register_hal(status=status)

        N = HN.HALNavigator('http://www.example.com/')
        if boolean:
            assert N
        else:
            assert not N
예제 #15
0
def test_HALNavigator__not_json():
    '''This is a pretty common problem'''
    with httprettify() as HTTPretty:
        index_uri = 'http://www.example.com/api/'
        html = '<p>\n\tThis is not JSON\n</p>'
        HTTPretty.register_uri('GET', index_uri, body=html)

        N = HN.HALNavigator(index_uri)
        with pytest.raises(HN.UnexpectedlyNotJSON):
            N()
예제 #16
0
def test_HALNavigator__default_curie_wrong_curie(reltest_links):
    with httprettify() as HTTPretty:
        index_uri = "http://example.com/api"
        register_hal(index_uri, links=reltest_links)

        N = HN.HALNavigator(index_uri, curie="xx")

        N1 = N['nonstandard-rel']
        N2 = N['yy:nonstandard-rel']

        assert N1 is not N2
예제 #17
0
def test_HALNavigator__call():
    with httprettify():
        uri = 'http://www.example.com/index'
        server_state = dict(some_attribute='some value')
        register_hal(uri=uri, state=server_state, title='Example Title')

        N = HN.HALNavigator(uri)
        assert N.state is None
        assert N() == server_state
        assert N.state == N()
        assert N.state is not N()
        assert N() is not N()
예제 #18
0
def test_HALNavigator__get_by_properties_single(bigtest_1):
    with httprettify() as HTTPretty:
        register_hal(bigtest_1.index_uri, bigtest_1.index_links)

        N = HN.HALNavigator(bigtest_1.index_uri)
        baz = N.links['test:foo'].get_by('name', 'baz')
        bar = N.links['test:foo'].get_by('name', 'bar')
        qux = N.links['test:foo'].get_by('name', 'qux')
        not_found = N.links['test:foo'].get_by('name', 'not_found')
        assert baz.uri == bigtest_1.index_links['test:foo'][1]['href']
        assert bar.uri == bigtest_1.index_links['test:foo'][0]['href']
        assert qux.uri == bigtest_1.index_links['test:foo'][2]['href']
        assert not_found is None
예제 #19
0
def test_HALNavigator__bad_getitem_objs():
    with httprettify():
        index_uri = 'http://www.example.com/'
        index_regex = re.compile(index_uri + '.*')
        template_href = 'http://www.example.com/{?max,page}'
        index_links = {'first': {'href': template_href, 'templated': True}}
        register_hal(index_regex, index_links)

        N = HN.HALNavigator(index_uri)
        with pytest.raises(TypeError):
            N[{'set'}]
        with pytest.raises(TypeError):
            N[12]
예제 #20
0
def test_HALNavigator__parameters():
    with httprettify():
        index_uri = 'http://www.example.com/'
        index_links = {
            'about': {
                'href': 'http://{.domain*}{/a,b}{?q,r}',
                'templated': True
            }
        }
        register_hal(index_uri, index_links)

        N = HN.HALNavigator(index_uri)
        assert N['about'].parameters == set(['a', 'b', 'q', 'r', 'domain'])
예제 #21
0
def test_HALNavigator__default_curie_conflict(reltest_links):
    with httprettify() as HTTPretty:
        index_uri = "http://example.com/api"
        register_hal(index_uri, links=reltest_links)

        N = HN.HALNavigator(index_uri, curie="xx")

        N1 = N['next']

        assert N1.uri == 'http://example.com/api/next'

        N2 = N['xx:next']

        assert N2.uri == 'http://example.com/api/xxnext'
예제 #22
0
def test_HALNavigator__double_dereference():
    with httprettify():
        index_uri = 'http://www.example.com/'
        first_uri = index_uri + '1'
        second_uri = index_uri + '2'
        index_links = {'first': {'href': first_uri}}
        first_links = {'second': {'href': second_uri}}
        second_links = {}
        register_hal(index_uri, index_links)
        register_hal(first_uri, first_links)
        register_hal(second_uri, second_links)

        N = HN.HALNavigator(index_uri)
        assert N['first', 'second'].uri == second_uri
예제 #23
0
def test_HALNavigator__relative_link():
    with httprettify():
        index_uri = 'http://www.example.com/api/'
        relative_uri = 'another/link'
        relative_templated = 'another/{link}'
        index_links = {
            'alternate': [{
                'href': index_uri + relative_uri
            }, {
                'href': index_uri + relative_templated,
                'templated': True
            }],
        }
        register_hal(index_uri, index_links)
        N = HN.HALNavigator(index_uri)
        assert N['alternate'][0].relative_uri == '/' + relative_uri
        assert N['alternate'][1].relative_uri == '/' + relative_templated
예제 #24
0
def test_HALNavigator__get_by_properties_multi(bigtest_1):
    with httprettify() as HTTPretty:
        register_hal(bigtest_1.index_uri, bigtest_1.index_links)

        N = HN.HALNavigator(bigtest_1.index_uri)
        bar = N.links['test:foo'].get_by('name', 'bar')
        baz = N.links['test:foo'].get_by('name', 'baz')
        qux = N.links['test:foo'].get_by('name', 'qux')

        bazs = N.links['test:foo'].getall_by('name', 'baz')
        assert bazs == [baz]
        not_founds = N.links['test:foo'].getall_by('name', 'not_founds')
        assert not_founds == []
        widgets = N.links['test:foo'].getall_by('profile',
                                                bigtest_1.widget_profile)
        gadgets = N.links['test:foo'].getall_by('profile',
                                                bigtest_1.gadget_profile)
        assert widgets == [bar, qux]
        assert gadgets == [baz]
예제 #25
0
def test_HALNavigator__expand():
    r'''Tests various aspects of template expansion'''
    with httprettify():
        index_uri = 'http://www.example.com/'
        template_uri = 'http://www.example.com/{?x,y,z}'
        index_links = {
            'template': {
                'href': template_uri,
                'templated': True,
            }
        }
        register_hal(index_uri, index_links)

        N = HN.HALNavigator(index_uri)

        unexpanded = N['template']
        unexpanded2 = N['template']
        assert unexpanded is not unexpanded2
        assert unexpanded.uri is None
        assert unexpanded.template_uri == index_links['template']['href']
        assert unexpanded.templated

        expanded = unexpanded.expand(x=1, y=2, z=3)
        expanded2 = unexpanded.expand(x=1, y=2, z=3)
        assert expanded is expanded2
        assert expanded is not unexpanded
        assert expanded.template_uri is None
        assert expanded.template_args is None
        assert expanded.uri == uritemplate.expand(template_uri,
                                                  variables=dict(x=1, y=2,
                                                                 z=3))

        half_expanded = unexpanded.expand(_keep_templated=True, x=1, y=2)
        half_expanded2 = unexpanded.expand(_keep_templated=True, x=1, y=2)
        # half expanded templates don't go into the id map
        assert half_expanded is not half_expanded2
        # but they should be equivalent
        assert half_expanded == half_expanded2
        assert half_expanded.uri == uritemplate.expand(template_uri,
                                                       variables=dict(x=1,
                                                                      y=2))
        assert half_expanded.template_uri == template_uri
        assert half_expanded.template_args == dict(x=1, y=2)
예제 #26
0
def test_HALNavigator__raise_exc(status, raise_exc):
    with httprettify():
        index_uri = 'http://www.example.com/'
        next_uri = index_uri + 'next'
        index_links = {'next': {'href': next_uri}}
        register_hal(index_uri, index_links)
        register_hal(next_uri, status=status)

        N = HN.HALNavigator('http://www.example.com/')
        if raise_exc:
            with pytest.raises(HN.HALNavigatorError):
                N['next']()
            try:
                N['next'].fetch()
            except HN.HALNavigatorError as hn:
                assert hn.nav.status[0] == status
        else:
            N['next'](raise_exc=False)
            assert N['next'].status[0] == status
예제 #27
0
def test_HALNavigator__create_response_without_location_info(
        status_code, status_reason):
    with httprettify() as HTTPretty:
        index_uri = 'http://www.example.com/api/'
        hosts_uri = index_uri + 'hosts'
        post_body = {'name': 'foo'}
        index_links = {'hosts': {'href': hosts_uri}}
        register_hal(index_uri, index_links)
        HTTPretty.register_uri(
            'POST',
            uri=hosts_uri,
            status=status_code,
        )
        N = HN.HALNavigator(index_uri)
        N2 = N['hosts'].create(post_body)
        assert HTTPretty.last_request.method == 'POST'
        assert N2 == (
            status_code,
            status_reason,
        )
예제 #28
0
def test_HALNavigator__dont_get_template_links():
    with httprettify():
        index_uri = 'http://www.example.com/'
        index_regex = re.compile(index_uri + '.*')
        template_href = 'http://www.example.com/{?max,page}'
        index_links = {'first': {'href': template_href, 'templated': True}}
        register_hal(index_regex, index_links)

        N = HN.HALNavigator(index_uri)
        with pytest.raises(TypeError):
            assert N['page':0]  # N is not templated
        with pytest.raises(HN.exc.AmbiguousNavigationError):
            assert N['first']()  # N['first'] is templated
        assert N['first'].templated
        assert N['first']['page':0].uri == 'http://www.example.com/?page=0'
        assert not N['first']['page':0].templated
        with pytest.raises(ValueError):
            assert N['first'][:'page':0]
        with pytest.raises(ValueError):
            assert N['first'][::'page']
예제 #29
0
def test_HALNavigator__multiple_links():
    with httprettify():
        index_uri = 'http://www.example.com/'
        index_links = {
            'about': {
                'href': index_uri + 'about',
                'title': 'A single link',
            },
            'alternate': [{
                'href': index_uri + 'alt/' + str(i),
                'name': 'alt_' + str(i)
            } for i in xrange(5)]
        }
        register_hal(index_uri, index_links)

        N = HN.HALNavigator(index_uri)
        assert isinstance(N['about'], HN.HALNavigator)
        assert isinstance(N['alternate'], list)
        for i, n in enumerate(N['alternate']):
            assert isinstance(n, HN.HALNavigator)
            assert n.uri == index_links['alternate'][i]['href']
        assert len(N['alternate']) == 5
예제 #30
0
def test_HALNavigator__relative_links():
    with httprettify():
        index_uri = 'http://www.example.com/'
        about_relative_uri = '/about/'
        about_full_uri = index_uri + 'about/'
        index_links = {'about': {'href': about_relative_uri}}
        about_links = {
            'alternate': {
                'href': 'alternate'
            },
            'index': {
                'href': './index'
            }
        }
        register_hal(index_uri, index_links)
        register_hal(about_full_uri, about_links)

        N = HN.HALNavigator(index_uri)
        assert N['about'].uri == 'http://www.example.com/about/'
        assert N['about', 'alternate'].uri == \
            'http://www.example.com/about/alternate'
        assert N['about']['index'].uri == 'http://www.example.com/about/index'