Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions polyapi/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
from .config import clear_config, set_api_key_and_url
from .generate import generate, clear
from .function_cli import function_add_or_update
from .rendered_spec import save_rendered_specs
from .rendered_spec import get_and_update_rendered_spec


CLI_COMMANDS = ["setup", "generate", "function", "clear", "help", "save_rendered_specs"]
CLI_COMMANDS = ["setup", "generate", "function", "clear", "help", "update_rendered_spec"]

CLIENT_DESC = """Commands
python -m polyapi setup Setup your Poly connection
Expand All @@ -18,7 +18,7 @@
"""


def execute_from_cli():
def execute_from_cli() -> None:
parser = argparse.ArgumentParser(
prog="python -m polyapi", description=CLIENT_DESC, formatter_class=argparse.RawTextHelpFormatter
)
Expand All @@ -43,8 +43,14 @@ def execute_from_cli():
elif command == "setup":
clear_config()
generate()
elif command == "save_rendered_specs":
save_rendered_specs()
elif command == "update_rendered_spec":
assert len(args.subcommands) == 2
updated = get_and_update_rendered_spec(args.subcommands[0], args.subcommands[1])
if updated:
print("Updated rendered spec!")
else:
print("Failed to update rendered spec!")
exit(1)
elif command == "clear":
print("Clearing the generated library...")
clear()
Expand Down
29 changes: 28 additions & 1 deletion polyapi/rendered_spec.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
from typing import Dict
from typing import Dict, Optional

import requests
from polyapi.config import get_api_key_and_url
from polyapi.generate import read_cached_specs, render_spec
from polyapi.execute import execute_post
from polyapi.typedefs import SpecificationDto
Expand All @@ -19,11 +22,35 @@ def update_rendered_spec(spec: SpecificationDto):
else:
raise NotImplementedError("todo")

# use super key on develop-k8s here!
resp = execute_post("/functions/rendered-specs", data)
assert resp.status_code == 201, (resp.text, resp.status_code)
# this needs to run with something like `kn func run...`


def _get_spec(api_key: str, spec_id: str) -> Optional[SpecificationDto]:
_, base_url = get_api_key_and_url()
url = f"{base_url}/specs"
headers = {"Authorization": f"Bearer {api_key}"}
resp = requests.get(url, headers=headers)
if resp.status_code == 200:
specs = resp.json()
for spec in specs:
if spec['id'] == spec_id:
return spec
return None
else:
raise NotImplementedError(resp.content)


def get_and_update_rendered_spec(api_key: str, spec_id: str) -> bool:
spec = _get_spec(api_key, spec_id)
if spec:
update_rendered_spec(spec)
return True
return False


def save_rendered_specs() -> None:
specs = read_cached_specs()
# right now we just support rendered apiFunctions
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ requires = ["setuptools>=61.2", "wheel"]

[project]
name = "polyapi-python"
version = "0.2.5.dev3"
version = "0.2.5.dev4"
description = "The Python Client for PolyAPI, the IPaaS by Developers for Developers"
authors = [{ name = "Dan Fellin", email = "[email protected]" }]
dependencies = [
Expand Down
52 changes: 52 additions & 0 deletions tests/test_rendered_spec.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import unittest
from mock import patch, Mock

from polyapi.rendered_spec import get_and_update_rendered_spec

GET_PRODUCTS_COUNT = {
"id": "8f7d24b0-4a29-40c0-9091",
"type": "serverFunction",
"context": "test",
"name": "getProductsCount111",
"description": "An API call to retrieve the count of products in the product list.",
"requirements": ["snabbdom"],
"function": {
"arguments": [
{
"name": "products",
"required": False,
"type": {
"kind": "array",
"items": {"kind": "primitive", "type": "string"},
},
}
],
"returnType": {"kind": "plain", "value": "number"},
"synchronous": True,
},
"code": "",
"language": "javascript",
"visibilityMetadata": {"visibility": "ENVIRONMENT"},
}


class T(unittest.TestCase):
@patch("polyapi.rendered_spec._get_spec")
def test_get_and_update_rendered_spec_fail(self, _get_spec):
""" pass in a bad id to update and make sure it returns False
"""
_get_spec.return_value = None
updated = get_and_update_rendered_spec("abc", "123")
self.assertEqual(_get_spec.call_count, 1)
self.assertFalse(updated)

@patch("polyapi.rendered_spec.execute_post")
@patch("polyapi.rendered_spec._get_spec")
def test_get_and_update_rendered_spec_success(self, _get_spec, execute_post):
""" pass in a bad id to update and make sure it returns False
"""
_get_spec.return_value = GET_PRODUCTS_COUNT
execute_post.return_value = Mock(status_code=201, text="Created")
updated = get_and_update_rendered_spec("abc", "123")
self.assertEqual(_get_spec.call_count, 1)
self.assertTrue(updated)
11 changes: 7 additions & 4 deletions tests/test_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
class T(unittest.TestCase):
def test_fix_titles(self):
# schema = json.loads(SCHEMA)
schema = {"$schema": "https://json-schema.org/draft-06/schema#"}
a, b = generate_schema_types(schema)
# shouldnt error with unknown dialect
self.assertTrue(b)
schema = {"$schema": "http://json-schema.org/draft-06/schema#"}
try:
a, b = generate_schema_types(schema)
except AssertionError:
pass

# should not throw with unknown dialect error