Example #1
0
def test_cli_history(cli):
    set_response(Document('http://1.com'))
    result = cli('get', 'http://mock')

    set_response(Document('http://2.com'))
    result = cli('get', 'http://mock')

    result = cli('history', 'show')
    assert result.output == ('History\n'
                             '[*] <Document "http://2.com">\n'
                             '[ ] <Document "http://1.com">\n')

    set_response(Document('http://1.com'))
    result = cli('history', 'back')
    result = cli('history', 'show')
    assert result.output == ('History\n'
                             '[ ] <Document "http://2.com">\n'
                             '[*] <Document "http://1.com">\n')
    result = cli('show')
    assert result.output == '<Document "http://1.com">\n'

    set_response(Document('http://2.com'))
    result = cli('history', 'forward')
    result = cli('history', 'show')
    assert result.output == ('History\n'
                             '[*] <Document "http://2.com">\n'
                             '[ ] <Document "http://1.com">\n')
    result = cli('show')
    assert result.output == '<Document "http://2.com">\n'
Example #2
0
def test_single_history():
    doc = Document('http://example.com', 'Example')
    history = History([doc])
    assert history.is_at_most_recent
    assert history.is_at_oldest
    assert history.current == doc
    assert list(history.get_items()) == [(True, doc)]
    assert load_history(dump_history(history)) == history

    with pytest.raises(ValueError):
        history.back()
    with pytest.raises(ValueError):
        history.forward()

    # Adding same document does not change history.
    new_doc = Document('http://example.com', 'Example')
    new_history = history.add(new_doc)
    assert list(new_history.get_items()) == [(True, doc)]

    # Adding same URL, different title changes existing item.
    new_doc = Document('http://example.com', 'New')
    new_history = history.add(new_doc)
    assert list(new_history.get_items()) == [(True, new_doc)]

    # Adding different document changes history.
    new_doc = Document('http://other.com', 'Example')
    new_history = history.add(new_doc)
    assert list(new_history.get_items()) == [(True, new_doc), (False, doc)]
Example #3
0
def doc():
    return Document(title='original',
                    content={
                        'nested':
                        Document(
                            content={
                                'follow':
                                Link(url='mock://example.com', action='get'),
                                'action':
                                Link(url='mock://example.com',
                                     action='post',
                                     transform='inplace',
                                     fields=['foo']),
                                'create':
                                Link(url='mock://example.com',
                                     action='post',
                                     fields=['foo']),
                                'update':
                                Link(url='mock://example.com',
                                     action='put',
                                     fields=['foo']),
                                'delete':
                                Link(url='mock://example.com', action='delete')
                            })
                    })
Example #4
0
def test_adding_from_midpoint():
    """
    Adding an item from midpoint in history removes any forwards items.
    """
    first = Document('http://first.com', 'First')
    second = Document('http://second.com', 'Second')
    history = History([second, first], idx=1)

    third = Document('http://third.com', 'Third')
    new = history.add(third)
    assert list(new.get_items()) == [(True, third), (False, first)]
Example #5
0
def test_navigating_forward():
    first = Document('http://first.com', 'First')
    second = Document('http://second.com', 'Second')
    history = History([second, first], idx=1)
    assert not history.is_at_most_recent
    assert history.is_at_oldest
    assert history.current == first
    assert list(history.get_items()) == [(False, second), (True, first)]

    doc, history = history.forward()
    assert doc == second
    assert list(history.get_items()) == [(True, second), (False, first)]
Example #6
0
def test_cli_reload(cli):
    result = cli('reload')
    assert result.output == 'No current document. Use `coreapi get` to fetch a document first.\n'
    assert result.exit_code == 1

    set_response(Document('http://example.com', 'Example'))
    result = cli('get', 'http://mock')

    set_response(Document('http://example.com', 'New'))
    cli('reload')
    result = cli('show')
    assert result.output == '<New "http://example.com">\n'
Example #7
0
    def transition(self, link, decoders, params=None, link_ancestors=None):
        if link.action == 'get':
            document = Document(title='new', content={'new': 123})
        elif link.action in ('put', 'post'):
            if params is None:
                params = {}
            document = Document(title='new',
                                content={
                                    'new': 123,
                                    'foo': params.get('foo')
                                })
        else:
            document = None

        return _handle_inplace_replacements(document, link, link_ancestors)
def test_document_urls():
    doc = Document(url='http://example.org/',
                   title='Example',
                   content={
                       'a': Document(title='Full',
                                     url='http://example.com/123'),
                       'b': Document(title='Path',
                                     url='http://example.org/123'),
                       'c': Document(title='None', url='http://example.org/')
                   })
    assert str(doc) == _dedent("""
        <Example "http://example.org/">
            a: <Full "http://example.com/123">
            b: <Path "http://example.org/123">
            c: <None "http://example.org/">
    """)
def test_newline_str():
    doc = Document(content={'foo': '1\n2'})
    assert str(doc) == _dedent("""
        <Document "">
            foo: "1
                  2"
    """)
Example #10
0
def test_cli_get(cli):
    set_response(Document('http://example.com', 'Example'))
    result = cli('get', 'http://mock')
    assert result.output == '<Example "http://example.com">\n'

    result = cli('show')
    assert result.output == '<Example "http://example.com">\n'
def test_html_document_rendering():
    doc = Document(content={'string': 'abc', 'int': 123, 'bool': True})
    content = HTMLCodec().dump(doc)
    assert 'coreapi-document' in content
    assert '<span>abc</span>' in content
    assert '<code>123</code>' in content
    assert '<code>true</code>' in content
Example #12
0
def test_cli_clear(cli):
    set_response(Document('http://example.com', 'Example'))
    result = cli('get', 'http://mock')

    cli('clear')
    result = cli('show')
    assert result.output == 'No current document. Use `coreapi get` to fetch a document first.\n'
    assert result.exit_code == 1
Example #13
0
def load_history(bytestring):
    history_data = json.loads(bytestring.decode('utf-8'))
    items = [
        Document(item['url'], item['title']) for item in history_data['items']
    ]
    idx = history_data['idx']
    max_items = history_data['max_items']
    return History(items=items, idx=idx, max_items=max_items)
Example #14
0
 def to_representation(self, instance):
     data = super(CoreAPIDocumentSerializer, self).to_representation(instance)
     try:
         url = data.pop('url')
     except KeyError:
         raise APIException('A \'url\' field is required to serialize as a Document')
     return Document(
         title=self.get_title(instance),
         url=url,
         content=data,
     )
Example #15
0
def get_notes():
    """
    Return the top level Document object, containing all the note instances.
    """
    return Document(
        url='/',
        title='Notes',
        content={
            'notes':
            [get_note(identifier) for identifier in reversed(notes.keys())],
            'add_note':
            Link(action='post',
                 fields=[Field(name='description', required=True)])
        })
Example #16
0
 def test_mocking(self):
     content = {
         'test': {
             'post_data':
             Link(url='/post_data/',
                  action='post',
                  fields=[Field('data', location='body')]),
         }
     }
     schema = Document(title='test', content=content)
     mock.add(schema, ['test', 'post_data'], {"a": 1})
     client = DjangoCoreAPIClient()
     doc = client.action(schema, ['test', 'post_data'],
                         params={'data': {
                             'test': 'cat'
                         }})
     self.assertEqual(doc, {"a": 1})
Example #17
0
    def test_post_data(self):
        content = {
            'test': {
                'post_data':
                Link(url='/post_data/',
                     action='post',
                     fields=[Field('data', location='body')]),
            }
        }
        schema = Document(title='test', content=content)

        client = DjangoCoreAPIClient()
        doc = client.action(schema, ['test', 'post_data'],
                            params={'data': {
                                'test': 'cat'
                            }})
        self.assertIsNotNone(doc)
Example #18
0
def test_empty_history():
    history = History()
    assert history.is_at_most_recent
    assert history.is_at_oldest
    assert history.current is None
    assert list(history.get_items()) == []
    assert load_history(dump_history(history)) == history

    with pytest.raises(ValueError):
        history.back()
    with pytest.raises(ValueError):
        history.forward()

    # Adding new document changes history.
    new_doc = Document('http://example.com', 'Example')
    new_history = history.add(new_doc)
    assert list(new_history.get_items()) == [(True, new_doc)]
Example #19
0
def test_cli_bookmarks(cli):
    set_response(Document('http://example.com', 'Example'))
    cli('get', 'http://example.com')

    result = cli('bookmarks', 'add', 'example')
    assert result.output == 'Added bookmark\nexample\n'

    result = cli('bookmarks', 'show')
    assert result.output == 'Bookmarks\nexample <Example "http://example.com">\n'

    result = cli('bookmarks', 'get', 'example')
    assert result.output == '<Example "http://example.com">\n'

    result = cli('bookmarks', 'remove', 'example')
    assert result.output == 'Removed bookmark\nexample\n'

    result = cli('bookmarks', 'show')
    assert result.output == 'Bookmarks\n'
Example #20
0
def get_note(identifier):
    """
    Return a Document object for a single note instance.
    """
    note = notes[identifier]
    return Document(
        url='/' + identifier,
        title='Note',
        content={
            'description':
            note['description'],
            'complete':
            note['complete'],
            'edit':
            Link(action='put',
                 fields=[Field(name='description'),
                         Field(name='complete')]),
            'delete':
            Link(action='delete')
        })
Example #21
0
    def add(self, doc):
        if not isinstance(doc, Document):
            raise ValueError('Argument must be a Document instance.')

        new = Document(doc.url, doc.title)
        current = self.current

        # Remove any forward history past the current item.
        items = self._items[self._idx:]

        # Add the new reference if required.
        if current == new:
            pass
        elif (current is not None) and (current.url == new.url):
            items = [new] + items[1:]
        else:
            items = [new] + items

        # Truncate the history if we've reached the maximum number of items.
        items = items[:self.max_items]
        return History(items, max_items=self.max_items)
Example #22
0
def parse_spore_description(data, base_url=None):
    schema_url = base_url if base_url is not None else data.get('base_url')
    if 'meta' in data and 'documentation' in data.get('meta'):
        description = data['meta']['documentation']
    else:
        description = ''

    spore_methods = data.get('methods')
    content = {}

    for method in spore_methods.items():
        action, keys, link = _get_link_from_method(method)

        base_dict = content
        for key in keys:
            base_dict = base_dict.setdefault(key, {})
        base_dict[action] = link

    return Document(title=data.get('name'),
                    url=schema_url,
                    description=description,
                    content=content,
                    media_type='application/sporeapi+json')
Example #23
0
def doc():
    return Document(url='http://example.org',
                    title='Example',
                    content={
                        'integer':
                        123,
                        'dict': {
                            'key': 'value'
                        },
                        'list': [1, 2, 3],
                        'link':
                        Link(url='/',
                             action='post',
                             transform='inplace',
                             fields=[
                                 'optional',
                                 Field('required',
                                       required=True,
                                       location='path')
                             ]),
                        'nested': {
                            'child': Link(url='/123')
                        }
                    })
Example #24
0
def document(request):
    return Response(Document(title='Test Document', url='/'))
Example #25
0
def post_data(request):
    if request.data.get('test') != 'cat':
        raise Exception('Missing post data')
    return Response(Document(title='Test Document', url='/'))
Example #26
0
def headers(request):
    if not request.META.get('HTTP_AUTHORIZATION'):
        raise Exception('Missing header')
    return Response(Document(title='Test Document', url='/'))
Example #27
0
 def mockreturn(self, request):
     codec = CoreJSONCodec()
     body = force_text(request.body)
     content = codec.encode(Document(content={'data': json.loads(body)}))
     return MockResponse(content)
Example #28
0
def test_invalid_arguments():
    with pytest.raises(ValueError):
        History([None, Document('http://example.com')])

    with pytest.raises(ValueError):
        History().add(None)
Example #29
0
def test_dotted_path_notation_with_invalid_array_lookup():
    doc = Document(content={'rows': [Document(content={'edit': Link()})]})
    keys = coerce_key_types(doc, ['rows', 'zero', 'edit'])
    assert keys == ['rows', 'zero', 'edit']
Example #30
0
def test_dotted_path_notation_with_invalid_key():
    doc = Document(content={'rows': [Document(content={'edit': Link()})]})
    keys = coerce_key_types(doc, ['dummy', '0', 'edit'])
    assert keys == ['dummy', '0', 'edit']