コード例 #1
0
ファイル: test_magic.py プロジェクト: kmatt/ipython-restmagic
def test_root_values_are_added_to_query(parse_rest_request, send):
    rest = RESTMagic()
    rest.root = RESTRequest(method='POST', url='http://example.org')
    parse_rest_request.return_value = RESTRequest(url='test')
    rest.rest('GET test')
    args = send.call_args[0]
    assert args[0] == RESTRequest(method='POST', url='http://example.org/test')
コード例 #2
0
    def rest(self, line, cell=''):
        """Run given HTTP query."""
        args = self.get_args(
            magic_arguments.parse_argstring(self.rest, line)
        )
        try:
            rest_request = parse_rest_request('\n'.join((
                ' '.join(args.query),
                expand_variables(cell, self.get_user_namespace()).rstrip('\n')
            )))
        except ParseError as ex:
            display_usage_example(magic='rest', error_text=str(ex),
                                  is_cell_magic=(cell != ''))
            return None

        sender = self.sender or RequestSender()
        root = self.root or RESTRequest()

        try:
            response = sender.send(
                RESTRequest('GET', 'https://') + root + rest_request,
                proxy=args.proxy,
                verify=not args.insecure,
                max_redirects=args.max_redirects,
                timeout=args.timeout,
            )
        except SSLError:
            self.showtraceback('Use `%rest --insecure` option to disable '
                               'SSL certificate verification.')
            return None
        except Exception:
            self.showtraceback('Request was not completed.')
            return None

        if args.verbose and not args.quiet:
            print(sender.dump())
        elif not args.quiet:
            try:
                if args.parser_expression:
                    display_dict(
                        ResponseParser(response=response,
                                       expression=remove_argument_quotes(args.parser_expression),
                                       content_subtype=args.parser).parse()
                    )
                else:
                    display_response(response)
            except UnknownSubtype:
                self.showtraceback("Use `%rest --parser` to specify which parser to use.")
            except Exception:
                self.showtraceback("Can't display the response.")
        return response
コード例 #3
0
def parse_rest_request(text):
    """Parse HTTP query.

    :param text: full HTTP query string
    :returns: RESTRequest with parsed values
    :raises: ParseError
    """
    pattern = re.compile(
        r"""
    ^\s*  # possible whitespaces at the beginning
    ((?P<method>\w+)\s+)?  # optional method
    (?P<url>\S+)
    ([ \t]+HTTP/\d+[.]?\d*)?  # optional protocol version identification
    """, re.VERBOSE | re.MULTILINE)
    match = re.match(pattern, text)
    if not match:
        raise ParseError('Usage error')
    # headers and body are separated by a blank line
    parts = re.split(r'\n[ \t]*\n', text[match.end():], 1)
    return RESTRequest(
        method=(match.group('method') or '').upper(),
        url=match.group('url'),
        headers=parse_rest_headers(parts[0]),
        body=parts[1] if len(parts) > 1 else '',
    )
コード例 #4
0
import pytest
from restmagic.request import RESTRequest


@pytest.mark.parametrize('a, b, expected', (
    (RESTRequest(), RESTRequest(), RESTRequest()),
    (RESTRequest(method='POST'), RESTRequest(), RESTRequest('POST')),
    (RESTRequest(method=''), RESTRequest('POST'), RESTRequest('POST')),
    (RESTRequest(url='test'), RESTRequest(), RESTRequest(url='test')),
    (RESTRequest(), RESTRequest(url='api/method'),
     RESTRequest(url='api/method')),
    (RESTRequest(url='https://x'), RESTRequest(url='http://y'),
     RESTRequest(url='http://y')),
    (RESTRequest(url='/'), RESTRequest(url='/'), RESTRequest(url='/')),
    (RESTRequest(), RESTRequest(url='/'), RESTRequest(url='/')),
    (RESTRequest(url='test'), RESTRequest(url='api/method'),
     RESTRequest(url='test/api/method')),
    (RESTRequest(headers={'a': '1'}), RESTRequest(headers={}),
     RESTRequest(headers={'a': '1'})),
    (RESTRequest(headers={
        'a': '1',
        'b': '2'
    }), RESTRequest(headers={'b': '100'}),
     RESTRequest(headers={
         'a': '1',
         'b': '100'
     })),
    (RESTRequest(), RESTRequest(body='test'), RESTRequest(body='test')),
    (RESTRequest(body='test'), RESTRequest(), RESTRequest()),
))
def test_requests_join(a, b, expected):
コード例 #5
0
ファイル: test_magic.py プロジェクト: kmatt/ipython-restmagic
def test_default_method_and_scheme_added_to_query(parse_rest_request, send):
    rest = RESTMagic()
    parse_rest_request.return_value = RESTRequest(url='test')
    rest.rest('test')
    args = send.call_args[0]
    assert args[0] == RESTRequest(method='GET', url='https://test')
コード例 #6
0
ファイル: test_magic.py プロジェクト: kmatt/ipython-restmagic
def parse_rest_request(mocker):
    return mocker.patch('restmagic.magic.parse_rest_request',
                        return_value=RESTRequest())
コード例 #7
0
ファイル: test_magic.py プロジェクト: kmatt/ipython-restmagic
def test_root_is_canceled(ip):
    rest = ip.find_magic('rest').__self__
    rest.root = RESTRequest(url='test')
    ip.run_line_magic('rest_root', '')
    assert rest.root is None
コード例 #8
0
ファイル: test_magic.py プロジェクト: kmatt/ipython-restmagic
def test_root_is_set(ip, parse_rest_request):
    rest = ip.find_magic('rest').__self__
    parse_rest_request.return_value = RESTRequest(url='test')
    assert rest.root is None
    ip.run_line_magic('rest_root', 'test')
    assert rest.root == RESTRequest(url='test')