def test_render_mail(self, autorebuild, submitter):
        # just test a random combination of the method inputs and hope it's ok for other
        #   combinations
        class WF(object):
            image = ImageName.parse('foo/bar:baz')
            openshift_build_selflink = '/builds/blablabla'
        kwargs = {'url': 'https://something.com'}
        if submitter:
            kwargs['submitter'] = submitter
        p = SendMailPlugin(None, WF(), **kwargs)
        subject, body = p._render_mail(autorebuild, False, False)

        exp_subject = 'Image foo/bar:baz; Status failed; Submitted by '
        exp_body = [
            'Image: foo/bar:baz',
            'Status: failed',
            'Submitted by: ',
            'Logs: https://something.com/builds/blablabla/log'
        ]
        if autorebuild:
            exp_subject += '<autorebuild>'
            exp_body[2] += '<autorebuild>'
        elif submitter:
            exp_subject += submitter
            exp_body[2] += submitter
        else:
            exp_subject += 'unknown'
            exp_body[2] += 'unknown'

        assert subject == exp_subject
        assert body == '\n'.join(exp_body)
    def test_get_email_from_koji_obj(self, has_kerberos,
                                     email_domain, expected_email,
                                     workflow):
        session = MockedClientSession('', has_kerberos=has_kerberos)
        flexmock(koji, ClientSession=lambda hub, opts: session)

        workflow.data.postbuild_results[KojiImportPlugin.key] = MOCK_KOJI_BUILD_ID

        smtp_map = {
            'from_address': '*****@*****.**',
            'host': 'smtp.bar.com',
            'domain': email_domain,
        }

        rcm = {'version': 1, 'smtp': smtp_map, 'openshift': {'url': 'https://something.com'}}
        workflow.conf = Configuration(raw_config=rcm)
        add_koji_map_in_workflow(workflow, hub_url='/', root_url='',
                                 ssl_certs_dir='/certs')

        p = SendMailPlugin(workflow, email_domain=email_domain)
        koji_task_owner = get_koji_task_owner(p.session, p.koji_task_id)

        try:
            found_email = p._get_email_from_koji_obj(koji_task_owner)
            assert expected_email == found_email
        except RuntimeError as exc:
            if not email_domain:
                assert str(exc) == "Empty email_domain specified"
            else:
                assert str(exc) == "Koji task owner name is missing"
    def test_should_send(self, rebuild, success, auto_canceled, manual_canceled, send_on, expected,
                         reactor_config_map):
        class WF(object):
            exit_results = {
                KojiPromotePlugin.key: MOCK_KOJI_BUILD_ID
            }
            plugin_workspace = {}

        kwargs = {
            'smtp_host': 'smtp.bar.com',
            'from_address': '*****@*****.**',
            'send_on': send_on,
        }

        workflow = WF()
        if reactor_config_map:
            smtp_map = {
                'from_address': '*****@*****.**',
                'host': 'smtp.spam.com',
            }
            workflow.plugin_workspace[ReactorConfigPlugin.key] = {}
            workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\
                ReactorConfig({'version': 1, 'smtp': smtp_map})

        p = SendMailPlugin(None, workflow, **kwargs)
        assert p._should_send(rebuild, success, auto_canceled, manual_canceled) == expected
Beispiel #4
0
    def test_should_send(self, rebuild, success, auto_canceled, manual_canceled, send_on, expected):
        class WF(object):
            exit_results = {
                KojiImportPlugin.key: MOCK_KOJI_BUILD_ID
            }
            plugin_workspace = {}

        kwargs = {
            'smtp_host': 'smtp.bar.com',
            'from_address': '*****@*****.**',
            'send_on': send_on,
        }

        workflow = WF()

        smtp_map = {
            'from_address': '*****@*****.**',
            'host': 'smtp.spam.com',
        }
        workflow.plugin_workspace[ReactorConfigPlugin.key] = {}
        workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\
            ReactorConfig({'version': 1, 'smtp': smtp_map})
        add_koji_map_in_workflow(workflow, hub_url='/', root_url='',
                                 ssl_certs_dir='/certs')

        p = SendMailPlugin(None, workflow, **kwargs)
        assert p._should_send(rebuild, success, auto_canceled, manual_canceled) == expected
    def test_run_ok_and_send(self, workflow):
        workflow.data.plugin_failed = True

        class SMTP(object):
            def sendmail(self, from_addr, to, msg):
                pass

            def quit(self):
                pass

        smtp_map = {
            'from_address': '*****@*****.**',
            'host': 'smtp.spam.com',
        }
        rcm = {'version': 1, 'smtp': smtp_map, 'openshift': {'url': 'https://something.com'}}
        workflow.conf = Configuration(raw_config=rcm)
        add_koji_map_in_workflow(workflow, hub_url='/', root_url='',
                                 ssl_certs_dir='/certs')

        receivers = ['*****@*****.**', '*****@*****.**']
        p = SendMailPlugin(workflow,
                           from_address='*****@*****.**', smtp_host='smtp.spam.com',
                           send_on=[])

        (flexmock(p).should_receive('_should_send')
            .with_args(False, False).and_return(True))
        flexmock(p).should_receive('_get_receivers_list').and_return(receivers)
        flexmock(p).should_receive('_get_image_name_and_repos').and_return(('foobar',
                                                                           ['foo/bar:baz',
                                                                            'foo/bar:spam']))

        smtp_inst = SMTP()
        flexmock(smtplib).should_receive('SMTP').and_return(smtp_inst)
        p.run()
    def test_get_receiver_list(self, additional_addresses, expected_receivers, workflow):
        session = MockedClientSession('', has_kerberos=True)
        pathinfo = MockedPathInfo('https://koji')

        flexmock(koji, ClientSession=lambda hub, opts: session, PathInfo=pathinfo)
        kwargs = {
            'url': 'https://something.com',
            'smtp_host': 'smtp.bar.com',
            'from_address': '*****@*****.**',
            'additional_addresses': additional_addresses
        }

        workflow.data.postbuild_results[KojiImportPlugin.key] = MOCK_KOJI_BUILD_ID

        smtp_map = {
            'from_address': '*****@*****.**',
            'host': 'smtp.bar.com',
            'send_to_submitter': False,
            'send_to_pkg_owner': False,
            'additional_addresses': additional_addresses
        }
        rcm = {'version': 1, 'smtp': smtp_map, 'openshift': {'url': 'https://something.com'}}
        workflow.conf = Configuration(raw_config=rcm)
        add_koji_map_in_workflow(workflow, hub_url=None, root_url='https://koji/',
                                 ssl_certs_dir='/certs')

        p = SendMailPlugin(workflow, **kwargs)
        if expected_receivers is not None:
            assert sorted(expected_receivers) == sorted(p._get_receivers_list())
        else:
            with pytest.raises(RuntimeError) as ex:
                p._get_receivers_list()
                assert str(ex.value) == 'No recipients found'
    def test_run_ok(self, tmpdir, workflow, source_dir):
        workflow.data.plugin_failed = True
        receivers = ['*****@*****.**', '*****@*****.**']

        dockerfile = source_dir / DOCKERFILE_FILENAME
        dockerfile.write_text(MOCK_DOCKERFILE, "utf-8")
        flexmock(workflow, df_path=str(dockerfile))

        mock_store_metadata_results(workflow)

        smtp_map = {
            'from_address': '*****@*****.**',
            'host': 'smtp.bar.com',
        }
        rcm = {'version': 1, 'smtp': smtp_map, 'openshift': {'url': 'https://something.com'}}
        workflow.conf = Configuration(raw_config=rcm)
        add_koji_map_in_workflow(workflow, hub_url='/', root_url='',
                                 ssl_certs_dir='/certs')

        p = SendMailPlugin(workflow,
                           from_address='*****@*****.**', smtp_host='smtp.spam.com',
                           send_on=[])

        (flexmock(p).should_receive('_should_send')
         .with_args(False, False).and_return(True))
        flexmock(p).should_receive('_get_receivers_list').and_return(receivers)
        flexmock(p).should_receive('_send_mail').with_args(receivers,
                                                           str, str, None)

        p.run()
Beispiel #8
0
    def test_get_receiver_list(self, monkeypatch, additional_addresses, expected_receivers):
        class TagConf(object):
            unique_images = []

        class WF(object):
            image = ImageName.parse('foo/bar:baz')
            openshift_build_selflink = '/builds/blablabla'
            build_process_failed = False
            autorebuild_canceled = False
            build_canceled = False
            tag_conf = TagConf()
            exit_results = {
                KojiImportPlugin.key: MOCK_KOJI_BUILD_ID
            }
            prebuild_results = {}
            plugin_workspace = {}

        monkeypatch.setenv("BUILD", json.dumps({
            'metadata': {
                'labels': {
                    'koji-task-id': MOCK_KOJI_TASK_ID,
                },
                'name': {},
            }
        }))

        session = MockedClientSession('', has_kerberos=True)
        pathinfo = MockedPathInfo('https://koji')

        flexmock(koji, ClientSession=lambda hub, opts: session, PathInfo=pathinfo)
        kwargs = {
            'url': 'https://something.com',
            'smtp_host': 'smtp.bar.com',
            'from_address': '*****@*****.**',
            'additional_addresses': additional_addresses
        }

        workflow = WF()

        openshift_map = {'url': 'https://something.com'}
        smtp_map = {
            'from_address': '*****@*****.**',
            'host': 'smtp.bar.com',
            'send_to_submitter': False,
            'send_to_pkg_owner': False,
            'additional_addresses': additional_addresses
        }
        workflow.plugin_workspace[ReactorConfigPlugin.key] = {}
        workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\
            ReactorConfig({'version': 1, 'smtp': smtp_map, 'openshift': openshift_map})
        add_koji_map_in_workflow(workflow, hub_url=None, root_url='https://koji/',
                                 ssl_certs_dir='/certs')

        p = SendMailPlugin(None, workflow, **kwargs)
        if expected_receivers is not None:
            assert sorted(expected_receivers) == sorted(p._get_receivers_list())
        else:
            with pytest.raises(RuntimeError) as ex:
                p._get_receivers_list()
                assert str(ex.value) == 'No recipients found'
    def test_run_invalid_receivers(self, caplog, workflow):
        workflow.data.plugin_failed = True
        error_addresses = ['*****@*****.**']

        mock_store_metadata_results(workflow)

        smtp_map = {
            'from_address': '*****@*****.**',
            'host': 'smtp.bar.com',
            'error_addresses': ['*****@*****.**'],
        }
        rcm = {'version': 1, 'smtp': smtp_map, 'openshift': {'url': 'https://something.com'}}
        workflow.conf = Configuration(raw_config=rcm)
        add_koji_map_in_workflow(workflow, hub_url='/', root_url='',
                                 ssl_certs_dir='/certs')

        p = SendMailPlugin(workflow,
                           from_address='*****@*****.**', smtp_host='smtp.spam.com',
                           send_on=[], error_addresses=error_addresses)

        (flexmock(p).should_receive('_should_send')
            .with_args(False, False).and_return(True))
        flexmock(p).should_receive('_get_receivers_list').and_return([])
        flexmock(p).should_receive('_get_image_name_and_repos').and_return(('foobar',
                                                                           ['foo/bar:baz',
                                                                            'foo/bar:spam']))
        p.run()
        assert 'no valid addresses in requested addresses. Doing nothing' in caplog.text
Beispiel #10
0
    def test_render_mail(self, autorebuild, submitter):
        # just test a random combination of the method inputs and hope it's ok for other
        #   combinations
        class WF(object):
            image = ImageName.parse('foo/bar:baz')
            openshift_build_selflink = '/builds/blablabla'
        kwargs = {'url': 'https://something.com'}
        if submitter:
            kwargs['submitter'] = submitter
        p = SendMailPlugin(None, WF(), **kwargs)
        subject, body = p._render_mail(autorebuild, False, False)

        exp_subject = 'Image foo/bar:baz; Status failed; Submitted by '
        exp_body = [
            'Image: foo/bar:baz',
            'Status: failed',
            'Submitted by: ',
            'Logs: https://something.com/builds/blablabla/log'
        ]
        if autorebuild:
            exp_subject += '<autorebuild>'
            exp_body[2] += '<autorebuild>'
        elif submitter:
            exp_subject += submitter
            exp_body[2] += submitter
        else:
            exp_subject += 'unknown'
            exp_body[2] += 'unknown'

        assert subject == exp_subject
        assert body == '\n'.join(exp_body)
    def test_run_does_nothing_if_conditions_not_met(self, reactor_config_map):  # noqa
        class WF(object):
            autorebuild_canceled = False
            build_canceled = False
            prebuild_results = {CheckAndSetRebuildPlugin.key: True}
            image = util.ImageName.parse('repo/name')
            build_process_failed = True
            exit_results = {}
            plugin_workspace = {}

        workflow = WF()
        if reactor_config_map:
            smtp_map = {
                'from_address': '*****@*****.**',
                'host': 'smtp.spam.com',
            }
            workflow.plugin_workspace[ReactorConfigPlugin.key] = {}
            workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\
                ReactorConfig({'version': 1, 'smtp': smtp_map})

        p = SendMailPlugin(None, workflow,
                           from_address='*****@*****.**', smtp_host='smtp.spam.com',
                           send_on=[MS])

        (flexmock(p).should_receive('_should_send')
            .with_args(True, False, False, False).and_return(False))
        flexmock(p).should_receive('_get_receivers_list').times(0)
        flexmock(p).should_receive('_send_mail').times(0)

        p.run()
Beispiel #12
0
    def test_run_fails_to_obtain_receivers(self):
        class TagConf(object):
            unique_images = []

        class WF(object):
            autorebuild_canceled = False
            build_canceled = False
            prebuild_results = {CheckAndSetRebuildPlugin.key: True}
            image = util.ImageName.parse('repo/name')
            build_process_failed = True
            tag_conf = TagConf()
            exit_results = {}

        error_addresses = ['*****@*****.**']
        p = SendMailPlugin(None,
                           WF(),
                           from_address='*****@*****.**',
                           smtp_host='smtp.spam.com',
                           send_on=[AF],
                           error_addresses=error_addresses)

        (flexmock(p).should_receive('_should_send').with_args(
            True, False, False, False).and_return(True))
        flexmock(p).should_receive('_get_receivers_list').and_raise(
            RuntimeError())
        flexmock(p).should_receive('_send_mail').with_args(
            error_addresses, six.text_type, six.text_type)

        p.run()
Beispiel #13
0
    def test_run_does_nothing_if_conditions_not_met(
            self, reactor_config_map):  # noqa
        class WF(object):
            autorebuild_canceled = False
            build_canceled = False
            prebuild_results = {CheckAndSetRebuildPlugin.key: True}
            image = util.ImageName.parse('repo/name')
            build_process_failed = True
            exit_results = {}
            plugin_workspace = {}

        workflow = WF()
        if reactor_config_map:
            smtp_map = {
                'from_address': '*****@*****.**',
                'host': 'smtp.spam.com',
            }
            workflow.plugin_workspace[ReactorConfigPlugin.key] = {}
            workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\
                ReactorConfig({'version': 1, 'smtp': smtp_map})

        p = SendMailPlugin(None,
                           workflow,
                           from_address='*****@*****.**',
                           smtp_host='smtp.spam.com',
                           send_on=[MS])

        (flexmock(p).should_receive('_should_send').with_args(
            True, False, False, False).and_return(False))
        flexmock(p).should_receive('_get_receivers_list').times(0)
        flexmock(p).should_receive('_send_mail').times(0)

        p.run()
Beispiel #14
0
    def test_should_send(self, rebuild, success, auto_canceled,
                         manual_canceled, send_on, expected,
                         reactor_config_map):
        class WF(object):
            exit_results = {KojiPromotePlugin.key: MOCK_KOJI_BUILD_ID}
            plugin_workspace = {}

        kwargs = {
            'smtp_host': 'smtp.bar.com',
            'from_address': '*****@*****.**',
            'send_on': send_on,
        }

        workflow = WF()
        if reactor_config_map:
            smtp_map = {
                'from_address': '*****@*****.**',
                'host': 'smtp.spam.com',
            }
            workflow.plugin_workspace[ReactorConfigPlugin.key] = {}
            workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\
                ReactorConfig({'version': 1, 'smtp': smtp_map})

        p = SendMailPlugin(None, workflow, **kwargs)
        assert p._should_send(rebuild, success, auto_canceled,
                              manual_canceled) == expected
Beispiel #15
0
    def test_generated_email(self, monkeypatch, has_kerberos, expected_receivers):
        class TagConf(object):
            unique_images = []

        class WF(object):
            image = ImageName.parse('foo/bar:baz')
            openshift_build_selflink = '/builds/blablabla'
            build_process_failed = False
            tag_conf = TagConf()
            exit_results = {
                KojiImportPlugin.key: MOCK_KOJI_BUILD_ID
            }
            plugin_workspace = {}

        monkeypatch.setenv("BUILD", json.dumps({
            'metadata': {
                'labels': {
                    'koji-task-id': MOCK_KOJI_TASK_ID,
                },
                'name': {},
            }
        }))

        session = MockedClientSession('', has_kerberos=has_kerberos)
        flexmock(koji, ClientSession=lambda hub, opts: session, PathInfo=MockedPathInfo)

        kwargs = {
            'url': 'https://something.com',
            'smtp_host': 'smtp.bar.com',
            'from_address': '*****@*****.**',
            'to_koji_submitter': True,
            'to_koji_pkgowner': True,
            'email_domain': MOCK_EMAIL_DOMAIN
        }

        workflow = WF()

        openshift_map = {'url': 'https://something.com'}
        smtp_map = {
            'from_address': '*****@*****.**',
            'host': 'smtp.bar.com',
            'send_to_submitter': True,
            'send_to_pkg_owner': True,
            'domain': MOCK_EMAIL_DOMAIN,
        }
        workflow.plugin_workspace[ReactorConfigPlugin.key] = {}
        workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\
            ReactorConfig({'version': 1, 'smtp': smtp_map, 'openshift': openshift_map})
        add_koji_map_in_workflow(workflow, hub_url='/', root_url='',
                                 ssl_certs_dir='/certs')

        p = SendMailPlugin(None, workflow, **kwargs)
        receivers = p._get_receivers_list()
        assert sorted(receivers) == sorted(expected_receivers)

        if has_kerberos:
            assert p.submitter == MOCK_KOJI_SUBMITTER_EMAIL
        else:
            assert p.submitter == MOCK_KOJI_SUBMITTER_GENERATED
    def test_koji_recepients_exception(self, exception_location, expected_receivers, workflow):
        if exception_location == 'empty_owner':
            koji_build_id = None
        else:
            koji_build_id = MOCK_KOJI_BUILD_ID

        has_kerberos = exception_location != 'empty_email_domain'
        session = MockedClientSession('', has_kerberos=has_kerberos)
        if exception_location == 'koji_connection':
            (flexmock(session)
                .should_receive('ssl_login')
                .and_raise(RuntimeError, "xyz"))
        elif exception_location == 'submitter':
            (flexmock(session)
                .should_receive('getTaskInfo')
                .and_raise(RuntimeError, "xyz"))
        elif exception_location == 'owner':
            (flexmock(session)
                .should_receive('getPackageConfig')
                .and_raise(RuntimeError, "xyz"))

        flexmock(koji, ClientSession=lambda hub, opts: session, PathInfo=MockedPathInfo)

        kwargs = {
            'url': 'https://something.com',
            'smtp_host': 'smtp.bar.com',
            'from_address': '*****@*****.**',
            'to_koji_submitter': True,
            'to_koji_pkgowner': True
        }
        smtp_map = {
            'from_address': '*****@*****.**',
            'host': 'smtp.bar.com',
            'send_to_submitter': True,
            'send_to_pkg_owner': True,
        }
        if exception_location != 'empty_email_domain':
            kwargs['email_domain'] = MOCK_EMAIL_DOMAIN
            smtp_map['domain'] = MOCK_EMAIL_DOMAIN

        workflow.data.postbuild_results[KojiImportPlugin.key] = koji_build_id
        if exception_location == 'empty_submitter':
            workflow.user_params['koji_task_id'] = None
        else:
            workflow.user_params['koji_task_id'] = MOCK_KOJI_TASK_ID
        rcm = {'version': 1, 'smtp': smtp_map, 'openshift': {'url': 'https://something.com'}}
        workflow.conf = Configuration(raw_config=rcm)
        add_koji_map_in_workflow(workflow, hub_url='/', root_url='',
                                 ssl_certs_dir='/certs')

        p = SendMailPlugin(workflow, **kwargs)
        if not expected_receivers:
            with pytest.raises(RuntimeError):
                p._get_receivers_list()
        else:
            receivers = p._get_receivers_list()
            assert sorted(receivers) == sorted(expected_receivers)
    def test_get_receivers_list_raises_unless_GitSource(self):
        class WF(object):
            source = None
        p = SendMailPlugin(None, WF())
        flexmock(p).should_receive('_get_component_label').and_return('foo')

        with pytest.raises(PluginFailedException) as e:
            p._get_receivers_list()
        assert str(e.value) == 'Source is not of type "GitSource", panic!'
Beispiel #18
0
    def test_get_receivers_list_raises_unless_GitSource(self):
        class WF(object):
            source = None
        p = SendMailPlugin(None, WF())
        flexmock(p).should_receive('_get_component_label').and_return('foo')

        with pytest.raises(PluginFailedException) as e:
            p._get_receivers_list()
        assert str(e.value) == 'Source is not of type "GitSource", panic!'
 def test_should_send(self, rebuild, success, auto_canceled,
                      manual_canceled, send_on, expected):
     p = SendMailPlugin(None,
                        None,
                        smtp_host='smtp.bar.com',
                        from_address='*****@*****.**',
                        send_on=send_on)
     assert p._should_send(rebuild, success, auto_canceled,
                           manual_canceled) == expected
 def test_fails_with_unknown_states(self):
     p = SendMailPlugin(None,
                        None,
                        smtp_host='smtp.bar.com',
                        from_address='*****@*****.**',
                        send_on=['unknown_state', MS])
     with pytest.raises(PluginFailedException) as e:
         p.run()
     assert str(
         e.value) == 'Unknown state(s) "unknown_state" for sendmail plugin'
    def test_skip_plugin(self, caplog, workflow):
        rcm = {'version': 1, 'openshift': {'url': 'https://something.com'}}
        workflow.conf = Configuration(raw_config=rcm)
        add_koji_map_in_workflow(workflow, hub_url='/', root_url='',
                                 ssl_certs_dir='/certs')

        p = SendMailPlugin(workflow)
        p.run()
        log_msg = 'no smtp configuration, skipping plugin'
        assert log_msg in caplog.text
    def test_get_receivers_list_request_exception(self):
        class WF(object):
            source = GitSource('git', 'foo', provider_params={'git_commit': 'foo'})
        p = SendMailPlugin(None, WF())
        flexmock(p).should_receive('_get_component_label').and_return('foo')
        flexmock(p).should_receive('_get_pdc_token').and_return('foo')
        flexmock(requests).should_receive('get').and_raise(requests.RequestException('foo'))

        with pytest.raises(RuntimeError) as e:
            p._get_receivers_list()
        assert str(e.value) == 'foo'
    def test_recepients_from_koji(self, monkeypatch, has_addit_address,
                                  has_koji_config, to_koji_submitter,
                                  to_koji_pkgowner, expected_receivers):
        class TagConf(object):
            unique_images = []

        class WF(object):
            image = util.ImageName.parse('foo/bar:baz')
            openshift_build_selflink = '/builds/blablabla'
            build_process_failed = False
            tag_conf = TagConf()
            exit_results = {KojiPromotePlugin.key: MOCK_KOJI_BUILD_ID}

        monkeypatch.setenv(
            "BUILD",
            json.dumps({
                'metadata': {
                    'labels': {
                        'koji-task-id': MOCK_KOJI_TASK_ID,
                    },
                }
            }))

        session = MockedClientSession('', has_kerberos=True)
        flexmock(koji,
                 ClientSession=lambda hub, opts: session,
                 PathInfo=MockedPathInfo)

        kwargs = {
            'url': 'https://something.com',
            'smtp_host': 'smtp.bar.com',
            'from_address': '*****@*****.**',
            'to_koji_submitter': to_koji_submitter,
            'to_koji_pkgowner': to_koji_pkgowner,
            'email_domain': MOCK_EMAIL_DOMAIN
        }
        if has_addit_address:
            kwargs['additional_addresses'] = [MOCK_ADDITIONAL_EMAIL]

        if has_koji_config:
            kwargs['koji_hub'] = ''
            kwargs['koji_proxyuser'] = None
            kwargs['koji_ssl_certs_dir'] = '/certs'
            kwargs['koji_krb_principal'] = None
            kwargs['koji_krb_keytab'] = None

        p = SendMailPlugin(None, WF(), **kwargs)

        if not expected_receivers:
            with pytest.raises(RuntimeError):
                p._get_receivers_list()
        else:
            receivers = p._get_receivers_list()
            assert sorted(receivers) == sorted(expected_receivers)
 def test_get_component_label(self, df_labels, pdc_component_df_label, expected):
     class WF(object):
         class builder(object):
             df_path = '/foo/bar'
     p = SendMailPlugin(None, WF(), pdc_component_df_label=pdc_component_df_label)
     flexmock(DockerfileParser, labels=df_labels)
     if expected is None:
         with pytest.raises(PluginFailedException):
             p._get_component_label()
     else:
         assert p._get_component_label() == expected
Beispiel #25
0
    def test_get_receivers_list_passes_verify_cert(self, value):
        class WF(object):
            source = GitSource('git', 'foo', provider_params={'git_commit': 'foo'})
        p = SendMailPlugin(None, WF(), pdc_verify_cert=value)
        flexmock(p).should_receive('_get_component_label').and_return('foo')
        flexmock(p).should_receive('_get_pdc_token').and_return('foo')
        flexmock(requests).should_receive('get').with_args(object, headers=object, params=object,
                                                           verify=value).and_raise(RuntimeError)

        with pytest.raises(RuntimeError):
            p._get_receivers_list()
Beispiel #26
0
    def test_get_receivers_list_request_exception(self):
        class WF(object):
            source = GitSource('git', 'foo', provider_params={'git_commit': 'foo'})
        p = SendMailPlugin(None, WF())
        flexmock(p).should_receive('_get_component_label').and_return('foo')
        flexmock(p).should_receive('_get_pdc_token').and_return('foo')
        flexmock(requests).should_receive('get').and_raise(requests.RequestException('foo'))

        with pytest.raises(RuntimeError) as e:
            p._get_receivers_list()
        assert str(e.value) == 'foo'
    def test_get_receivers_list_passes_verify_cert(self, value):
        class WF(object):
            source = GitSource('git', 'foo', provider_params={'git_commit': 'foo'})
        p = SendMailPlugin(None, WF(), pdc_verify_cert=value)
        flexmock(p).should_receive('_get_component_label').and_return('foo')
        flexmock(p).should_receive('_get_pdc_token').and_return('foo')
        flexmock(requests).should_receive('get').with_args(object, headers=object, params=object,
                                                           verify=value).and_raise(RuntimeError)

        with pytest.raises(RuntimeError):
            p._get_receivers_list()
Beispiel #28
0
 def test_get_component_label(self, df_labels, pdc_component_df_label, expected):
     class WF(object):
         class builder(object):
             df_path = '/foo/bar'
     p = SendMailPlugin(None, WF(), pdc_component_df_label=pdc_component_df_label)
     flexmock(DockerfileParser, labels=df_labels)
     if expected is None:
         with pytest.raises(PluginFailedException):
             p._get_component_label()
     else:
         assert p._get_component_label() == expected
    def test_get_receivers_list_passes_pdc_token(self):
        class WF(object):
            source = GitSource('git', 'foo', provider_params={'git_commit': 'foo'})
        p = SendMailPlugin(None, WF())
        flexmock(p).should_receive('_get_component_label').and_return('foo')
        flexmock(p).should_receive('_get_pdc_token').and_return('thisistoken')
        headers = {'Authorization': 'Token thisistoken'}
        flexmock(requests).should_receive('get').with_args(object, headers=headers, params=object,
                                                           verify=True).and_raise(RuntimeError)

        with pytest.raises(RuntimeError):
            p._get_receivers_list()
Beispiel #30
0
    def test_get_receivers_list_passes_pdc_token(self):
        class WF(object):
            source = GitSource('git', 'foo', provider_params={'git_commit': 'foo'})
        p = SendMailPlugin(None, WF())
        flexmock(p).should_receive('_get_component_label').and_return('foo')
        flexmock(p).should_receive('_get_pdc_token').and_return('thisistoken')
        headers = {'Authorization': 'Token thisistoken'}
        flexmock(requests).should_receive('get').with_args(object, headers=headers, params=object,
                                                           verify=True).and_raise(RuntimeError)

        with pytest.raises(RuntimeError):
            p._get_receivers_list()
    def test_run_does_nothing_if_conditions_not_met(self):
        class WF(object):
            build_failed = True
            autorebuild_canceled = False
            prebuild_results = {CheckAndSetRebuildPlugin.key: True}
            image = ImageName.parse('repo/name')
        p = SendMailPlugin(None, WF(), send_on=[MS])

        flexmock(p).should_receive('_should_send').with_args(True, False, False).and_return(False)
        flexmock(p).should_receive('_get_receivers_list').times(0)
        flexmock(p).should_receive('_send_mail').times(0)

        p.run()
Beispiel #32
0
    def test_should_send(self, rebuild, success, auto_canceled,
                         manual_canceled, send_on, expected):
        class WF(object):
            exit_results = {KojiPromotePlugin.key: MOCK_KOJI_BUILD_ID}

        kwargs = {
            'smtp_host': 'smtp.bar.com',
            'from_address': '*****@*****.**',
            'send_on': send_on,
        }
        p = SendMailPlugin(None, WF(), **kwargs)
        assert p._should_send(rebuild, success, auto_canceled,
                              manual_canceled) == expected
Beispiel #33
0
    def test_run_does_nothing_if_conditions_not_met(self):
        class WF(object):
            build_result = BuildResult(fail_reason="not built")
            autorebuild_canceled = False
            prebuild_results = {CheckAndSetRebuildPlugin.key: True}
            image = ImageName.parse('repo/name')
        p = SendMailPlugin(None, WF(), send_on=[MS])

        flexmock(p).should_receive('_should_send').with_args(True, False, False).and_return(False)
        flexmock(p).should_receive('_get_receivers_list').times(0)
        flexmock(p).should_receive('_send_mail').times(0)

        p.run()
Beispiel #34
0
    def test_get_receivers_passes_proper_params(self):
        class WF(object):
            source = GitSource('git', 'foo', provider_params={'git_commit': 'branch'})
        p = SendMailPlugin(None, WF(), pdc_contact_role='role')
        flexmock(p).should_receive('_get_component_label').and_return('component')
        flexmock(p).should_receive('_get_pdc_token').and_return('foo')

        params = {'global_component': 'component', 'dist_git_branch': 'branch', 'role': 'role'}
        flexmock(requests).should_receive('get').with_args(object, headers=object, params=params,
                                                           verify=object).\
            and_raise(requests.RequestException())

        with pytest.raises(RuntimeError):
            p._get_receivers_list()
Beispiel #35
0
    def test_run_ok(self):
        class WF(object):
            build_result = BuildResult(fail_reason="not built")
            autorebuild_canceled = False
            prebuild_results = {CheckAndSetRebuildPlugin.key: True}
            image = ImageName.parse('repo/name')
        receivers = ['*****@*****.**', '*****@*****.**']
        p = SendMailPlugin(None, WF(), send_on=[AF])

        flexmock(p).should_receive('_should_send').with_args(True, False, False).and_return(True)
        flexmock(p).should_receive('_get_receivers_list').and_return(receivers)
        flexmock(p).should_receive('_send_mail').with_args(receivers, six.text_type, six.text_type)

        p.run()
    def test_run_ok(self):
        class WF(object):
            build_failed = True
            autorebuild_canceled = False
            prebuild_results = {CheckAndSetRebuildPlugin.key: True}
            image = ImageName.parse('repo/name')
        receivers = ['*****@*****.**', '*****@*****.**']
        p = SendMailPlugin(None, WF(), send_on=[AF])

        flexmock(p).should_receive('_should_send').with_args(True, False, False).and_return(True)
        flexmock(p).should_receive('_get_receivers_list').and_return(receivers)
        flexmock(p).should_receive('_send_mail').with_args(receivers, six.text_type, six.text_type)

        p.run()
    def test_get_receivers_passes_proper_params(self):
        class WF(object):
            source = GitSource('git', 'foo', provider_params={'git_commit': 'branch'})
        p = SendMailPlugin(None, WF(), pdc_contact_role='role')
        flexmock(p).should_receive('_get_component_label').and_return('component')
        flexmock(p).should_receive('_get_pdc_token').and_return('foo')

        params = {'global_component': 'component', 'dist_git_branch': 'branch', 'role': 'role'}
        flexmock(requests).should_receive('get').with_args(object, headers=object, params=params,
                                                           verify=object).\
            and_raise(requests.RequestException())

        with pytest.raises(RuntimeError):
            p._get_receivers_list()
Beispiel #38
0
    def test_get_receivers_list_wrong_status_code(self):
        class WF(object):
            source = GitSource('git', 'foo', provider_params={'git_commit': 'foo'})
        p = SendMailPlugin(None, WF())
        flexmock(p).should_receive('_get_component_label').and_return('foo')
        flexmock(p).should_receive('_get_pdc_token').and_return('foo')

        class R(object):
            status_code = 404
            text = 'bazinga!'
        flexmock(requests).should_receive('get').and_return(R())

        with pytest.raises(RuntimeError) as e:
            p._get_receivers_list()
        assert str(e.value) == 'PDC returned non-200 status code (404), see referenced build log'
    def test_run_fails_to_obtain_receivers(self):
        class WF(object):
            build_failed = True
            autorebuild_canceled = False
            prebuild_results = {CheckAndSetRebuildPlugin.key: True}
            image = ImageName.parse('repo/name')
        error_addresses = ['*****@*****.**']
        p = SendMailPlugin(None, WF(), send_on=[AF], error_addresses=error_addresses)

        flexmock(p).should_receive('_should_send').with_args(True, False, False).and_return(True)
        flexmock(p).should_receive('_get_receivers_list').and_raise(RuntimeError())
        flexmock(p).should_receive('_send_mail').with_args(error_addresses, six.text_type,
                                                           six.text_type)

        p.run()
Beispiel #40
0
    def test_run_fails_to_obtain_receivers(self):
        class WF(object):
            build_result = BuildResult(fail_reason="not built")
            autorebuild_canceled = False
            prebuild_results = {CheckAndSetRebuildPlugin.key: True}
            image = ImageName.parse('repo/name')
        error_addresses = ['*****@*****.**']
        p = SendMailPlugin(None, WF(), send_on=[AF], error_addresses=error_addresses)

        flexmock(p).should_receive('_should_send').with_args(True, False, False).and_return(True)
        flexmock(p).should_receive('_get_receivers_list').and_raise(RuntimeError())
        flexmock(p).should_receive('_send_mail').with_args(error_addresses, six.text_type,
                                                           six.text_type)

        p.run()
    def test_get_receivers_list_wrong_status_code(self):
        class WF(object):
            source = GitSource('git', 'foo', provider_params={'git_commit': 'foo'})
        p = SendMailPlugin(None, WF())
        flexmock(p).should_receive('_get_component_label').and_return('foo')
        flexmock(p).should_receive('_get_pdc_token').and_return('foo')

        class R(object):
            status_code = 404
            text = 'bazinga!'
        flexmock(requests).should_receive('get').and_return(R())

        with pytest.raises(RuntimeError) as e:
            p._get_receivers_list()
        assert str(e.value) == 'PDC returned non-200 status code (404), see referenced build log'
Beispiel #42
0
    def test_generated_email(self, monkeypatch, has_kerberos,
                             expected_receivers):
        class TagConf(object):
            unique_images = []

        class WF(object):
            image = util.ImageName.parse('foo/bar:baz')
            openshift_build_selflink = '/builds/blablabla'
            build_process_failed = False
            tag_conf = TagConf()
            exit_results = {KojiPromotePlugin.key: MOCK_KOJI_BUILD_ID}

        monkeypatch.setenv(
            "BUILD",
            json.dumps({
                'metadata': {
                    'labels': {
                        'koji-task-id': MOCK_KOJI_TASK_ID,
                    },
                }
            }))

        session = MockedClientSession('', has_kerberos=has_kerberos)
        flexmock(koji,
                 ClientSession=lambda hub, opts: session,
                 PathInfo=MockedPathInfo)

        kwargs = {
            'url': 'https://something.com',
            'smtp_host': 'smtp.bar.com',
            'from_address': '*****@*****.**',
            'to_koji_submitter': True,
            'to_koji_pkgowner': True,
            'email_domain': MOCK_EMAIL_DOMAIN,
            'koji_hub': '',
            'koji_proxyuser': None,
            'koji_ssl_certs_dir': '/certs',
            'koji_krb_principal': None,
            'koji_krb_keytab': None
        }
        p = SendMailPlugin(None, WF(), **kwargs)
        receivers = p._get_receivers_list()
        assert sorted(receivers) == sorted(expected_receivers)

        if has_kerberos:
            assert p.submitter == MOCK_KOJI_SUBMITTER_EMAIL
        else:
            assert p.submitter == MOCK_KOJI_SUBMITTER_GENERATED
Beispiel #43
0
    def test_send_mail(self):
        p = SendMailPlugin(None, None, from_address='*****@*****.**', smtp_uri='smtp.spam.com')

        class SMTP(object):
            def sendmail(self, from_addr, to, msg):
                pass

            def quit(self):
                pass

        smtp_inst = SMTP()
        flexmock(smtplib).should_receive('SMTP').and_return(smtp_inst)
        flexmock(smtp_inst).should_receive('sendmail').\
            with_args('*****@*****.**', ['*****@*****.**'], str)
        flexmock(smtp_inst).should_receive('quit')
        p._send_mail(['*****@*****.**'], 'subject', 'body')
    def test_send_mail(self):
        p = SendMailPlugin(None, None, from_address='*****@*****.**', smtp_url='smtp.spam.com')

        class SMTP(object):
            def sendmail(self, from_addr, to, msg):
                pass

            def quit(self):
                pass

        smtp_inst = SMTP()
        flexmock(smtplib).should_receive('SMTP').and_return(smtp_inst)
        flexmock(smtp_inst).should_receive('sendmail').\
            with_args('*****@*****.**', ['*****@*****.**'], str)
        flexmock(smtp_inst).should_receive('quit')
        p._send_mail(['*****@*****.**'], 'subject', 'body')
    def test_run_ok(self, tmpdir, reactor_config_map):  # noqa
        class TagConf(object):
            unique_images = []

        class WF(object):
            autorebuild_canceled = False
            build_canceled = False
            prebuild_results = {CheckAndSetRebuildPlugin.key: True}
            image = util.ImageName.parse('repo/name')
            build_process_failed = True
            tag_conf = TagConf()
            exit_results = {}
            plugin_workspace = {}
            source = mock_source()
            builder = mock_builder()
            with open(os.path.join(str(tmpdir), 'Dockerfile'), 'wt') as df:
                df.write(MOCK_DOCKERFILE)
                setattr(builder, 'df_path', df.name)

        receivers = ['*****@*****.**', '*****@*****.**']

        workflow = WF()
        mock_store_metadata_results(workflow)

        if reactor_config_map:
            smtp_map = {
                'from_address': '*****@*****.**',
                'host': 'smtp.bar.com',
            }
            workflow.plugin_workspace[ReactorConfigPlugin.key] = {}
            workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\
                ReactorConfig({'version': 1, 'smtp': smtp_map})

        p = SendMailPlugin(None, workflow,
                           from_address='*****@*****.**', smtp_host='smtp.spam.com',
                           send_on=[AF])

        (flexmock(p).should_receive('_should_send')
         .with_args(True, False, False, False).and_return(True))
        flexmock(p).should_receive('_get_receivers_list').and_return(receivers)
        flexmock(p).should_receive('_fetch_log_files').and_return(None)
        flexmock(p).should_receive('_send_mail').with_args(receivers,
                                                           six.text_type, six.text_type, None)

        p.run()
    def test_run_fails_to_obtain_receivers(self, reactor_config_map):  # noqa
        class TagConf(object):
            unique_images = []

        class WF(object):
            autorebuild_canceled = False
            build_canceled = False
            prebuild_results = {CheckAndSetRebuildPlugin.key: True}
            image = util.ImageName.parse('repo/name')
            build_process_failed = True
            tag_conf = TagConf()
            exit_results = {}
            plugin_workspace = {}
            source = mock_source()

        error_addresses = ['*****@*****.**']
        workflow = WF()
        mock_store_metadata_results(workflow)

        if reactor_config_map:
            smtp_map = {
                'from_address': '*****@*****.**',
                'host': 'smtp.bar.com',
                'error_addresses': ['*****@*****.**'],
            }
            workflow.plugin_workspace[ReactorConfigPlugin.key] = {}
            workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\
                ReactorConfig({'version': 1, 'smtp': smtp_map})

        p = SendMailPlugin(None, workflow,
                           from_address='*****@*****.**', smtp_host='smtp.spam.com',
                           send_on=[AF], error_addresses=error_addresses)

        (flexmock(p).should_receive('_should_send')
            .with_args(True, False, False, False).and_return(True))
        flexmock(p).should_receive('_get_receivers_list').and_raise(RuntimeError())
        flexmock(p).should_receive('_fetch_log_files').and_return(None)
        flexmock(p).should_receive('_get_image_name_and_repos').and_return(('foobar',
                                                                           ['foo/bar:baz',
                                                                            'foo/bar:spam']))
        flexmock(p).should_receive('_send_mail').with_args(error_addresses,
                                                           six.text_type, six.text_type, None)

        p.run()
    def test_get_receivers_pdc_actually_responds(self, pdc_response, pdc_contact_role, expected):
        class WF(object):
            source = GitSource('git', 'foo', provider_params={'git_commit': 'foo'})
        p = SendMailPlugin(None, WF(), pdc_contact_role=pdc_contact_role)
        flexmock(p).should_receive('_get_component_label').and_return('foo')
        flexmock(p).should_receive('_get_pdc_token').and_return('foo')

        class R(object):
            status_code = 200

            def json(self):
                return pdc_response
        flexmock(requests).should_receive('get').and_return(R())

        if isinstance(expected, str):
            with pytest.raises(RuntimeError) as e:
                p._get_receivers_list()
            assert str(e.value) == expected
        else:
            assert p._get_receivers_list() == expected
    def test_fails_with_unknown_states(self, reactor_config_map):  # noqa
        class WF(object):
            exit_results = {}
            plugin_workspace = {}

        workflow = WF()
        if reactor_config_map:
            smtp_map = {
                'from_address': '*****@*****.**',
                'host': 'smtp.spam.com',
            }
            workflow.plugin_workspace[ReactorConfigPlugin.key] = {}
            workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\
                ReactorConfig({'version': 1, 'smtp': smtp_map})

        p = SendMailPlugin(None, workflow,
                           smtp_host='smtp.bar.com', from_address='*****@*****.**',
                           send_on=['unknown_state', MS])
        with pytest.raises(PluginFailedException) as e:
            p.run()
        assert str(e.value) == 'Unknown state(s) "unknown_state" for sendmail plugin'
    def test_send_mail(self, throws_exception, reactor_config_map):
        class WF(object):
            exit_results = {}
            plugin_workspace = {}

        workflow = WF()
        if reactor_config_map:
            smtp_map = {
                'from_address': '*****@*****.**',
                'host': 'smtp.bar.com',
            }
            workflow.plugin_workspace[ReactorConfigPlugin.key] = {}
            workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\
                ReactorConfig({'version': 1, 'smtp': smtp_map})

        p = SendMailPlugin(None, workflow, from_address='*****@*****.**', smtp_host='smtp.spam.com')

        class SMTP(object):
            def sendmail(self, from_addr, to, msg):
                pass

            def quit(self):
                pass

        smtp_inst = SMTP()
        flexmock(smtplib).should_receive('SMTP').and_return(smtp_inst)
        sendmail_chain = (flexmock(smtp_inst).should_receive('sendmail').
                          with_args('*****@*****.**', ['*****@*****.**'], str))
        if throws_exception:
            sendmail_chain.and_raise(smtplib.SMTPException, "foo")
        flexmock(smtp_inst).should_receive('quit')

        if throws_exception:
            with pytest.raises(SMTPException) as e:
                p._send_mail(['*****@*****.**'], 'subject', 'body')
            assert str(e.value) == 'foo'
        else:
            p._send_mail(['*****@*****.**'], 'subject', 'body')
    def test_get_receiver_list(self, monkeypatch, additional_addresses, expected_receivers,
                               reactor_config_map):
        class TagConf(object):
            unique_images = []

        class WF(object):
            image = util.ImageName.parse('foo/bar:baz')
            openshift_build_selflink = '/builds/blablabla'
            build_process_failed = False
            autorebuild_canceled = False
            build_canceled = False
            tag_conf = TagConf()
            exit_results = {
                KojiPromotePlugin.key: MOCK_KOJI_BUILD_ID
            }
            prebuild_results = {}
            plugin_workspace = {}

        monkeypatch.setenv("BUILD", json.dumps({
            'metadata': {
                'labels': {
                    'koji-task-id': MOCK_KOJI_TASK_ID,
                },
                'name': {},
            }
        }))

        session = MockedClientSession('', has_kerberos=True)
        pathinfo = MockedPathInfo('https://koji')

        flexmock(koji, ClientSession=lambda hub, opts: session, PathInfo=pathinfo)
        kwargs = {
            'url': 'https://something.com',
            'smtp_host': 'smtp.bar.com',
            'from_address': '*****@*****.**',
            'koji_root': 'https://koji/',
            'additional_addresses': additional_addresses
        }

        workflow = WF()

        if reactor_config_map:
            openshift_map = {'url': 'https://something.com'}
            koji_map = {
                'hub_url': None,
                'root_url': 'https://koji/',
                'auth': {
                    'ssl_certs_dir': '/certs',
                    'proxyuser': None,
                    'krb_principal': None,
                    'krb_keytab_path': None
                }
            }
            smtp_map = {
                'from_address': '*****@*****.**',
                'host': 'smtp.bar.com',
                'send_to_submitter': False,
                'send_to_pkg_owner': False,
                'additional_addresses': additional_addresses
            }
            workflow.plugin_workspace[ReactorConfigPlugin.key] = {}
            workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\
                ReactorConfig({'version': 1, 'smtp': smtp_map, 'koji': koji_map,
                               'openshift': openshift_map})

        p = SendMailPlugin(None, workflow, **kwargs)
        if expected_receivers is not None:
            assert sorted(expected_receivers) == sorted(p._get_receivers_list())
        else:
            with pytest.raises(RuntimeError) as ex:
                p._get_receivers_list()
                assert str(ex) == 'No recipients found'
    def test_failed_logs(self, tmpdir, monkeypatch, error_type, reactor_config_map):  # noqa
        # just test a random combination of the method inputs and hope it's ok for other
        #   combinations
        class TagConf(object):
            unique_images = []

        class WF(object):
            image = util.ImageName.parse('foo/bar:baz')
            openshift_build_selflink = '/builds/blablabla'
            build_process_failed = True
            autorebuild_canceled = False
            build_canceled = False
            tag_conf = TagConf()
            exit_results = {
                KojiPromotePlugin.key: MOCK_KOJI_BUILD_ID
            }
            prebuild_results = {}
            plugin_workspace = {}
            source = mock_source()
            builder = mock_builder()
            with open(os.path.join(str(tmpdir), 'Dockerfile'), 'wt') as df:
                df.write(MOCK_DOCKERFILE)
                setattr(builder, 'df_path', df.name)

        monkeypatch.setenv("BUILD", json.dumps({
            'metadata': {
                'labels': {
                    'koji-task-id': MOCK_KOJI_TASK_ID,
                },
                'name': {},
            }
        }))

        session = MockedClientSession('', has_kerberos=True)
        pathinfo = MockedPathInfo('https://koji')

        flexmock(OSBS).should_receive('get_orchestrator_build_logs').and_raise(error_type)

        flexmock(koji, ClientSession=lambda hub, opts: session, PathInfo=pathinfo)
        kwargs = {
            'url': 'https://something.com',
            'smtp_host': 'smtp.bar.com',
            'from_address': '*****@*****.**',
            'to_koji_submitter': True,
            'to_koji_pkgowner': False,
            'koji_hub': '/',
            'koji_root': 'https://koji/',
            'koji_proxyuser': None,
            'koji_ssl_certs_dir': '/certs',
            'koji_krb_principal': None,
            'koji_krb_keytab': None
        }

        workflow = WF()
        mock_store_metadata_results(workflow)

        if reactor_config_map:
            smtp_map = {
                'from_address': '*****@*****.**',
                'host': 'smtp.bar.com',
                'send_to_submitter': True,
                'send_to_pkg_owner': False,
            }
            koji_map = {
                'hub_url': '/',
                'root_url': 'https://koji/',
                'auth': {'ssl_certs_dir': '/certs'}
            }
            workflow.plugin_workspace[ReactorConfigPlugin.key] = {}
            workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\
                ReactorConfig({'version': 1,
                               'openshift': {'url': 'https://something.com'},
                               'smtp': smtp_map,
                               'koji': koji_map})

        p = SendMailPlugin(None, workflow, **kwargs)
        subject, body, fail_logs = p._render_mail(True, False, False, False)
        assert not fail_logs
 def test_fails_with_unknown_states(self):
     p = SendMailPlugin(None, None, send_on=['unknown_state', MS])
     with pytest.raises(PluginFailedException) as e:
         p.run()
     assert str(e.value) == 'Unknown state(s) "unknown_state" for sendmail plugin'
 def test_should_send(self, rebuild, success, canceled, send_on, expected):
     p = SendMailPlugin(None, None, send_on=send_on)
     assert p._should_send(rebuild, success, canceled) == expected
 def test_get_pdc_token(self, tmpdir):
     tokenfile = os.path.join(str(tmpdir), SendMailPlugin.PDC_TOKEN_FILE)
     p = SendMailPlugin(None, None, pdc_secret_path=str(tmpdir))
     with open(tokenfile, 'w') as f:
         f.write('thisistoken')
     assert p._get_pdc_token() == 'thisistoken'
    def test_recepients_from_koji(self, monkeypatch,
                                  has_addit_address,
                                  has_koji_config, to_koji_submitter, to_koji_pkgowner,
                                  expected_receivers, use_import, reactor_config_map):
        class TagConf(object):
            unique_images = []

        class WF(object):
            image = util.ImageName.parse('foo/bar:baz')
            openshift_build_selflink = '/builds/blablabla'
            build_process_failed = False
            tag_conf = TagConf()
            plugin_workspace = {}
            if use_import:
                exit_results = {
                    KojiImportPlugin.key: MOCK_KOJI_BUILD_ID,
                }
            else:
                exit_results = {
                    KojiPromotePlugin.key: MOCK_KOJI_BUILD_ID,
                }
            prebuild_results = {}

        monkeypatch.setenv("BUILD", json.dumps({
            'metadata': {
                'labels': {
                    'koji-task-id': MOCK_KOJI_TASK_ID,
                },
                'name': {},
            }
        }))

        session = MockedClientSession('', has_kerberos=True)
        flexmock(koji, ClientSession=lambda hub, opts: session, PathInfo=MockedPathInfo)

        kwargs = {
            'url': 'https://something.com',
            'smtp_host': 'smtp.bar.com',
            'from_address': '*****@*****.**',
            'to_koji_submitter': to_koji_submitter,
            'to_koji_pkgowner': to_koji_pkgowner,
            'email_domain': MOCK_EMAIL_DOMAIN
        }
        smtp_map = {
            'from_address': '*****@*****.**',
            'host': 'smtp.bar.com',
            'send_to_submitter': to_koji_submitter,
            'send_to_pkg_owner': to_koji_pkgowner,
            'domain': MOCK_EMAIL_DOMAIN,
        }
        if has_addit_address:
            kwargs['additional_addresses'] = [MOCK_ADDITIONAL_EMAIL]
            smtp_map['additional_addresses'] = [MOCK_ADDITIONAL_EMAIL]

        koji_map = None
        if has_koji_config:
            kwargs['koji_hub'] = '/'
            kwargs['koji_proxyuser'] = None
            kwargs['koji_ssl_certs_dir'] = '/certs'
            kwargs['koji_krb_principal'] = None
            kwargs['koji_krb_keytab'] = None
            koji_map = {
                'hub_url': '/',
                'root_url': '',
                'auth': {
                    'ssl_certs_dir': '/certs',
                }
            }

        workflow = WF()
        if reactor_config_map:
            openshift_map = {'url': 'https://something.com'}
            workflow.plugin_workspace[ReactorConfigPlugin.key] = {}
            full_config = {
                'version': 1,
                'smtp': smtp_map,
                'openshift': openshift_map,
            }
            if koji_map:
                full_config['koji'] = koji_map
            workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\
                ReactorConfig(full_config)

        p = SendMailPlugin(None, workflow, **kwargs)

        if not expected_receivers:
            with pytest.raises(RuntimeError):
                p._get_receivers_list()
        else:
            receivers = p._get_receivers_list()
            assert sorted(receivers) == sorted(expected_receivers)
    def test_render_mail(self, monkeypatch, tmpdir, autorebuild, auto_cancel,
                         manual_cancel, to_koji_submitter, has_koji_logs,
                         koji_integration, success, reactor_config_map,
                         has_store_metadata_results, annotations, has_repositories,
                         expect_error):
        log_url_cases = {
            # (koji_integration,autorebuild,success)
            (False, False, False): False,
            (False, False, True): False,
            (False, True, False): False,  # Included as attachment
            (False, True, True): False,
            (True, False, False): True,
            (True, False, True): True,
            (True, True, False): False,   # Included as attachment
            (True, True, True): False,    # Logs in Koji Build
        }

        class TagConf(object):
            unique_images = []

        git_source_url = 'git_source_url'
        git_source_ref = '123423431234123'
        VcsInfo = namedtuple('VcsInfo', ['vcs_type', 'vcs_url', 'vcs_ref'])

        class WF(object):
            image = util.ImageName.parse('foo/bar:baz')
            openshift_build_selflink = '/builds/blablabla'
            build_process_failed = False
            autorebuild_canceled = auto_cancel
            build_canceled = manual_cancel
            tag_conf = TagConf()
            exit_results = {
                KojiPromotePlugin.key: MOCK_KOJI_BUILD_ID
            }
            prebuild_results = {}
            plugin_workspace = {}
            builder = mock_builder()

            class mock_source(object):
                def get_vcs_info(self):
                    return VcsInfo(
                        vcs_type='git',
                        vcs_url=git_source_url,
                        vcs_ref=git_source_ref
                    )
            source = mock_source()

            with open(os.path.join(str(tmpdir), 'Dockerfile'), 'wt') as df:
                df.write(MOCK_DOCKERFILE)
                setattr(builder, 'df_path', df.name)

        monkeypatch.setenv("BUILD", json.dumps({
            'metadata': {
                'labels': {
                    'koji-task-id': MOCK_KOJI_TASK_ID,
                },
                'name': {},
            }
        }))

        session = MockedClientSession('', has_kerberos=True)
        pathinfo = MockedPathInfo('https://koji')
        if not has_koji_logs:
            (flexmock(pathinfo)
                .should_receive('work')
                .and_raise(RuntimeError, "xyz"))

        fake_logs = [LogEntry(None, 'orchestrator'),
                     LogEntry(None, 'orchestrator line 2'),
                     LogEntry('x86_64', 'Hurray for bacon: \u2017'),
                     LogEntry('x86_64', 'line 2')]
        flexmock(OSBS).should_receive('get_orchestrator_build_logs').and_return(fake_logs)

        flexmock(koji, ClientSession=lambda hub, opts: session, PathInfo=pathinfo)
        kwargs = {
            'url': 'https://something.com',
            'smtp_host': 'smtp.bar.com',
            'from_address': '*****@*****.**',
            'to_koji_submitter': to_koji_submitter,
            'to_koji_pkgowner': False,
            'koji_hub': '/' if koji_integration else None,
            'koji_root': 'https://koji/',
            'koji_proxyuser': None,
            'koji_ssl_certs_dir': '/certs',
            'koji_krb_principal': None,
            'koji_krb_keytab': None
        }

        workflow = WF()
        if has_store_metadata_results:
            if annotations:
                if has_repositories:
                    mock_store_metadata_results(workflow)
                else:
                    mock_store_metadata_results(workflow, {'repositories': {}})
            else:
                mock_store_metadata_results(workflow, None)

        if reactor_config_map:
            openshift_map = {'url': 'https://something.com'}
            koji_map = {
                'hub_url': '/' if koji_integration else None,
                'root_url': 'https://koji/',
                'auth': {
                    'ssl_certs_dir': '/certs',
                    'proxyuser': None,
                    'krb_principal': None,
                    'krb_keytab_path': None
                }
            }
            smtp_map = {
                'from_address': '*****@*****.**',
                'host': 'smtp.bar.com',
                'send_to_submitter': to_koji_submitter,
                'send_to_pkg_owner': False,
            }
            workflow.plugin_workspace[ReactorConfigPlugin.key] = {}
            workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\
                ReactorConfig({'version': 1, 'smtp': smtp_map, 'koji': koji_map,
                               'openshift': openshift_map})

        p = SendMailPlugin(None, workflow, **kwargs)

        # Submitter is updated in _get_receivers_list
        try:
            p._get_receivers_list()
        except RuntimeError as ex:
            # Only valid exception is a RuntimeError when there are no
            # recipients available
            assert str(ex) == 'No recipients found'

        if expect_error:
            with pytest.raises(ValueError):
                p._render_mail(autorebuild, success, auto_cancel, manual_cancel)
            return

        subject, body, logs = p._render_mail(autorebuild, success,
                                             auto_cancel, manual_cancel)

        if auto_cancel or manual_cancel:
            status = 'Canceled'
            assert not logs
        elif success:
            status = 'Succeeded'
            assert not logs
        else:
            status = 'Failed'
            # Full logs are only generated on a failed autorebuild
            assert autorebuild == bool(logs)

        if has_repositories:
            exp_subject = '%s building image foo/bar' % status
            exp_body = [
                'Image Name: foo/bar',
                'Repositories: ',
                '    foo/bar:baz',
                '    foo/bar:spam',
            ]
        else:
            exp_subject = '%s building image %s' % (status, MOCK_NAME_LABEL)
            exp_body = [
                'Image Name: ' + MOCK_NAME_LABEL,
                'Repositories: ',
            ]

        common_body = [
            'Status: ' + status,
            'Submitted by: ',
            'Source url: ' + git_source_url,
            'Source ref: ' + git_source_ref,
        ]
        exp_body.extend(common_body)

        if autorebuild:
            exp_body[-3] += '<autorebuild>'
        elif koji_integration and to_koji_submitter:
            exp_body[-3] += MOCK_KOJI_SUBMITTER_EMAIL
        else:
            exp_body[-3] += SendMailPlugin.DEFAULT_SUBMITTER

        if log_url_cases[(koji_integration, autorebuild, success)]:
            if has_koji_logs:
                exp_body.insert(-2, "Logs: https://koji/work/tasks/12345")
            else:
                exp_body.insert(-2, "Logs: https://something.com/builds/blablabla/log")

        assert subject == exp_subject
        assert body == '\n'.join(exp_body)
    def test_koji_recepients_exception(self, monkeypatch, exception_location, expected_receivers,
                                       reactor_config_map):
        class TagConf(object):
            unique_images = []

        if exception_location == 'empty_owner':
            koji_build_id = None
        else:
            koji_build_id = MOCK_KOJI_BUILD_ID

        if exception_location == 'empty_submitter':
            koji_task_id = None
        else:
            koji_task_id = MOCK_KOJI_TASK_ID

        class WF(object):
            image = util.ImageName.parse('foo/bar:baz')
            openshift_build_selflink = '/builds/blablabla'
            build_process_failed = False
            tag_conf = TagConf()
            exit_results = {
                KojiPromotePlugin.key: koji_build_id
            }
            plugin_workspace = {}

        monkeypatch.setenv("BUILD", json.dumps({
            'metadata': {
                'labels': {
                    'koji-task-id': koji_task_id,
                },
                'name': {},
            }
        }))

        has_kerberos = exception_location != 'empty_email_domain'
        session = MockedClientSession('', has_kerberos=has_kerberos)
        if exception_location == 'koji_connection':
            (flexmock(session)
                .should_receive('ssl_login')
                .and_raise(RuntimeError, "xyz"))
        elif exception_location == 'submitter':
            (flexmock(session)
                .should_receive('getTaskInfo')
                .and_raise(RuntimeError, "xyz"))
        elif exception_location == 'owner':
            (flexmock(session)
                .should_receive('getPackageConfig')
                .and_raise(RuntimeError, "xyz"))

        flexmock(koji, ClientSession=lambda hub, opts: session, PathInfo=MockedPathInfo)

        kwargs = {
            'url': 'https://something.com',
            'smtp_host': 'smtp.bar.com',
            'from_address': '*****@*****.**',
            'to_koji_submitter': True,
            'to_koji_pkgowner': True,
            'koji_hub': '/',
            'koji_proxyuser': None,
            'koji_ssl_certs_dir': '/certs',
            'koji_krb_principal': None,
            'koji_krb_keytab': None
        }
        smtp_map = {
            'from_address': '*****@*****.**',
            'host': 'smtp.bar.com',
            'send_to_submitter': True,
            'send_to_pkg_owner': True,
        }
        if exception_location != 'empty_email_domain':
            kwargs['email_domain'] = MOCK_EMAIL_DOMAIN
            smtp_map['domain'] = MOCK_EMAIL_DOMAIN

        workflow = WF()
        if reactor_config_map:
            openshift_map = {'url': 'https://something.com'}
            koji_map = {
                'hub_url': '/',
                'root_url': '',
                'auth': {
                    'ssl_certs_dir': '/certs',
                }
            }
            workflow.plugin_workspace[ReactorConfigPlugin.key] = {}
            workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\
                ReactorConfig({'version': 1, 'smtp': smtp_map, 'koji': koji_map,
                               'openshift': openshift_map})

        p = SendMailPlugin(None, workflow, **kwargs)
        if not expected_receivers:
            with pytest.raises(RuntimeError):
                p._get_receivers_list()
        else:
            receivers = p._get_receivers_list()
            assert sorted(receivers) == sorted(expected_receivers)
    def test_generated_email(self, monkeypatch, has_kerberos, expected_receivers,
                             reactor_config_map):
        class TagConf(object):
            unique_images = []

        class WF(object):
            image = util.ImageName.parse('foo/bar:baz')
            openshift_build_selflink = '/builds/blablabla'
            build_process_failed = False
            tag_conf = TagConf()
            exit_results = {
                KojiPromotePlugin.key: MOCK_KOJI_BUILD_ID
            }
            plugin_workspace = {}

        monkeypatch.setenv("BUILD", json.dumps({
            'metadata': {
                'labels': {
                    'koji-task-id': MOCK_KOJI_TASK_ID,
                },
                'name': {},
            }
        }))

        session = MockedClientSession('', has_kerberos=has_kerberos)
        flexmock(koji, ClientSession=lambda hub, opts: session, PathInfo=MockedPathInfo)

        kwargs = {
            'url': 'https://something.com',
            'smtp_host': 'smtp.bar.com',
            'from_address': '*****@*****.**',
            'to_koji_submitter': True,
            'to_koji_pkgowner': True,
            'email_domain': MOCK_EMAIL_DOMAIN,
            'koji_hub': '/',
            'koji_proxyuser': None,
            'koji_ssl_certs_dir': '/certs',
            'koji_krb_principal': None,
            'koji_krb_keytab': None
        }

        workflow = WF()
        if reactor_config_map:
            openshift_map = {'url': 'https://something.com'}
            koji_map = {
                'hub_url': '/',
                'root_url': '',
                'auth': {
                    'ssl_certs_dir': '/certs',
                }
            }
            smtp_map = {
                'from_address': '*****@*****.**',
                'host': 'smtp.bar.com',
                'send_to_submitter': True,
                'send_to_pkg_owner': True,
                'domain': MOCK_EMAIL_DOMAIN,
            }
            workflow.plugin_workspace[ReactorConfigPlugin.key] = {}
            workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\
                ReactorConfig({'version': 1, 'smtp': smtp_map, 'koji': koji_map,
                               'openshift': openshift_map})

        p = SendMailPlugin(None, workflow, **kwargs)
        receivers = p._get_receivers_list()
        assert sorted(receivers) == sorted(expected_receivers)

        if has_kerberos:
            assert p.submitter == MOCK_KOJI_SUBMITTER_EMAIL
        else:
            assert p.submitter == MOCK_KOJI_SUBMITTER_GENERATED
    def test_run_ok_and_send(self, monkeypatch, reactor_config_map):  # noqa
        class TagConf(object):
            unique_images = []

        class WF(object):
            autorebuild_canceled = False
            build_canceled = False
            prebuild_results = {CheckAndSetRebuildPlugin.key: True}
            image = util.ImageName.parse('repo/name')
            build_process_failed = True
            tag_conf = TagConf()
            exit_results = {}
            plugin_workspace = {}
            source = mock_source()

        class SMTP(object):
            def sendmail(self, from_addr, to, msg):
                pass

            def quit(self):
                pass

        monkeypatch.setenv("BUILD", json.dumps({
            'metadata': {
                'labels': {
                    'koji-task-id': MOCK_KOJI_TASK_ID,
                },
                'name': {},
            }
        }))

        workflow = WF()
        if reactor_config_map:
            smtp_map = {
                'from_address': '*****@*****.**',
                'host': 'smtp.spam.com',
            }
            workflow.plugin_workspace[ReactorConfigPlugin.key] = {}
            workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\
                ReactorConfig({'version': 1, 'smtp': smtp_map})

        receivers = ['*****@*****.**', '*****@*****.**']
        fake_logs = [LogEntry(None, 'orchestrator'),
                     LogEntry(None, 'orchestrator line 2'),
                     LogEntry('x86_64', 'Hurray for bacon: \u2017'),
                     LogEntry('x86_64', 'line 2')]
        p = SendMailPlugin(None, workflow,
                           from_address='*****@*****.**', smtp_host='smtp.spam.com',
                           send_on=[AF])

        (flexmock(p).should_receive('_should_send')
            .with_args(True, False, False, False).and_return(True))
        flexmock(p).should_receive('_get_receivers_list').and_return(receivers)
        flexmock(OSBS).should_receive('get_orchestrator_build_logs').and_return(fake_logs)
        flexmock(p).should_receive('_get_image_name_and_repos').and_return(('foobar',
                                                                           ['foo/bar:baz',
                                                                            'foo/bar:spam']))

        smtp_inst = SMTP()
        flexmock(smtplib).should_receive('SMTP').and_return(smtp_inst)
        p.run()