Skip to content
Open
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
92 changes: 92 additions & 0 deletions test/codegen/test_codegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -825,6 +825,81 @@ def test_codegen_dataschema_matches_generated_payload_version(pinned, tmp_path,
assert ("/versions/zzz" if pinned else "/versions/stable") in source


@pytest.mark.parametrize("topic_key", ["topic_name", "topic-name", "topic"])
def test_codegen_py_mqtt_tests_cover_topic_and_envelope_variables(topic_key, tmp_path, monkeypatch):
import ast
import py_compile

document = _versioned_schema_document()
message = document["messagegroups"]["Example"]["messages"]["Reading"]
message["envelopemetadata"]["source"] = {
"type": "uritemplate", "value": "https://example.test/{station_id}",
}
message["envelopemetadata"]["subject"] = {"type": "uritemplate", "value": "{station_id}"}
message["protocoloptions"] = {topic_key: "hydro/{water_shortname}/{station_id}/{station_id}"}
definitions = tmp_path / "catalog.json"
definitions.write_text(json.dumps(document), encoding="utf-8")
output = tmp_path / "out"
monkeypatch.setattr(sys, "argv", [
"xrcg", "generate", "--language", "py", "--style", "mqttclient",
"--definitions", str(definitions), "--output", str(output), "--projectname", "TopicContract",
])
assert xrcg.cli() == 0
for source in output.rglob("*.py"):
py_compile.compile(str(source), doraise=True)
generated = ast.parse(next(output.rglob("test_client.py")).read_text(encoding="utf-8"))
calls = [node for node in ast.walk(generated)
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
and node.func.attr.startswith("publish_")]
assert len(calls) == 1
names = [keyword.arg for keyword in calls[0].keywords]
assert names.count("station_id") == 1
assert names.count("water_shortname") == 1
assert "_time" in names


def test_codegen_py_kafka_cross_event_test_uses_inherited_wire_types(tmp_path, monkeypatch):
import ast
import copy
import py_compile

document = _versioned_schema_document()
messages = document["messagegroups"]["Example"]["messages"]
messages["Reading"]["envelopemetadata"]["subject"] = {
"type": "uritemplate", "value": "{station_id}",
}
messages["Other"] = copy.deepcopy(messages["Reading"])
messages["Other"]["envelopemetadata"]["type"]["value"] = "Example.Other"
document["messagegroups"]["Kafka"] = {"messages": {
"Reading.kafka": {"basemessageuri": "#/messagegroups/Example/messages/Reading"},
"Other.kafka": {"basemessageuri": "#/messagegroups/Example/messages/Other"},
}}
document["endpoints"] = {"Kafka": {
"protocol": "Kafka", "usage": ["producer"], "messagegroups": ["#/messagegroups/Kafka"],
"protocoloptions": {"options": {"key": "{station_id}"}},
}}
definitions = tmp_path / "catalog.json"
definitions.write_text(json.dumps(document), encoding="utf-8")
output = tmp_path / "out"
monkeypatch.setattr(sys, "argv", [
"xrcg", "generate", "--language", "py", "--style", "kafkaproducer",
"--endpoint", "Kafka", "--definitions", str(definitions),
"--output", str(output), "--projectname", "WireTypeContract",
])
assert xrcg.cli() == 0
for source in output.rglob("*.py"):
py_compile.compile(str(source), doraise=True)
generated = ast.parse(next(output.rglob("test_producer.py")).read_text(encoding="utf-8"))
test = next(node for node in generated.body if isinstance(node, ast.FunctionDef)
and node.name.endswith("cross_event_type_kafka_key"))
filters = [node.comparators[0] for node in ast.walk(test)
if isinstance(node, ast.Compare) and isinstance(node.ops[0], ast.In)
and isinstance(node.left, ast.Subscript) and isinstance(node.left.slice, ast.Constant)
and node.left.slice.value == "type"]
assert len(filters) == 1
assert [item.value for item in filters[0].elts] == ["Example.Reading", "Example.Other"]


@pytest.mark.parametrize("content_mode", ["binary", "structured"])
@pytest.mark.parametrize("mapping_kind", ["none", "empty", "match", "unmatched", "chain"])
def test_generated_dataschema_overrides(content_mode, mapping_kind, tmp_path, monkeypatch):
Expand All @@ -844,6 +919,9 @@ def test_generated_dataschema_overrides(content_mode, mapping_kind, tmp_path, mo
overrides = mappings[mapping_kind]
document = _versioned_schema_document()
messages = document["messagegroups"]["Example"]["messages"]
messages["Reading"]["envelopemetadata"]["datacontenttype"] = {
"type": "string", "value": "application/json",
}
for name in ("Shared", "Explicit"):
messages[name] = copy.deepcopy(messages["Reading"])
messages[name]["messageid"] = name
Expand Down Expand Up @@ -885,6 +963,20 @@ def schema(message):
expected = registered if mapping_kind in ("match", "chain") else original
expected_explicit = registered if mapping_kind in ("match", "chain") else explicit
assert list(map(schema, sender.messages)) == [expected, expected, expected_explicit]
if content_mode == "structured":
import base64

for message in sender.messages:
envelope = json.loads(message["value"])
assert envelope["data"] == json.loads(data.to_json())
assert "data_base64" not in envelope
binary_payload = CaptureProducer()
producer_class(binary_payload, "readings", content_mode).send_reading(
data, content_type="application/vnd.apache.avro+avro", flush_producer=False)
envelope = json.loads(binary_payload.messages[0]["value"])
assert "data" not in envelope
assert base64.b64decode(envelope["data_base64"], validate=True) == data.to_byte_array(
"application/vnd.apache.avro+avro")
untouched = CaptureProducer()
producer_class(untouched, "readings", content_mode).send_reading(data, flush_producer=False)
assert schema(untouched.messages[0]) == original
Expand Down
27 changes: 27 additions & 0 deletions xrcg/templates/py/_common/util.include.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,33 @@
{{ dataType }}
{%- endmacro -%}

{%- macro CollectMqttUriTemplateVariables(message, variables) -%}
{%- for attrname, attribute in message.envelopemetadata.items() -%}
{%- if attribute.value and attribute.type == "uritemplate" and attrname != "time" -%}
{%- for placeholder in attribute.value | regex_search('\\{([A-Za-z0-9_]+)\\}') -%}
{%- if placeholder not in variables -%}
{%- set _ = variables.append(placeholder) -%}
{%- endif -%}
{%- endfor -%}
{%- endif -%}
{%- endfor -%}
{%- set topic = none -%}
{%- if message.protocoloptions and message.protocoloptions.topic_name -%}
{%- set topic = message.protocoloptions.topic_name -%}
{%- elif message.protocoloptions and message.protocoloptions['topic-name'] -%}
{%- set topic = message.protocoloptions['topic-name'] -%}
{%- elif message.protocoloptions and message.protocoloptions.topic -%}
{%- set topic = message.protocoloptions.topic -%}
{%- endif -%}
{%- if topic -%}
{%- for placeholder in topic | regex_search('\\{([A-Za-z0-9_]+)\\}') -%}
{%- if placeholder not in variables -%}
{%- set _ = variables.append(placeholder) -%}
{%- endif -%}
{%- endfor -%}
{%- endif -%}
{%- endmacro -%}

{%- macro DeclareDataTestModule(data_project_name, type_name) -%}
{%- set root_package = data_project_name | dotunderscore | lower -%}
{%- set relative_type_name = type_name | replace(root_package + ".", "", 1) -%}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -243,9 +243,12 @@ class {{ class_name }}:
attributes["dataschema"] = self._dataschema_overrides.get(attributes["dataschema"], attributes["dataschema"])
event = CloudEvent.create(attributes, byte_data)
if self.content_mode == "structured":
media_type = content_type.split(";", 1)[0].strip().lower()
if byte_data is not None and (media_type == "application/json" or media_type.endswith("+json")):
event = CloudEvent.create(attributes, json.loads(byte_data))
message = to_structured(
event,
data_marshaller=lambda x: self.__binary_data_marshaller(x),
data_marshaller=lambda x: x,
envelope_marshaller=lambda envelope: json.dumps({**envelope, "datacontenttype": content_type}),
key_mapper=lambda x: self.__key_mapper(x, data, key_mapper, kafka_key),
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,7 @@ def test_{{ groupname | lower | replace(" ", "_") | dotunderscore }}_cross_event
if msg is None or msg.error():
continue
cloudevent = parse_cloudevent(msg)
if cloudevent['type'] in ["{{ first_msg_id }}", "{{ second_msg_id }}"]:
if cloudevent['type'] in ["{{ first_msg.envelopemetadata['type']['value'] if ('type' in first_msg.envelopemetadata and 'value' in first_msg.envelopemetadata['type']) else first_msg_id }}", "{{ second_msg.envelopemetadata['type']['value'] if ('type' in second_msg.envelopemetadata and 'value' in second_msg.envelopemetadata['type']) else second_msg_id }}"]:
key = msg.key().decode('utf-8') if msg.key() else None
collected_keys.append(key)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -688,39 +688,7 @@ class {{ class_name }}(_ClientBase):
{%- set messagename = messageid | dotunderscore | snake %}
{%- set type_name = util.DeclareDataType( data_project_name, root, message ) %}
{%- set uri_template_vars = [] %}
{%- for attrname, attribute in message.envelopemetadata.items() %}
{%- if attribute.value and attribute.type == "uritemplate" and attrname != "time" %}
{%- set phs = attribute.value | regex_search('\\{([A-Za-z0-9_]+)\\}') %}
{%- if phs %}
{%- for placeholder in phs %}
{%- if placeholder not in uri_template_vars %}
{%- set _ = uri_template_vars.append(placeholder) %}
{%- endif %}
{%- endfor %}
{%- endif %}
{%- endif %}
{%- endfor %}
{#- Also include URI template placeholders that appear in the message-level
MQTT topic uritemplate (protocoloptions.topic_name per spec) so the
publish method exposes every variable the topic requires. -#}
{%- set _topic_value = none -%}
{%- if message.protocoloptions and message.protocoloptions.topic_name -%}
{%- set _topic_value = message.protocoloptions.topic_name -%}
{%- elif message.protocoloptions and message.protocoloptions['topic-name'] -%}
{%- set _topic_value = message.protocoloptions['topic-name'] -%}
{%- elif message.protocoloptions and message.protocoloptions.topic -%}
{%- set _topic_value = message.protocoloptions.topic -%}
{%- endif -%}
{%- if _topic_value -%}
{%- set topic_phs = _topic_value | regex_search('\\{([A-Za-z0-9_]+)\\}') -%}
{%- if topic_phs %}
{%- for placeholder in topic_phs %}
{%- if placeholder not in uri_template_vars %}
{%- set _ = uri_template_vars.append(placeholder) %}
{%- endif %}
{%- endfor %}
{%- endif %}
{%- endif %}
{%- set _ = util.CollectMqttUriTemplateVariables(message, uri_template_vars) %}
{%- set time_uri_template_vars = [] %}
{%- if 'time' in message.envelopemetadata and message.envelopemetadata['time'].value and message.envelopemetadata['time'].type == "uritemplate" -%}
{%- for placeholder in message.envelopemetadata['time'].value | regex_search('\\{([A-Za-z0-9_]+)\\}') -%}
Expand Down
12 changes: 5 additions & 7 deletions xrcg/templates/py/mqttclient/{testdir}test_client.py.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -183,18 +183,16 @@ async def test_{{groupName}}_{{messagename.split('.')[-1]}}_py(mosquitto_broker)
await asyncio.sleep(1)

# Publish 5 messages to test message settlement and ordering
{%- set uri_template_vars = [] %}
{%- set _ = util.CollectMqttUriTemplateVariables(message, uri_template_vars) %}
for i in range(5):
await publisher_client.publish_{{messagename.split('.')[-1]}}(
topic=test_topic,
{%- for attrname, attribute in message.envelopemetadata.items() %}
{%- if attribute.type == "uritemplate" and attribute.value and attrname != "time" %}
{%- set phs = attribute.value | regex_search('\\{([A-Za-z0-9_]+)\\}') %}
{%- if phs %}
{%- for placeholder in phs %}
{%- for placeholder in uri_template_vars %}
{{ placeholder | snake }}=f"test_{{placeholder}}_{i}",
{%- endfor %}
{%- endif %}
{%- elif not attribute.value and attrname != "time" %}
{%- for attrname, attribute in message.envelopemetadata.items() %}
{%- if not attribute.value and attribute.type != "uritemplate" and attrname != "time" %}
_{{ attrname | snake }}=f"test_{{attrname}}_{i}",
{%- endif %}
{%- endfor %}
Expand Down
Loading