コード例 #1
0
def status(obj, format, query, time_frame, api_id):
    """
This command displays API status

\b
Status Field:
- `status`: string 
- `hits`: numerate
- `percent`: string
    """
    api_client = obj['api_client']

    try:
        status_values = api_client.status(api_id,
                                          parse(time_frame)).json()['values']
    except TypeError:
        raise GraviteeioError("Unsupported type for time frame")

    to_return = []
    total = 0
    for key, value in status_values.items():
        status_str = "{}xx".format(key[0:1])
        to_return.append({
            "status": status_str,
            "hits": value,
            "percent": value * 100
        })
        total += value

    if total > 0:
        for status in to_return:
            status["percent"] = round(status["percent"] / total, 2)

    if format == "hbar":
        query = "reverse(@)[].{Status: status, Percent: percent}"
    # start_time = time.time()
    try:
        status_filtered = jmespath.search(query, to_return)

        header = None
        if len(status_filtered) > 0 and type(status_filtered[0]) is dict:
            header = status_filtered[0].keys()

        outputFormat = OutputFormat.value_of(format)
        gio.echo(status_filtered, outputFormat, header)

    except exceptions.JMESPathError as jmespatherr:
        raise GraviteeioError(str(jmespatherr))
    except Exception as err:
        raise GraviteeioError("to print {} with the format {}".format(
            status_filtered, format))
コード例 #2
0
def test_output_dict_table(capsys):
    data = {"param1": "value1","param2": "value2"}
    gio.echo(data, OutputFormat.value_of("table"), ["Header","Header"])
    captured = capsys.readouterr()
    assert captured.out == " Header  Header \n----------------\n param1  value1 \n param2  value2 \n"
コード例 #3
0
def test_output_dict_tsv_apis_ps(capsys):
    
    gio.echo(APIS_PS_DATA, OutputFormat.value_of("tsv"), ["id","Name","Tags","Synchronized","Status"])
    captured = capsys.readouterr()
    assert captured.out == "id\tName\tTags\tSynchronized\tStatus\n339ac63d-a072-4234-9ac6-3da0726234be\tGravitee.io features\t[]\tTrue\tstarted\tNone\n"
コード例 #4
0
def test_output_dict_tsv_apis_ps_with_no_data(capsys):
    
    gio.echo([], OutputFormat.value_of("tsv"), [])
    captured = capsys.readouterr()
    assert captured.out == "\t\n"
コード例 #5
0
def test_output_dict_table_apis_ps(capsys):
    gio.echo(APIS_PS_DATA_table, OutputFormat.value_of("table"), ["id","Name","Tags","Synchronized","Status"])
    captured = capsys.readouterr()
    assert captured.out == " id                                    Name                  Tags    Synchronized  Status  \n-------------------------------------------------------------------------------------------\n 339ac63d-a072-4234-9ac6-3da0726234be  Gravitee.io features  <none>  V             STARTED \n"
コード例 #6
0
def test_output_list_tsv(capsys):
    data = ['demo', 'qualif', 'prod']
    gio.echo(data, OutputFormat.value_of("tsv"), ["Env"])
    captured = capsys.readouterr()
    assert captured.out == "Env\ndemo\nqualif\nprod\n"
コード例 #7
0
def test_output_dict_tsv(capsys):
    data = {"param1": "value1","param2": "value2"}
    gio.echo(data, OutputFormat.value_of("tsv"), ["Header1","Header2"])
    captured = capsys.readouterr()
    assert captured.out == "Header1\tHeader2\nparam1\tvalue1\nparam2\tvalue2\n"
コード例 #8
0
def ps(obj, format, query):
    """
This command displays the list of APIs

\b
API Field:

- `id`: string 
- `name`: string
- `version`: string
- `description`: string
- `visibility`: enum `public`, `private``
- `state`: enum `initialized`, `stopped`, `started`, `closed`
- `labels`: string array
- `manageable`: boolean
- `numberOfRatings`: num
- `tags` :string array
- `created_at`: unix time
- `updated_at:` unix time
- `owner`:
    - `id`: string
    - `displayName`: string
- `picture_url`: string url
- `virtual_hosts`: array
    - `host`: string
    - `path`: string
    - `overrideEntrypoint`: boolean
- `lifecycle_state`: enum `created`, `published`, `unpublished`, `deprecated`, `archived`
- `workflow_state`: enum `draft`, ìn_review`, `request_for_changes`, `review_ok`
- `is_synchronized`: boolean
    """
    async def get_apis():
        client = ApiClientAsync(obj['config'])
        apis = await client.get_apis_with_state()
        return apis

    try:
        loop = asyncio.get_event_loop()
        apis = loop.run_until_complete(get_apis())

        # print("{}".format(apis))
    except Exception:
        raise GraviteeioError("to get apis")

    if not apis and len(apis) <= 0:
        click.echo("No Api(s) found ")

    if not query:
        if FormatType.table == FormatType.value_of(format):
            query = "[].{Id: id, Name: name, Tags: style_tags(tags), Synchronized: style_synchronized(is_synchronized), Status: style_state(state), Workflow: style_workflow_state(workflow_state)}"
        else:
            query = "[].{Id: id, Name: name, Tags: tags, Synchronized: is_synchronized, Status: state, Workflow: workflow_state}"

    class CustomFunctions(functions.Functions):
        #options= jmespath.Options()
        @functions.signature({'types': ['string']})
        def _func_style_state(self, state):
            state_color = 'red'
            if state == 'started':
                state_color = 'green'
            return click.style(state.upper(), fg=state_color)

        @functions.signature({'types': []})
        def _func_style_workflow_state(self, workflow_state):
            if workflow_state:
                return click.style(workflow_state.upper(), fg='blue')
            else:
                return '-'

        @functions.signature({'types': []})
        def _func_style_tags(self, tags):
            if tags:
                return ', '.join(tags)
            else:
                return "<none>"

        @functions.signature({'types': []})
        def _func_style_synchronized(self, state):
            if state:
                return click.style("V", fg='green')
            else:
                return click.style("X", fg='yellow')

    try:
        apis_filtered = jmespath.search(
            query, apis, jmespath.Options(custom_functions=CustomFunctions()))
        header = None
        if len(apis_filtered) > 0 and type(apis_filtered[0]) is dict:
            header = apis_filtered[0].keys()

        # print("{}".format(apis_filtered))

        outputFormat = OutputFormat.value_of(format)
        if format is "table" and header:
            # TODO: Dynamic table style
            justify_columns = {}
            for x in range(2, len(header)):
                justify_columns[x] = 'center'
            #justify_columns = {3: 'center', 4: 'center', 5: 'center'}
            outputFormat.style = justify_columns
        #print("{}".format(apis_filtered))
        gio.echo(apis_filtered, outputFormat, header)
    except exceptions.JMESPathError as jmespatherr:
        raise GraviteeioError(str(jmespatherr))
    except Exception:
        raise GraviteeioError("to print {} with the format {}".format(
            apis_filtered, format))