def setup_method(self, method): super().setup_method(method) self.sample_message = api.Message( topic='', body={ 'build_id': 442562, 'name': 'bodhi', 'tag_id': 214, 'instance': 's390', 'tag': 'f26-updates-testing-pending', 'user': '******', 'version': '2.0', 'owner': 'sharkcz', 'release': '1.fc17' }, ) self.sample_side_tag_message = api.Message( topic='', body={ 'build_id': 442562, 'name': 'bodhi', 'tag_id': 214, 'instance': 's390', 'tag': 'f30-side-tag-testing-pending', 'user': '******', 'version': '2.0', 'owner': 'sharkcz', 'release': '1.fc17' }, ) self.handler = signed.SignedHandler()
def test_clear_messages_on_send(self): """Assert the message queue is cleared after the event handler runs.""" session = Session() session.info['messages'] = [api.Message()] with fml_testing.mock_sends(api.Message()): notifications.send_messages_after_commit(session) assert session.info['messages'] == []
def test_instance(self): """Assert all goes well if the message published matches the asserted instance.""" def pub(): api.publish(api.Message()) with testing.mock_sends(api.Message()): pub()
def publish(topic, msg, force=False): """ Send a message via Fedora Messaging. This is used to send a message to the AMQP broker. Args: topic (str): The topic suffix. The "bodhi" prefix is applied (along with the "topic_prefix" settings from Fedora Messaging). msg (dict): The message body to send. force (bool): If False (the default), the message is only sent after the currently active database transaction successfully commits. If true, the messages is sent immediately. """ # Dirty, nasty hack that I feel shame for: use the fedmsg encoder that modifies # messages quietly if they have objects with __json__ methods on them. # For now, copy that behavior. In the future, callers should pass # fedora_messaging.api.Message sub-classes or this whole API should go away. body = json.loads(json.dumps(msg, cls=FedMsgEncoder)) message = api.Message(topic="bodhi.{}".format(topic), body=body) if force: api.publish(message) return session = Session() if 'messages' not in session.info: session.info['messages'] = [] session.info['messages'].append(message) _log.debug('Queuing message %r for delivery on session commit', message.id)
def admin_new_release(): if not is_admin(): flask.flash("You are not an admin", "error") return flask.redirect(flask.url_for("ui.index")) form = forms.ReleaseForm() if form.validate_on_submit(): release = db.Release() form.populate_obj(obj=release) db.Session.add(release) db.Session.commit() message = fm_api.Message( topic="kerneltest.release.new", body={ "agent": flask.g.user.username, "release": { "releasenum": release.version, "support": release.support }, }, ) try: fm_api.publish(message) except ( fm_api.exceptions.ConnectionException, fm_api.exceptions.ConnectionException, ): pass flask.flash('Release "%s" added' % release.version) return flask.redirect(flask.url_for("ui.index")) return flask.render_template("release_new.html", form=form, submit_text="Create release")
def test_publish_force(self): """Assert that fedora-messaging messages respect the force flag.""" expected = api.Message(topic='bodhi.demo.topic', body={u'such': 'important'}) with fml_testing.mock_sends(expected): notifications.publish('demo.topic', {'such': 'important'}, force=True)
def publish_fedmsg(session, message): if not get_config('fedmsg-publisher.enabled', False): return message = fedmsg.Message( topic='{modname}.{topic}'.format(**message), body=message['msg'], ) session.log.info('Publishing fedmsg:\n' + str(message)) fedmsg.publish(message)
def test_pub_connection_refused(self): """Assert ConnectionException is raised on connection refused.""" # Because we don't call accept, we can be sure of a connection refusal sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("", 0)) url = "amqp://localhost:{port}/".format(port=sock.getsockname()[1]) api._session_cache.session = api._session.PublisherSession(amqp_url=url) self.assertRaises(exceptions.ConnectionException, api.publish, api.Message())
def _do_publish(session, topic, body): namespace = get_config('osci.namespace') artifact_type = get_config('osci.build_group_artifact_type') message = fedmsg.Message( topic=f'ci.{namespace}.{artifact_type}.test.{topic}', body=body, ) session.log.info('Publishing fedmsg:\n' + str(message)) fedmsg.publish(message)
def test_error_logged(self, mock_log, mock_pub): session = Session() message = api.Message() session.info['messages'] = [message] mock_pub.side_effect = fml_exceptions.BaseException() notifications.send_messages_after_commit(session) mock_log.exception.assert_called_once_with( "An error occurred publishing %r after a database commit", message)
def test_mix_class_instance(self): """Assert a mix of class and instance works.""" def pub(): api.publish(api.Message()) api.publish(CustomMessage()) with mock.patch.dict(message._class_to_schema_name, {CustomMessage: "custom"}): with testing.mock_sends(api.Message(), CustomMessage): pub()
def test_pub_timeout(): """Assert PublishTimeout is raised if a connection just hangs.""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("", 0)) config.conf["amqp_url"] = "amqp://localhost:{port}/".format( port=sock.getsockname()[1]) try: yield threads.deferToThread(api.publish, api.Message(), 5) except Exception as e: if not isinstance(e, exceptions.PublishTimeout): pytest.fail("Expected a timeout exception, not {}".format(e)) finally: sock.close()
def test_mix_class_instance_order_matters(self): """Assert the order of messages matters.""" expected_err = ( "Expected message of type <class 'fedora_messaging.tests.unit.test_testing" ".CustomMessage'>, but <class 'fedora_messaging.message.Message'> was sent" ) def pub(): api.publish(api.Message()) api.publish(CustomMessage()) with mock.patch.dict(message._class_to_schema_name, {CustomMessage: "custom"}): with self.assertRaises(AssertionError) as cm: with testing.mock_sends(CustomMessage, api.Message()): pub() self.assertEqual(expected_err, cm.exception.args[0])
def test_printer(self): """Assert the printer callback prints messages.""" message = api.Message(body=u"Hello world", topic=u"hi") message._headers = { "fedora_messaging_schema": "fedora_messaging.message:Message", "sent-at": "2018-08-22T00:00:00", } message.id = "95383db8-8cdc-4464-8276-d482ac28b0b6" expected_stdout = ( u"Id: 95383db8-8cdc-4464-8276-d482ac28b0b6\n" u"Topic: hi\n" u"Headers: {\n" u' "fedora_messaging_schema": "fedora_messaging.message:Message",\n' u' "sent-at": "2018-08-22T00:00:00"\n' u"}\n" u'Body: "Hello world"\n') with mock.patch("sys.stdout", new_callable=StringIO) as mock_stdout: example.printer(message) self.assertEqual(expected_stdout, mock_stdout.getvalue())
def admin_edit_release(relnum): if not is_admin(): flask.flash("You are not an admin", "error") return flask.redirect(flask.url_for("ui.index")) release = db.Release.query.filter_by(version=relnum).one_or_none() if not release: flask.flash("No release %s found" % relnum) return flask.redirect(flask.url_for("ui.index")) form = forms.ReleaseForm(obj=release) if form.validate_on_submit(): form.populate_obj(obj=release) db.Session.commit() message = fm_api.Message( topic="kerneltest.release.edit", body={ "agent": flask.g.user.username, "release": { "releasenum": release.version, "support": release.support }, }, ) try: fm_api.publish(message) except ( fm_api.exceptions.ConnectionException, fm_api.exceptions.ConnectionException, ): pass flask.flash('Release "%s" updated' % release.version) return flask.redirect(flask.url_for("ui.index")) return flask.render_template("release_new.html", form=form, release=release, submit_text="Edit release")
def test_two_reminder(self, smtp_mock, mail_mock): """ Test the cron job for a meeting with a single reminder to send. """ smtp_mock.return_value = FakeSMTP() mail_mock.return_value = None # Meeting with a reminder remobj = model.Reminder('H-12', '[email protected]', '[email protected],[email protected]', 'Come to our test meeting') remobj.save(self.session) self.session.flush() date_sa = datetime.utcnow() + timedelta(hours=12) date_so = datetime.utcnow() + timedelta(hours=13) obj = model.Meeting( # id:1 meeting_name='Test meeting with reminder', meeting_date=date_sa.date(), meeting_date_end=date_so.date(), meeting_time_start=date_sa.time(), meeting_time_stop=date_so.time(), meeting_information='This is a test meeting with reminder', calendar_name='test_calendar', reminder_id=remobj.reminder_id) obj.save(self.session) obj.add_manager(self.session, ['pingou']) self.session.commit() self.assertNotEqual(obj, None) with testing.mock_sends( api.Message(topic="fedocal.reminder", body={ 'meeting': { 'meeting_id': 1, 'meeting_name': 'Test meeting with reminder', 'meeting_manager': ['pingou'], 'meeting_date': ANY, 'meeting_date_end': ANY, 'meeting_time_start': ANY, 'meeting_time_stop': ANY, 'meeting_timezone': 'UTC', 'meeting_information': 'This is a test meeting with reminder', 'meeting_location': None, 'calendar_name': 'test_calendar' }, 'calendar': { 'calendar_name': 'test_calendar', 'calendar_contact': '*****@*****.**', 'calendar_description': 'This is a test calendar', 'calendar_editor_group': 'fi-apprentice', 'calendar_admin_group': 'infrastructure-main2', 'calendar_status': 'Enabled' } })): msgs = fedocal_cron.send_reminder() self.assertEqual(len(msgs), 1) self.assertEqual(msgs[0]['To'], '[email protected], [email protected]') self.assertEqual(msgs[0]['From'], '[email protected]')
def pub(): api.publish(api.Message()) api.publish(api.Message())