Merge "Replace special characters in MQTT topic"

This commit is contained in:
Zuul 2024-03-12 14:32:49 +00:00 committed by Gerrit Code Review
commit 93d2118ecf
2 changed files with 21 additions and 0 deletions

View File

@ -822,6 +822,22 @@ class TestMQTTConnection(ZuulTestCase):
self.assertIn("topic component 'bad' is invalid", A.messages[0],
"A should report a syntax error")
def test_topic_replace_invalid_chars(self):
# Test that special characters in the topic are replaced
self.create_branch('org/project', 'weird#+')
self.fake_gerrit.addEvent(
self.fake_gerrit.getFakeBranchCreatedEvent(
'org/project', 'weird#+'))
self.waitUntilSettled()
A = self.fake_gerrit.addFakeChange('org/project', 'weird#+', 'A')
self.fake_gerrit.addEvent(A.getPatchsetCreatedEvent(1))
self.waitUntilSettled()
success_event = self.mqtt_messages.pop()
self.assertEqual(success_event['topic'],
'tenant-one/zuul_buildset/check/org/project/weird__')
class TestElasticsearchConnection(AnsibleZuulTestCase):
config_file = 'zuul-elastic-driver.conf'

View File

@ -27,6 +27,10 @@ class MQTTReporter(BaseReporter):
name = 'mqtt'
log = logging.getLogger("zuul.MQTTReporter")
invalid_topic_chars = str.maketrans({
'+': '_',
'#': '_',
})
def report(self, item, phase1=True, phase2=True):
if not phase1:
@ -158,6 +162,7 @@ class MQTTReporter(BaseReporter):
change=getattr(item.changes[0], 'number', None),
patchset=getattr(item.changes[0], 'patchset', None),
ref=getattr(item.changes[0], 'ref', None))
topic = topic.translate(self.invalid_topic_chars)
except Exception:
log.exception("Error while formatting MQTT topic %s:",
self.config['topic'])