How to use the tavern.util.exceptions function in tavern

To help you get started, we’ve selected a few tavern examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github taverntesting / tavern / tavern / testutils / jmesutils.py View on Github external
def validate_comparison(each_comparison):
    try:
        assert set(each_comparison.keys()) == {"jmespath", "operator", "expected"}
    except KeyError as e:
        raise_from(
            exceptions.BadSchemaError("Invalid keys given to JMES validation function"),
            e,
        )

    jmespath, _operator, expected = (
        each_comparison["jmespath"],
        each_comparison["operator"],
        each_comparison["expected"],
    )

    try:
        COMPARATORS[_operator]
    except KeyError as e:
        raise_from(exceptions.BadSchemaError("Invalid comparator given"), e)

    return jmespath, _operator, expected
github taverntesting / tavern / tests / unit / response / test_rest.py View on Github external
def test_incorrect_status_code(self, example_response, includes):
        """Test full verification + return saved values
        """
        r = RestResponse(Mock(), "Test 1", example_response, includes)

        class FakeResponse:
            headers = example_response["headers"]
            content = "test".encode("utf8")

            def json(self):
                return example_response["body"]

            status_code = 400

        with pytest.raises(exceptions.TestFailError):
            r.verify(FakeResponse())

        assert r.errors
github taverntesting / tavern / tests / unit / test_mqtt.py View on Github external
def test_unknown_fields(self, req, includes):
        """Unkown args should raise an error
        """
        req["fodokfowe"] = "Hello"

        with pytest.raises(exceptions.UnexpectedKeysError):
            MQTTRequest(Mock(), req, includes)
github taverntesting / tavern / tests / unit / test_request.py View on Github external
def test_cannot_send_data_and_json(self, req, includes):
        req["json"] = [1, 2, 3]
        req["data"] = [1, 2, 3]

        with pytest.raises(exceptions.BadSchemaError):
            get_request_args(req, includes)
github taverntesting / tavern / tavern / core.py View on Github external
def _resolve_test_stages(test_spec, available_stages):
    # Need to get a final list of stages in the tests (resolving refs)
    test_stages = []
    for raw_stage in test_spec["stages"]:
        stage = raw_stage
        if stage.get("type") == "ref":
            if "id" in stage:
                ref_id = stage["id"]
                if ref_id in available_stages:
                    # Make sure nothing downstream can change the globally
                    # defined stage. Just give the test a local copy.
                    stage = deepcopy(available_stages[ref_id])
                    logger.debug("found stage reference: %s", ref_id)
                else:
                    logger.error("Bad stage: unknown stage referenced: %s", ref_id)
                    raise exceptions.InvalidStageReferenceError(
                        "Unknown stage reference: {}".format(ref_id)
                    )
            else:
                logger.error("Bad stage: 'ref' type must specify 'id'")
                raise exceptions.BadSchemaError("'ref' stage type must specify 'id'")
        test_stages.append(stage)

    return test_stages
github taverntesting / tavern / tavern / _plugins / rest / request.py View on Github external
optional_with_default = {"verify": True, "stream": False}

    if "method" not in rspec:
        logger.debug("Using default GET method")
        rspec["method"] = "GET"

    content_keys = ["data", "json", "files"]

    in_request = [c for c in content_keys if c in rspec]
    if len(in_request) > 1:
        # Explicitly raise an error here
        # From requests docs:
        # Note, the json parameter is ignored if either data or files is passed.
        # However, we allow the data + files case, as requests handles it correctly
        if set(in_request) != {"data", "files"}:
            raise exceptions.BadSchemaError(
                "Can only specify one type of request data in HTTP request (tried to "
                "send {})".format(" and ".join(in_request))
            )

    headers = rspec.get("headers", {})
    has_content_header = "content-type" in [h.lower() for h in headers.keys()]

    if "files" in rspec:
        if has_content_header:
            logger.warning(
                "Tried to specify a content-type header while sending a file - this will be ignored"
            )
            rspec["headers"] = {
                i: j for i, j in headers.items() if i.lower() != "content-type"
            }
github taverntesting / tavern / tavern / plugins.py View on Github external
Raises:
        exceptions.DuplicateKeysError: More than one kind of request specified
        exceptions.MissingKeysError: No request type specified
    """

    plugins = load_plugins(test_block_config)

    keys = {}

    for p in plugins:
        keys[p.plugin.request_block_name] = p.plugin.request_type

    if len(set(keys) & set(stage)) > 1:
        logger.error("Can only specify 1 request type")
        raise exceptions.DuplicateKeysError
    elif not list(set(keys) & set(stage)):
        logger.error("Need to specify one of '%s'", keys.keys())
        raise exceptions.MissingKeysError

    # We've validated that 1 and only 1 is there, so just loop until the first
    # one is found
    for p in plugins:
        try:
            request_args = stage[p.plugin.request_block_name]
        except KeyError:
            pass
        else:
            session = sessions[p.name]
            request_class = p.plugin.request_type
            logger.debug(
                "Initialising request class for %s (%s)", p.name, request_class
github taverntesting / tavern / tests / unit / test_helpers.py View on Github external
def test_bad_format_string_multiple(self):
        """Multple format spec in string is disallowed"""
        with pytest.raises(exceptions.InvalidFormattedJsonError):
            format_keys(ForceIncludeToken("{a}{b}"), {"fd": "123"})