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}"
예제 #2
0
def test_list_http_methods(openapi3_content):
    methods = ["get", "put", "post", "patch", "delete"]
    res = {
        k: v
        for k, v in search(openapi3_content, "/account").items()
        if k in methods
    }

    assert isinstance(res, dict)
    assert set(list(res.keys())) <= set(methods)
예제 #3
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()
예제 #4
0
def test_strange_parameters(openapi3_content):
    url = "/linode/instances/{linodeId}/disks"
    current = search(openapi3_content, url)
    query = request_generator(openapi3_content)
    try:
        if "post" in current:
            gen = query(url, method="post")
            res = next(gen)
            assert res is not None
    except ValueError as ve:
        print("cannot generate data", ve)
    except Exception as ex:
        assert False, f"uncontrolled exception in, {ex}"
예제 #5
0
def test_no_struct_schema(openapi3_content):
    current = search(openapi3_content, "/linode/instances")
    query = request_generator(openapi3_content)
    try:
        if "get" in current:
            gen = query("/linode/instances")
            res = next(gen)
            assert res is not None
        if "post" in current:
            gen = query("/linode/instances", method="post")
            res = next(gen)
            assert res is not None
    except ValueError as ve:
        print("cannot generate data", ve)
    except Exception as ex:
        assert False, f"uncontrolled exception in, {ex}"
예제 #6
0
 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
예제 #7
0
 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
예제 #8
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
예제 #9
0
def test_listing_endpoints(openapi3_content):
    res = list(search(openapi3_content, "paths").keys())

    assert isinstance(res, list)
    assert len(res) > 0
    assert isinstance(res[0], str)