Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

check-node-fixtures: Compare python/openapi schemas.

Steve Howell73e7f7edec65
diff --git a/tools/check-node-fixtures b/tools/check-node-fixtures
index d0dc8549d67..f4ca629678a 100755
--- a/tools/check-node-fixtures
+++ b/tools/check-node-fixtures
@@ -1,5 +1,6 @@
#!/usr/bin/env python3
import argparse
+import difflib
import os
import subprocess
import sys
@@ -41,7 +42,15 @@ os.environ["DJANGO_SETTINGS_MODULE"] = "zproject.test_settings"
django.setup()
from zerver.lib import event_schema
-from zerver.lib.data_types import make_checker
+from zerver.lib.data_types import ( # force vertical
+ DictType,
+ EnumType,
+ ListType,
+ UnionType,
+ make_checker,
+ schema,
+)
+from zerver.openapi.openapi import openapi_spec
SKIP_LIST = [
# The event_schema checker for user_status is overly strict.
@@ -51,6 +60,25 @@ SKIP_LIST = [
]
+EXEMPT_OPENAPI_NAMES = [
+ # openapi does a nicer union
+ "realm_user_update_event",
+ # message_retention_days
+ "default_stream_groups_event",
+ "default_streams_event",
+ "stream_delete_event",
+ "subscription_add_event",
+ # bots
+ "realm_bot_add_event",
+ "realm_bot_update_event",
+ # users field missing
+ "update_display_settings_event",
+ "update_global_notifications_event",
+ # Additional keys(push_users_notify) due to bug in API.
+ "message_event",
+]
+
+
def get_event_checker(
event: Dict[str, Any]
) -> Optional[Callable[[str, Dict[str, Any]], None]]:
@@ -101,6 +129,89 @@ def verify_fixtures_are_sorted(names: List[str]) -> None:
)
+def from_openapi(node: Dict[str, Any]) -> Any:
+ if "oneOf" in node:
+ return UnionType([from_openapi(n) for n in node["oneOf"]])
+
+ if node["type"] == "object":
+ if "additionalProperties" in node:
+ # this might be a glitch in our current spec? or
+ # maybe I just understand it yet
+ if isinstance(node["additionalProperties"], dict):
+ return from_openapi(node["additionalProperties"])
+
+ if "properties" not in node:
+ return dict
+
+ required_keys = []
+ for key, sub_node in node["properties"].items():
+ required_keys.append((key, from_openapi(sub_node)))
+ return DictType(required_keys)
+
+ if node["type"] == "boolean":
+ return bool
+
+ if node["type"] == "integer":
+ if "enum" in node:
+ return EnumType(node["enum"])
+ return int
+
+ if node["type"] == "number":
+ return float
+
+ if node["type"] == "string":
+ if "enum" in node:
+ return EnumType(node["enum"])
+ return str
+
+ if node["type"] == "array":
+ return ListType(from_openapi(node["items"]))
+
+ raise AssertionError("cannot handle node")
+
+
+def validate_openapi() -> None:
+ node = openapi_spec.openapi()["paths"]["/events"]["get"]["responses"]["200"][
+ "content"
+ ]["application/json"]["schema"]["properties"]["events"]["items"]["oneOf"]
+
+ for sub_node in node:
+ name = sub_node["properties"]["type"]["enum"][0]
+ for key in ["op", "operation"]:
+ if key in sub_node["properties"]:
+ name += "_" + sub_node["properties"][key]["enum"][0]
+
+ name += "_event"
+
+ if not hasattr(event_schema, name):
+ print("NEED SCHEMA to match openapi", name)
+ continue
+
+ openapi_type = from_openapi(sub_node)
+ openapi_schema = schema(name, openapi_type)
+
+ py_type = getattr(event_schema, name)
+ py_schema = schema(name, py_type)
+
+ if name in EXEMPT_OPENAPI_NAMES:
+ if openapi_schema == py_schema:
+ raise AssertionError(f"unnecessary exemption for {name}")
+ continue
+
+ if openapi_schema != py_schema:
+ print(f"py\n{py_schema}\n")
+ print(f"openapi\n{openapi_schema}\n")
+
+ for line in difflib.unified_diff(
+ py_schema.split("\n"),
+ openapi_schema.split("\n"),
+ fromfile="py",
+ tofile="openapi",
+ ):
+ print(line)
+ raise AssertionError("openapi schemas disagree")
+
+
def run() -> None:
fixtures = read_fixtures()
verify_fixtures_are_sorted(list(fixtures.keys()))
@@ -109,6 +220,7 @@ def run() -> None:
print(f"skip {name}")
continue
check_event(name, event)
+ validate_openapi()
if __name__ == "__main__":
diff --git a/zerver/lib/data_types.py b/zerver/lib/data_types.py
index 8c3e42c25e9..0a143fdb420 100644
--- a/zerver/lib/data_types.py
+++ b/zerver/lib/data_types.py
@@ -12,6 +12,12 @@ from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
+def indent(s: str) -> str:
+ padding = " "
+ parts = s.split("\n")
+ return "\n".join(padding + part for part in parts)
+
+
@dataclass
class DictType:
def __init__(
@@ -48,6 +54,14 @@ class DictType:
if k not in keys:
raise AssertionError(f"Unknown key {k} in {var_name}")
+ def schema(self, var_name: str) -> str:
+ # Our current schema is lossy, since our openapi configs
+ # aren't rigorous about "required" fields yet.
+ keys = sorted(list(self.required_keys) + list(self.optional_keys))
+
+ sub_schema = "\n".join(schema(name, data_type) for name, data_type in keys)
+ return f"{var_name} (dict):\n{indent(sub_schema)}"
+
@dataclass
class EnumType:
@@ -57,15 +71,27 @@ class EnumType:
if val not in self.valid_vals:
raise AssertionError(f"{var_name} is not in {self.valid_vals}")
+ def schema(self, var_name: str) -> str:
+ return f"{var_name} in {sorted(self.valid_vals)}"
+
class Equals:
def __init__(self, expected_value: Any) -> None:
self.expected_value = expected_value
+ # super hack for openapi workaround
+ if self.expected_value is None:
+ self.equalsNone = True
+
def check_data(self, var_name: str, val: Dict[str, Any]) -> None:
if val != self.expected_value:
raise AssertionError(f"{var_name} should be equal to {self.expected_value}")
+ def schema(self, var_name: str) -> str:
+ # Treat Equals as the degenerate case of EnumType, which
+ # matches how we do things with openapi.
+ return f"{var_name} in {repr([self.expected_value])}"
+
class ListType:
def __init__(self, sub_type: Any, length: Optional[int] = None) -> None:
@@ -80,6 +106,10 @@ class ListType:
vname = f"{var_name}[{i}]"
check_data(self.sub_type, vname, sub_val)
+ def schema(self, var_name: str) -> str:
+ sub_schema = schema("type", self.sub_type)
+ return f"{var_name} (list):\n{indent(sub_schema)}"
+
@dataclass
class OptionalType:
@@ -90,6 +120,11 @@ class OptionalType:
return
check_data(self.sub_type, var_name, val)
+ def schema(self, var_name: str) -> str:
+ # our openapi spec doesn't support optional types very well yet,
+ # so we just return the schema for our subtype
+ return schema(var_name, self.sub_type)
+
@dataclass
class UnionType:
@@ -107,13 +142,30 @@ class UnionType:
raise AssertionError(f"{var_name} does not pass the union type check")
+ def schema(self, var_name: str) -> str:
+ # We hack around our openapi specs not accounting for None.
+ sub_schemas = "\n".join(
+ sorted(
+ schema("type", sub_type)
+ for sub_type in self.sub_types
+ if not hasattr(sub_type, "equalsNone")
+ )
+ )
+ return f"{var_name} (union):\n{indent(sub_schemas)}"
+
+
class UrlType:
def check_data(self, var_name: str, val: Any) -> None:
try:
URLValidator()(val)
- except ValidationError:
+ except ValidationError: # nocoverage
raise AssertionError(f"{var_name} is not a URL")
+ def schema(self, var_name: str) -> str:
+ # just report str to match openapi
+ return f"{var_name}: str"
+
+
def event_dict_type(
required_keys: Sequence[Tuple[str, Any]],
optional_keys: Sequence[Tuple[str, Any]] = [],
@@ -146,6 +198,23 @@ def make_checker(data_type: DictType,) -> Callable[[str, Dict[str, object]], Non
return f
+def schema(
+ # return a YAML-like string for our data type
+ var_name: str,
+ data_type: Any,
+) -> str:
+ """
+ schema is a glorified repr of a data type, but it
+ also includes a var_name you pass in, plus we dumb
+ things down a bit to match our current openapi spec
+ """
+ if hasattr(data_type, "schema"):
+ return data_type.schema(var_name)
+ if data_type in [bool, dict, int, float, list, str]:
+ return f"{var_name}: {data_type.__name__}"
+ raise AssertionError(f"unknown type {data_type}")
+
+
def check_data(
# Check that data conforms to our data_type
data_type: Any,
diff --git a/zerver/tests/test_data_types.py b/zerver/tests/test_data_types.py
new file mode 100644
index 00000000000..10c9a700e8e
--- /dev/null
+++ b/zerver/tests/test_data_types.py
@@ -0,0 +1,46 @@
+from zerver.lib.data_types import (
+ DictType,
+ EnumType,
+ Equals,
+ ListType,
+ OptionalType,
+ UnionType,
+ UrlType,
+ schema,
+)
+from zerver.lib.test_classes import ZulipTestCase
+
+
+class MiscTest(ZulipTestCase):
+ def test_data_type_schema(self) -> None:
+ """
+ We really only test this to get test coverage. The
+ code covered here is really only used in testing tools.
+ """
+ test_schema = DictType(
+ [
+ ("type", Equals("realm")),
+ ("maybe_n", OptionalType(int)),
+ ("s", str),
+ ("flag", bool),
+ ("level", EnumType([1, 2, 3])),
+ ("lst", ListType(int)),
+ ("value", UnionType([int, str])),
+ ("url", UrlType()),
+ ]
+ )
+ expected = """
+test (dict):
+ flag: bool
+ level in [1, 2, 3]
+ lst (list):
+ type: int
+ maybe_n: int
+ s: str
+ type in ['realm']
+ url: str
+ value (union):
+ type: int
+ type: str
+"""
+ self.assertEqual(schema("test", test_schema).strip(), expected.strip())