Code Monkey home page Code Monkey logo

http's Introduction

grappa logo

Build Status PyPI Coverage Status Documentation Status Stability Code Climate Python Versions Say Thanks

About

HTTP request/response assertion plugin for grappa. grappa-http extends grappa assertion operators with HTTP protocol testing.

To get started, take a look to the documentation, tutorial and examples.

Showcase

import pook
import requests
from grappa_http import should

# Activate the HTTP mock engine
pook.on()

# Register a sample mock
pook.get('server.org/foo?bar=baz', reply=200,
         response_headers={'Server': 'nginx'},
         response_json={'foo': 'bar'})

# Perform HTTP request
res = requests.get('http://server.org/foo?bar=baz')

# Test response status to be OK
res | should.be.ok
# Or alternatively using the status code
res | should.have.status(200)

# Test request URL
res | should.have.url.hostname('server.org')
res | should.have.url.port(80)
res | should.have.url.path('/foo')
res | should.have.url.query.params({'bar': 'baz'})

# Test response body MIME content type
res | should.have.content('json')

# Test response headers
(res | (should.have.header('Content-Type')
        .that.should.be.equal('application/json')))
res | should.have.header('Server').that.should.contain('nginx')

# Test response body
res | should.have.body.equal.to('{\n    "foo": "bar"\n}')
res | should.have.body.that.contains('foo')

# Test response body length
res | should.have.body.length.of(20)
res | should.have.body.length.higher.than(10)

# Test response JSON body
res | should.have.json.equal.to({'foo': 'bar'})
res | should.have.json.have.key('foo') > should.be.equal.to('bar')

# Validate response JSON bodies using JSONSchema
res | should.implement.jsonschema({
    '$schema': 'http://json-schema.org/draft-04/schema#',
    'title': 'Response JSON',
    'type': 'object',
    'required': ['foo'],
    'properties': {
        'foo': {
            'description': 'foo always means foo',
            'type': 'string'
        }
    }
})

Full-featured error report example:

Traceback (most recent call last):
  File "grappa-http/tests/http_test.py", line 38, in test_http_tutorial
    res | should.have.body.equal.to('{\n    "foo": "baa"\n}')
  File "grappa/grappa/test.py", line 208, in __ror__
    return self.__overload__(value)
  File "grappa/grappa/test.py", line 196, in __overload__
    return self.__call__(subject, overload=True)
  File "grappa/grappa/test.py", line 73, in __call__
    return self._trigger() if overload else Test(subject)
  File "grappa/grappa/test.py", line 113, in _trigger
    raise err
AssertionError: Oops! Something went wrong!

  The following assertion was not satisfied
    subject "{\n    "foo": "bar"\n}" should have body equal to "{\n    "foo": "baa"\n}"

  What we expected
    a response body data equal to:
        {
            "foo": "baa"
        }

  What we got instead
    a response body with data:
        {
            "foo": "bar"
        }

  Difference comparison
    >   {
    > -     "foo": "bar"
    > ?               ^
    > +     "foo": "baa"
    > ?               ^
    >   }

  Where
    File "grappa-http/tests/http_test.py", line 38, in test_http_tutorial

    30|       res | should.have.content('json')
    31|
    32|       # Test response headers
    33|       (res | (should.have.header('Content-Type')
    34|               .that.should.be.equal('application/json')))
    35|       res | should.have.header('Server').that.should.contain('nginx')
    36|
    37|       # Test response body
    38| >     res | should.have.body.equal.to('{\n    "foo": "baa"\n}')
    39|       res | should.have.body.that.contains('foo')
    40|
    41|       # Test response body length
    42|       res | should.have.body.length.of(20)
    43|       res | should.have.body.length.higher.than(10)
    44|
    45|       # Test response JSON body

Features

  • Full-featured HTTP response assertions.
  • Supports any protocol primitive assertions.
  • First-class support for JSON body assertion.
  • Built-in JSONSchema validation.
  • Full-features request URL validation.
  • Featured regular expression based assertion.
  • Works with requests and aiohttp HTTP clients.
  • Friendly and detailed assertion error reporting with body diff comparisons.
  • Provides both expect and should assertion styles.
  • Testing framework agnostic. Works with unittest, nosetests, pytest, behave...
  • Works with Python 2.6+, 3+, PyPy and possibly other Python implementations.

Supported HTTP clients

Installation

Using pip package manager:

pip install --upgrade grappa-http

Or install the latest sources from Github:

pip install -e git+git://github.com/grappa-py/http.git#egg=grappa

http's People

Contributors

h2non avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

http's Issues

API design

res | should.be.ok
res | should.be.error
res | should.be.bad_request
res | should.have.status(200)
res | should.be.xml
res | should.be.json
res | should.be.content('json')
res | should.be.content('application/json')
res | should.have.header('Server')
res | should.have.header.present('Server')

Dictionary keys by variable is throwing exception

Trying to assert a dictionary to not contain keys from a list of keys
data | should.not_have.key(key)

is throwing AssertionError
`test_ddt.py:19: in _runtestmodule
matchrsi(cfg.result[0], data)
......\modules\matchrsi.py:32: in matchrsi
data | should.not_have.key(key)
C:\Program Files\Python37\lib\site-packages\grappa\test.py:208: in ror
return self.overload(value)
C:\Program Files\Python37\lib\site-packages\grappa\test.py:196: in overload
return self.call(subject, overload=True)
C:\Program Files\Python37\lib\site-packages\grappa\test.py:73: in call
return self._trigger() if overload else Test(subject)


self = <grappa.test.Test object at 0x0000026784443C88>

def _trigger(self):
    """
    Trigger assertions in the current test engine.

    Raises:
        AssertionError: in case of assertion error.
        Exception: in case of any other assertion error.
    """
    log.debug('[test] trigger with context: {}'.format(self._ctx))

    try:
        err = self._engine.run(self._ctx)
    except Exception as _err:
        err = _err
    finally:
        # Important: reset engine state to defaults
        self._engine.reset()
        self._root._engine.reset()

    # If error is present, raise it!
    if err:
      raise err

E AssertionError: Oops! Something went wrong!
E
E The following assertion was not satisfied
E subject "{'id': 'de83e969-504 ..." should not have key "restrictionReason"
E
E Where
E File "D:\workspace\isswtest\issw-functest\modules\matchrsi.py", line 32, in matchrsi
E
E 24| empty_attr = [k for k, v in rsi.Attributes.items() if v is None]
E 25| nonempty_attr = [k for k, v in rsi.Attributes.items() if v is not None]
E 26| else:
E 27| empty_attr = nonempty_attr = []
E 28|
E 29| if rsi.object_exist:
E 30| is_xobject(data)
E 31| for key in empty_attr:
E 32| > data | should.not_have.key(key)
E 33| list(data.keys()) | should.do_not.contain(key)
E 34|
E 35| for key in nonempty_attr:
E 36| data | should.have.key(key)
E 37| data.get(key) | should.be.equal.to(rsi.Attributes.get(key))
E 38| else:
E 39| # RSI Object does not exist

C:\Program Files\Python37\lib\site-packages\grappa\test.py:113: AssertionError`

Alternatively using
list(data.keys()) | should.do_not.contain(key)
is working though

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.