示例#1
0
    def test_ask_credentials_when_cached_credentials_are_not_working(self):
        cached_credentials = ["cached_username", "cached_password"]
        interactive_credentials = [
            ["interactive_username", "interactive_password"]
        ]
        expected_token = "test token"
        exception = xmlrpc_client.Fault(
            2950,
            "Either the password or username is incorrect")
        login_mocked_return_values = [
            exception,      # raised by the cached credentials
            expected_token  # 1st pair of interactive credentials works fine
        ]

        auth = Authenticator(
            connection=self.mock_connection,
            user=cached_credentials[0],
            password=cached_credentials[1],
            token=None)

        auth.connection.auth.login.side_effect = lambda username, password: _side_effect_return_from_list(
            login_mocked_return_values)

        auth._get_credentials_interactive = MagicMock()
        auth._get_credentials_interactive.side_effect = lambda: _set_username_and_password(
            auth, interactive_credentials)

        self.assertEqual(expected_token, auth.token())
        self.assertEqual(1, auth._get_credentials_interactive.call_count)

        expected_login_calls = []
        for c in [cached_credentials] + interactive_credentials:
            expected_login_calls.append(call.login(c[0], c[1]))
        auth.connection.auth.assert_has_calls(expected_login_calls)
        self.assertEqual(2, auth.connection.auth.login.call_count)
示例#2
0
async def test_get_announce_url_fails(mocker):
    tracker = NblTracker(options={
        'username': '******',
        'password': '******',
        'base_url': 'http://nbl.local',
        'announce': 'http://nbl.local/announce',
        'exclude': 'some files',
    }, )

    mocks = AsyncMock(
        get=mocker.patch('upsies.utils.http.get',
                         AsyncMock(return_value='<html>foo</html>', )),
        post=mocker.patch('upsies.utils.http.post', AsyncMock()),
        login=AsyncMock(),
        logout=AsyncMock(),
    )
    mocker.patch.object(tracker, 'login', mocks.login)
    mocker.patch.object(tracker, 'logout', mocks.logout)

    exp_cmd = f'{__project_name__} set trackers.{tracker.name}.announce_url <YOUR URL>'
    with pytest.raises(
            errors.RequestError,
            match=rf'^Failed to find announce URL - set it manually: {exp_cmd}$'
    ):
        await tracker.get_announce_url()
    assert mocks.mock_calls == [
        call.login(),
        call.get('http://nbl.local' + NblTracker._url_path['upload'],
                 cache=False,
                 user_agent=True),
        call.logout(),
    ]
示例#3
0
async def test_get_announce_url_succeeds(mocker):
    tracker = NblTracker(options={
        'username': '******',
        'password': '******',
        'base_url': 'http://nbl.local',
        'announce': 'http://nbl.local/announce',
        'exclude': 'some files',
    }, )

    mocks = AsyncMock(
        get=mocker.patch(
            'upsies.utils.http.get',
            AsyncMock(return_value='''
            <html>
                <input type="text" value="https://nbl.local:123/l33tb34f/announce">
            </html>
            ''', )),
        post=mocker.patch('upsies.utils.http.post', AsyncMock()),
        login=AsyncMock(),
        logout=AsyncMock(),
    )
    mocker.patch.object(tracker, 'login', mocks.login)
    mocker.patch.object(tracker, 'logout', mocks.logout)

    announce_url = await tracker.get_announce_url()
    assert announce_url == 'https://nbl.local:123/l33tb34f/announce'
    assert mocks.mock_calls == [
        call.login(),
        call.get('http://nbl.local' + NblTracker._url_path['upload'],
                 cache=False,
                 user_agent=True),
        call.logout(),
    ]
示例#4
0
async def test_get_announce_url_succeeds(mocker):
    tracker = BbTracker(options={'base_url': 'http://bb.local'})

    mocks = AsyncMock(
        get=mocker.patch('upsies.utils.http.get', AsyncMock(
            return_value='''
            <html>
                <input type="text" value="https://bb.local:123/l33tb34f/announce">
            </html>
            ''',
        )),
        post=mocker.patch('upsies.utils.http.post', AsyncMock()),
        login=AsyncMock(),
        logout=AsyncMock(),
    )
    mocker.patch.object(tracker, 'login', mocks.login)
    mocker.patch.object(tracker, 'logout', mocks.logout)

    announce_url = await tracker.get_announce_url()
    assert announce_url == 'https://bb.local:123/l33tb34f/announce'
    assert mocks.mock_calls == [
        call.login(),
        call.get('http://bb.local' + BbTracker._url_path['upload'], cache=False, user_agent=True),
        call.logout(),
    ]
    def test_givenAEmailNotificator_whenSendNotificationDoesNotWork_thenWaitTimer(
            self):
        a_mock_smtp_server = MagicMock()
        a_mock_smtp_server.sendmail.side_effect = SMTPRecipientsRefused(
            "a_fake_recipients")

        email_notificator = EmailNotificator(
            self.a_fake_sender_email,
            self.a_fake_sender_login_credential,
            self.a_fake_destination_email,
            a_mock_smtp_server,
            on_error_sleep_time=1,
        )

        with self.assertWarns(Warning):
            email_notificator.send_notification(self.a_notification)

            expected_content = f"Subject: {self.default_subject_message}\n\n{self.a_notification}"
            post_call = [
                call.starttls(),
                call.login(self.a_fake_sender_email,
                           self.a_fake_sender_login_credential),
                call.sendmail(
                    from_addr=self.a_fake_sender_email,
                    to_addrs=self.a_fake_destination_email,
                    msg=expected_content,
                ),
                call.sendmail(
                    from_addr=self.a_fake_sender_email,
                    to_addrs=self.a_fake_destination_email,
                    msg=expected_content,
                ),
            ]

            a_mock_smtp_server.assert_has_calls(post_call)
    def test_givenAEmailNotificator_whenSendNotificationWithSubject_thenSendMessageWithSubject(
        self, ):
        a_mock_smtp_server = MagicMock()
        email_notificator = EmailNotificator(
            self.a_fake_sender_email,
            self.a_fake_sender_login_credential,
            self.a_fake_destination_email,
            a_mock_smtp_server,
        )

        a_user_formatted_subject = "Here a subject"
        email_notificator.send_notification(self.a_notification,
                                            subject=a_user_formatted_subject)

        expected_content = f"Subject: {a_user_formatted_subject}\n\n{self.a_notification}"
        post_call = [
            call.starttls(),
            call.login(self.a_fake_sender_email,
                       self.a_fake_sender_login_credential),
            call.sendmail(
                from_addr=self.a_fake_sender_email,
                to_addrs=self.a_fake_destination_email,
                msg=expected_content,
            ),
        ]

        a_mock_smtp_server.assert_has_calls(post_call)
    def test_givenAEmailNotificator_whenSendNotification_thenSendMessageDefaultSubject(
        self, ):
        a_mock_smtp_server = MagicMock()
        email_notificator = EmailNotificator(
            self.a_fake_sender_email,
            self.a_fake_sender_login_credential,
            self.a_fake_destination_email,
            a_mock_smtp_server,
        )

        email_notificator.send_notification(self.a_notification)

        expected_content = f"Subject: {self.default_subject_message}\n\n{self.a_notification}"
        post_call = [
            call.starttls(),
            call.login(self.a_fake_sender_email,
                       self.a_fake_sender_login_credential),
            call.sendmail(
                from_addr=self.a_fake_sender_email,
                to_addrs=self.a_fake_destination_email,
                msg=expected_content,
            ),
        ]

        a_mock_smtp_server.assert_has_calls(post_call)
示例#8
0
def test_login(caplog, store_mock):
    """Simple login case."""
    caplog.set_level(logging.INFO, logger="charmcraft.commands")

    LoginCommand('group').run(noargs)

    assert store_mock.mock_calls == [
        call.login(),
    ]
    assert ["Login successful."] == [rec.message for rec in caplog.records]
示例#9
0
 def test_login_called_if_smtp_type_not_insecure(self, monkeypatch):
     smtp = MagicMock()
     monkeypatch.setattr("prefect.tasks.notifications.email_task.smtplib",
                         smtp)
     t = EmailTask(msg="")
     with set_temporary_config({"cloud.use_local_secrets": True}):
         with context(
             {"secrets": dict(EMAIL_USERNAME="******", EMAIL_PASSWORD="******")}):
             res = t.run()
     assert call.login("foo",
                       "bar") in smtp.SMTP_SSL.return_value.mock_calls
示例#10
0
    def test_should_raise_an_exception_after_the_user_provides_wrong_credentials_three_times_in_a_row(self):
        interactive_credentials = [
            ["interactive_username1", "interactive_password1"],
            ["interactive_username2", "interactive_password2"],
            ["interactive_username3", "interactive_password3"]
        ]
        cached_credentials = ["cached_username", "cached_password"]
        exception = xmlrpc_client.Fault(
            2950,
            "Either the password or username is incorrect")
        login_mocked_return_values = [
            exception,  # raised by the cached credentials
            exception,  # raised by the 1st pair of interactive credentials
            exception,  # raised by the 2nd pair of interactive credentials
            exception   # raised by the 3rd pair of interactive credentials
        ]

        auth = Authenticator(
            connection=self.mock_connection,
            user=cached_credentials[0],
            password=cached_credentials[1],
            token=None)
        auth.connection.auth.login.side_effect = lambda username, password: _side_effect_return_from_list(
            login_mocked_return_values)

        auth._get_credentials_interactive = MagicMock()
        auth._get_credentials_interactive.side_effect = lambda: _set_username_and_password(
            auth, interactive_credentials)

        with self.assertRaises(MaximumNumberOfAuthenticationFailures):
            auth.token()
        self.assertEqual(
            Authenticator.MAX_NUM_OF_CREDENTIAL_FAILURES_ALLOWED,
            auth._get_credentials_interactive.call_count)

        expected_login_calls = []
        for c in [cached_credentials] + interactive_credentials:
            expected_login_calls.append(call.login(c[0], c[1]))
        auth.connection.auth.assert_has_calls(expected_login_calls)
        self.assertEqual(4, auth.connection.auth.login.call_count)
示例#11
0
    def test_keep_asking_credentials_if_they_are_wrong(self):
        interactive_credentials = [
            ["interactive_username1", "interactive_password1"],
            ["interactive_username2", "interactive_password2"],
            ["interactive_username3", "interactive_password3"]
        ]
        expected_token = "test token"
        exception = xmlrpc_client.Fault(
            2950,
            "Either the password or username is incorrect")
        login_mocked_return_values = [
            exception,      # raised by the 1st pair of interactive credentials
            exception,      # raised by the 2nd pair of interactive credentials
            expected_token  # 3rd pair of interactive credentials works fine
        ]

        # Note well: there are no cached credentials
        auth = Authenticator(
            connection=self.mock_connection,
            user=None,
            password=None,
            token=None)
        auth.connection.auth.login.side_effect = lambda username, password: _side_effect_return_from_list(
            login_mocked_return_values)

        auth._get_credentials_interactive = MagicMock()
        auth._get_credentials_interactive.side_effect = lambda: _set_username_and_password(
            auth, interactive_credentials)

        self.assertEqual(expected_token, auth.token())

        self.assertEqual(3, auth._get_credentials_interactive.call_count)

        expected_login_calls = []
        for c in interactive_credentials:
            expected_login_calls.append(call.login(c[0], c[1]))
        auth.connection.auth.assert_has_calls(expected_login_calls)
        self.assertEqual(3, auth.connection.auth.login.call_count)
示例#12
0
async def test_submit_calls_methods_and_callbacks_in_correct_order(
        job, mocker):
    mocks = Mock()
    mocks.attach_mock(job._tracker.login, 'login')
    mocks.attach_mock(job._tracker.logout, 'logout')
    mocks.attach_mock(job._tracker.upload, 'upload')
    job.signal.register('logging_in', mocks.logging_in_cb)
    job.signal.register('logged_in', mocks.logged_in_cb)
    job.signal.register('uploading', mocks.uploading_cb)
    job.signal.register('uploaded', mocks.uploaded_cb)
    job.signal.register('logging_out', mocks.logging_out_cb)
    job.signal.register('logged_out', mocks.logged_out_cb)
    await job._submit()
    assert mocks.method_calls == [
        call.logging_in_cb(),
        call.login(),
        call.logged_in_cb(),
        call.uploading_cb(),
        call.upload(job._tracker_jobs),
        call.uploaded_cb(),
        call.logging_out_cb(),
        call.logout(),
        call.logged_out_cb(),
    ]
示例#13
0
 def test_login(self, smtp_context):
     assert (call.login(user="******", password="******")
             in smtp_context.mock_calls)
示例#14
0
	def test_send_mail(self, mock_smtp):
		mock_instance = mock_smtp.return_value
		self.mm.send_mail(self.to, "message")

		smtp_calls = [call.ehlo(), call.starttls(), call.login(self.username, self.password), call.sendmail(self.from_address, self.to, "message"), call.quit()]
		mock_instance.assert_has_calls(smtp_calls, 'calls must be in the right order')