def test_all_in(openapi3_content):
    raw_endpoints = search(openapi3_content, "paths")
    query = request_generator(openapi3_content)
    resolver = ref_resolver(openapi3_content)
    endpoints = transform_tree(raw_endpoints, resolver)

    for url, endpoint in endpoints.items():
        try:
            if "get" in endpoint:
                gen = query(url)
                res = next(gen)
                assert res is not None
            if "put" in endpoint:
                gen = query(url, method="put")
                res = next(gen)
                assert res is not None
            if "post" in endpoint:
                gen = query(url, method="post")
                res = next(gen)
                assert res is not None
            if "delete" in endpoint:
                gen = query(url, method="delete")
                res = next(gen)
                assert res is not None
        except Exception as ex:
            assert False, f"uncontrolled exception in {url}, {endpoint}, {ex}"
Esempio n. 2
0
def request_generator(open_api_data: dict, default_strategy: list = []):
    if not open_api_data or not isinstance(open_api_data, dict):
        raise ValueError("Not data supplied")
    if not default_strategy:
        from apicheck.core.generator.open_api_strategy import strategy
        default_strategy = strategy
    transformer = ref_resolver(open_api_data)

    def _endpoint_generator(query, ancestors=set([]), method="get"):
        # TODO: raise invalid query and item not found inside search
        if not query:
            raise ValueError("Invalid query")
        item = search(open_api_data, query, ancestors=ancestors)
        if not item or method not in item:
            raise ValueError("Item not found")
        # empty request to fill
        request = {"method": method, "path": query, "headers": []}
        # TODO: retrieve parameters
        if "parameters" in item:
            parameters = item["parameters"]
        else:
            parameters = None
        resolved = transform_tree(item, transformer)
        if method == "get":
            res = _get_gen(query, resolved, default_strategy, parameters)
        elif method == "put":
            res = _put_gen(query, resolved, default_strategy, parameters)
        elif method == "post":
            res = _post_gen(query, resolved, default_strategy, parameters)
        else:
            raise NotImplementedError("No way man")
        return res

    return _endpoint_generator
Esempio n. 3
0
def request_generator(open_api_data: dict,
                      default_strategy: list = []):
    if not open_api_data or not isinstance(open_api_data, dict):
        return fail(AbsentValue("Not openapi data supplied"))
    if not default_strategy:
        from apicheck.core.generator.open_api_strategy import strategy
        default_strategy = strategy
    transformer = ref_resolver(open_api_data)

    def _endpoint_generator(query, ancestors=set([]), method="get"):
        if not query:
            return AbsentValue("Invalid query")
        item = search(open_api_data, query, ancestors=ancestors)
        if not item or method not in item:
            return AbsentValue("Item not found")
        if "parameters" in item:
            parameters = item["parameters"]
        else:
            parameters = None
        resolved = transform_tree(item, transformer)
        if method == "get":
            res = _get_gen(query, resolved, default_strategy, parameters)
        elif method == "put":
            res = _put_gen(query, resolved, default_strategy, parameters)
        elif method == "post":
            res = _post_gen(query, resolved, default_strategy, parameters)
        else:
            res = _delete_gen(query, resolved, default_strategy, parameters)
        return res
    return _endpoint_generator
Esempio n. 4
0
async def send_to_proxy_from_definition(running_config: RunningConfig):
    openapi3_content: dict = await openapi3_from_db(running_config.api_id)

    session_user_agent = generate_user_agent()

    async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(
            verify_ssl=False)) as session:

        raw_endpoints = search(openapi3_content, "paths")
        query = request_generator(openapi3_content)
        resolver = ref_resolver(openapi3_content)
        endpoints = transform_tree(raw_endpoints, resolver)

        http_scheme, netloc, path, *_ = urlparse(running_config.api_url)

        host, port = split_netloc(netloc, http_scheme)

        for url, endpoint in endpoints.items():

            logger.info(f"Generating data for End Point: {url}")

            try:
                for method in ("get", "put", "post", "delete"):
                    if method in endpoint:
                        gen = query(url, method=method)
                        req: dict = next(gen)
                        break
                else:
                    raise APICheckException("Unknown method in url: ", url)

            except ValueError as ve:
                logger.error(f"cannot generate data: {ve} - {url}")

            url = f"{http_scheme}://{host}:{port}{path}{req['path']}"

            custom_headers = req["headers"]
            custom_headers["user-agent"] = session_user_agent

            fn_params = dict(url=url,
                             headers=custom_headers,
                             proxy=f"http://{running_config.proxy_ip}:"
                             f"{running_config.proxy_port}",
                             skip_auto_headers=("content-type", "user-agent"))

            try:
                fn_params["data"] = req["body"]
            except KeyError:
                fn_params["data"] = None

            fn_method = getattr(session, req["method"])

            async with fn_method(**fn_params) as response:
                resp = await response.text()
Esempio n. 5
0
def test_resolve_reference(openapi3_content):
    expected = {
        "description": "Error",
        "content": {
            "application/json": {
                "schema": {
                    "type": "object",
                    "properties": {
                        "errors": {
                            "type": "array",
                            "items": {
                                "type": "object",
                                "description": "An object for describing a "
                                               "single error that occurred "
                                               "during the processing of a "
                                               "request.\n",
                                "properties": {
                                    "reason": {
                                        "type": "string",
                                        "description": "What happened to "
                                                       "cause this error. In "
                                                       "most cases, this can "
                                                       "be fixed immediately "
                                                       "by changing the data "
                                                       "you sent in the "
                                                       "request, but in some "
                                                       "cases you will be "
                                                       "instructed to [open "
                                                       "a Support Ticket]("
                                                       "#operation/createTicket) or perform some other action before you can complete the request successfully.\n",
                                        "example": "fieldname must be a "
                                                   "valid value"
                                    },
                                    "field": {
                                        "type": "string",
                                        "description": "The field in the "
                                                       "request that caused "
                                                       "this error. This may "
                                                       "be a path, separated "
                                                       "by periods in the "
                                                       "case of nested "
                                                       "fields. In some "
                                                       "cases this may come "
                                                       "back as \"null\" if "
                                                       "the error is not "
                                                       "specific to any "
                                                       "single element of "
                                                       "the request.\n",
                                        "example": "fieldname"
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    res = search(openapi3_content, "default",
                 ancestors=set(["/account", "get", "responses"]))
    resolved = transform_tree(res, ref_resolver(openapi3_content))

    assert isinstance(resolved, dict)
    assert resolved == expected