Ejemplo n.º 1
0
        def dynamo_table(name):
            table = Mock()
            table.name = name

            def query(**kwargs):
                if table.name in resources.dynamo:
                    if 'KeyConditionExpression' in kwargs:
                        return {
                            'Items':
                            filter_dynamo(kwargs['KeyConditionExpression'],
                                          resources.dynamo[table.name])
                        }
                return {'Items': []}

            def scan(**kwargs):
                if table.name in resources.dynamo:
                    if 'FilterExpression' in kwargs:
                        return {
                            'Items':
                            list(
                                filter(
                                    lambda x: x[kwargs['FilterExpression'].name
                                                ]['S'] == kwargs[
                                                    'FilterExpression'].value,
                                    resources.dynamo[table.name]))
                        }
                return {'Items': []}

            table.query = query
            table.scan = scan
            return table
Ejemplo n.º 2
0
 def test_initial_attach_device_on_eucalyptus(self):
     instance = Mock()
     instance.block_device_mapping = {}
     cloud_type = self.request.session.get('cloud_type')
     device = self.form_class.suggest_next_device_name(
         cloud_type, instance.block_device_mapping)
     self.assertEqual(device, '/dev/vdc')
Ejemplo n.º 3
0
 def test_next_attach_device_on_aws(self):
     instance = Mock()
     instance.block_device_mapping = {'/dev/sdf': 'foo'}
     cloud_type = self.request.session.get('cloud_type')
     device = self.form_class.suggest_next_device_name(
         cloud_type, instance.block_device_mapping)
     self.assertEqual(device, '/dev/sdg')
Ejemplo n.º 4
0
class TestGetSDTemplateNoSysop(DefaultSiteTestCase):
    """Test the get_sd_template method of the RedirectRobot class."""
    def test_with_delete_and_existing_sdtemplate(self):
        """Test with delete and existing sdtemplate."""
        options = {'delete': True, 'sdtemplate': '{{t}}'}
        bot = RedirectTestRobot('broken', **options)
        self.assertEqual(bot.sdtemplate, '{{t}}')

    @patch.object(i18n, 'twhas_key', new=Mock(return_value=True))
    @patch.object(i18n, 'twtranslate', new=Mock(return_value='{{sd_title}}'))
    def test_with_delete_and_i18n_sd(self):
        """Test with delete and i18n template."""
        bot = RedirectTestRobot('broken', delete=True)
        self.assertEqual(bot.sdtemplate, '{{sd_title}}')

    @patch.object(i18n, 'twhas_key', new=Mock(return_value=False))
    def test_with_delete_no_sd_no_i18n(self):
        """Test with delete and no i18n template."""
        bot = RedirectTestRobot('broken', delete=True)
        with patch.object(pywikibot, 'warning') as w:
            self.assertIsNone(bot.sdtemplate)
        w.assert_called_with('No speedy deletion template available.')

    def test_with_delete_and_non_existing_sdtemplate(self):
        """Test with delete and non-exisitng sdtemplate."""
        options = {'delete': True, 'sdtemplate': 'txt {{n|a}} txt'}
        bot = RedirectTestRobot('broken', **options)
        with patch.object(Page, 'exists', new=Mock(return_value=False)):
            with patch.object(pywikibot, 'warning') as w:
                self.assertIsNone(bot.sdtemplate, None)
        w.assert_called_with('No speedy deletion template "n" available.')
Ejemplo n.º 5
0
    def cursor(self):
        cursor = Mock()

        def fetchone():
            return []

        def execute(what):
            self.executes.append(what)

        cursor.execute = execute
        cursor.fetchone = fetchone
        return cursor
Ejemplo n.º 6
0
        def queue(QueueName):
            q = Mock()
            if QueueName not in resources.sqs_messages:
                resources.sqs_messages.update({QueueName: []})

            def send_message(MessageBody, MessageGroupId):
                resources.sqs_messages[QueueName].append(
                    QueueMessage(MessageGroupId, MessageBody, QueueName))

            def receive_messages(**kwargs):
                for item in resources.sqs_messages[QueueName]:
                    item.attributes['ApproximateReceiveCount'] += 1
                    yield item

            q.receive_messages = receive_messages
            q.send_message = send_message
            return q
Ejemplo n.º 7
0
 def test_with_delete_and_non_existing_sdtemplate(self):
     """Test with delete and non-exisitng sdtemplate."""
     options = {'delete': True, 'sdtemplate': 'txt {{n|a}} txt'}
     bot = RedirectTestRobot('broken', **options)
     with patch.object(Page, 'exists', new=Mock(return_value=False)):
         with patch.object(pywikibot, 'warning') as w:
             self.assertIsNone(bot.sdtemplate, None)
     w.assert_called_with('No speedy deletion template "n" available.')
Ejemplo n.º 8
0
 def test_elb_health_check_data_with_slash_ping_path(self):
     elb_conn, elb = self.make_elb()
     health_check = Mock(
         target='HTTPS:443/', interval=300, timeout=15, healthy_threshold=3, unhealthy_threshold=5)
     elb.health_check = health_check
     request = self.create_request()
     view = ELBHealthChecksView(request, elb=elb).elb_healthchecks()
     form = view.get('elb_form')
     self.assertEqual(form.ping_protocol.data, 'HTTPS')
     self.assertEqual(form.ping_port.data, 443)
     self.assertEqual(form.ping_path.data, '/')
Ejemplo n.º 9
0
class ImageFormDescriptionTestCase(BaseFormTestCase):
    form_class = ImageForm
    request = testing.DummyRequest()
    image = Mock()
    image.description = '{{ 1 + 2 }}'
    form = form_class(request, image=image)

    def test_angular_expression_escaping_on_image_update_form(self):
        self.assertNotEqual(self.form.description.data, '{{ 1 + 2 }}')
        self.assertEqual(self.form.description.data,
                         '{{ 1 + 2 }}')
Ejemplo n.º 10
0
    def client(self,
               service_name,
               region_name=None,
               api_version=None,
               use_ssl=True,
               verify=None,
               endpoint_url=None,
               aws_access_key_id=None,
               aws_secret_access_key=None,
               aws_session_token=None,
               config=None):
        client = Mock()
        client.name = service_name
        setattr(resources, service_name, client)

        def s3list_objects_v2(Bucket, Prefix):
            parts = Prefix.split('/')
            log_type = parts[0]
            batch = parts[1]
            result = []
            if Bucket in resources.buckets and log_type in resources.buckets[Bucket] and \
                    batch in resources.buckets[Bucket][log_type]:
                for item in resources.buckets[Bucket][log_type][batch]:
                    for obj in list(item.keys()):
                        result.append(obj)
            return {'KeyCount': len(result), 'Data': result}

        def s3put_object(Body, Bucket, Key, ContentType=None):
            parts = Key.split('/')
            log_type = parts[0]
            batch = parts[1]
            update_dict(resources.buckets, Bucket, log_type, batch)
            resources.buckets[Bucket][log_type][batch].append({Key: Body})

        def dynamo_put_item(TableName, Item):
            if TableName not in resources.dynamo:
                resources.dynamo[TableName] = []
            if 'uid' in Item:
                for i in range(len(resources.dynamo[TableName])):
                    if resources.dynamo[TableName][i]['uid']['S'] == Item[
                            'uid']['S']:
                        del resources.dynamo[TableName][i]
            resources.dynamo[TableName].append(Item)

        if client.name == 's3':
            client.list_objects_v2 = s3list_objects_v2
            client.put_object = s3put_object

        if client.name == 'dynamodb':
            client.put_item = dynamo_put_item
            client.create_table = lambda *args, **kwargs: None

        return client
Ejemplo n.º 11
0
 def test_elb_health_checks_tab_view(self):
     elb_conn, elb = self.make_elb()
     health_check = Mock(
         target='HTTP:80/index.html', interval=300, timeout=15, healthy_threshold=3, unhealthy_threshold=5)
     elb.health_check = health_check
     request = self.create_request()
     view = ELBHealthChecksView(request, elb=elb).elb_healthchecks()
     form = view.get('elb_form')
     self.assertEqual(view.get('elb_name'), 'test_elb')
     self.assertEqual(form.ping_protocol.data, 'HTTP')
     self.assertEqual(form.ping_port.data, 80)
     self.assertEqual(form.ping_path.data, '/index.html')
     self.assertEqual(form.passes_until_healthy.data, '3')
     self.assertEqual(form.failures_until_unhealthy.data, '5')
Ejemplo n.º 12
0
 def test_elb_health_checks_form(self):
     request = self.create_request()
     elb_conn, elb = self.make_elb()
     elb.health_check = Mock(
         interval=30,
         timeout=30,
         healthy_threshold=3,
         unhealthy_threshold=2,
         target='HTTP:80/index.html',
     )
     form = ELBHealthChecksForm(request, elb_conn=elb_conn, elb=elb)
     self.assertEqual(form.ping_protocol.data, 'HTTP')
     self.assertEqual(form.ping_port.data, 80)
     self.assertEqual(form.ping_path.data, '/index.html')
     self.assertEqual(form.time_between_pings.data, '30')
     self.assertEqual(form.response_timeout.data, 30)
     self.assertEqual(form.failures_until_unhealthy.data, '2')
     self.assertEqual(form.passes_until_healthy.data, '3')
Ejemplo n.º 13
0
 def test_initial_attach_device_on_eucalyptus(self):
     instance = Mock()
     instance.block_device_mapping = {}
     device = self.form_class.suggest_next_device_name(self.request, instance)
     self.assertEqual(device, '/dev/vdc')
Ejemplo n.º 14
0
    unittest,
    TestCase,
    DefaultDrySiteTestCase,
    WikibaseTestCase,
    ScriptMainTestCase,
)
from tests.bot_tests import TWNBotTestCase

if StdNumValidationError:
    AnyIsbnValidationException = (StdNumValidationError, IsbnExc)
else:
    AnyIsbnValidationException = IsbnExc


# Suppress ImportWarning: package stdnum.isbn not found; using scripts.isbn
@patch('pywikibot.cosmetic_changes.warn', Mock())
class TestCosmeticChangesISBN(DefaultDrySiteTestCase):
    """Test CosmeticChanges ISBN fix."""
    def test_valid_isbn(self):
        """Test ISBN."""
        cc = CosmeticChangesToolkit(self.site, namespace=0)

        text = cc.fix_ISBN(' ISBN 097522980x ')
        self.assertEqual(text, ' ISBN 0-9752298-0-X ')

        text = cc.fix_ISBN(' ISBN 9780975229804 ')
        self.assertEqual(text, ' ISBN 978-0-9752298-0-4 ')

    @unittest.expectedFailure  # T144288
    def test_valid_isbn_failing(self):
        """Test ISBN.
Ejemplo n.º 15
0

class RedirectTestRobot(RedirectRobot):
    """RedirectRobot test class."""
    @property
    def current_page(self):
        """Patch current_page to return any page."""
        return Page(self.site, 'Main', ns=4)

    @property
    def site(self):
        """Patch site to return a site object."""
        return pywikibot.Site()


@patch.object(Page, 'exists', new=Mock(return_value=True))
class TestGetSDTemplateNoSysop(DefaultSiteTestCase):
    """Test the get_sd_template method of the RedirectRobot class."""
    def test_with_delete_and_existing_sdtemplate(self):
        """Test with delete and existing sdtemplate."""
        options = {'delete': True, 'sdtemplate': '{{t}}'}
        bot = RedirectTestRobot('broken', **options)
        self.assertEqual(bot.sdtemplate, '{{t}}')

    @patch.object(i18n, 'twhas_key', new=Mock(return_value=True))
    @patch.object(i18n, 'twtranslate', new=Mock(return_value='{{sd_title}}'))
    def test_with_delete_and_i18n_sd(self):
        """Test with delete and i18n template."""
        bot = RedirectTestRobot('broken', delete=True)
        self.assertEqual(bot.sdtemplate, '{{sd_title}}')
Ejemplo n.º 16
0
 def make_alarm(resource_id, dimension_key='InstanceId', state_value='OK'):
     dimensions = {dimension_key: [resource_id]}
     return Mock(state_value=state_value, dimensions=dimensions)
Ejemplo n.º 17
0
#
# (C) Pywikibot team, 2015-2018
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals

import pywikibot
from pywikibot import BaseSite

from scripts.category import CategoryPreprocess, CategoryMoveRobot

from tests import patch, Mock
from tests.aspects import unittest, DefaultSiteTestCase, TestCase

MOCKED_USERNAME = Mock(return_value='FakeUsername')


# Temporarily set a username to circumvent NoUsername error; T161692
@patch.object(BaseSite, 'username', new=MOCKED_USERNAME)
class CfdActions(DefaultSiteTestCase):
    """Test CFD (Categories for deletion) actions."""
    def test_strip_cfd_templates_does_nothing_when_no_templates(self):
        """Test that when there are no CFD templates, the page text is not changed."""
        bot = CategoryMoveRobot(oldcat='Old', newcat='New')
        bot.newcat.text = "Nothing should change.\n\nAnother line."
        bot._strip_cfd_templates(commit=False)
        self.assertEqual(bot.newcat.text,
                         "Nothing should change.\n\nAnother line.")

    def test_strip_cfd_templates_with_spaces_in_comments(self):
Ejemplo n.º 18
0
 def test_next_attach_device_on_aws(self):
     instance = Mock()
     instance.block_device_mapping = {'/dev/sdf': 'foo'}
     cloud_type = self.request.session.get('cloud_type')
     device = self.form_class.suggest_next_device_name(cloud_type, instance.block_device_mapping)
     self.assertEqual(device, '/dev/sdg')
Ejemplo n.º 19
0
 def test_initial_attach_device_on_eucalyptus(self):
     instance = Mock()
     instance.block_device_mapping = {}
     cloud_type = self.request.session.get('cloud_type')
     device = self.form_class.suggest_next_device_name(cloud_type, instance.block_device_mapping)
     self.assertEqual(device, '/dev/vdc')
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals

import pywikibot
from pywikibot import site, Page, i18n

from scripts.redirect import RedirectRobot

from tests import Mock, patch
from tests.aspects import DefaultSiteTestCase


# To make `self.site.logged_in(sysop=True)` always return False
@patch.object(site.APISite, 'logged_in', new=Mock(return_value=False))
@patch.object(Page, 'exists', new=Mock(return_value=True))
class TestGetSDTemplateNoSysop(DefaultSiteTestCase):
    """Test the get_sd_template method of the RedirectRobot class."""
    def test_with_delete_and_existing_sdtemplate(self):
        """Test with delete and existing sdtemplate."""
        options = {'delete': True, 'sdtemplate': '{{t}}'}
        bot = RedirectRobot('broken', **options)
        self.assertEqual(bot.sdtemplate, '{{t}}')

    @patch.object(i18n, 'twhas_key', new=Mock(return_value=True))
    @patch.object(i18n, 'twtranslate', new=Mock(return_value='{{sd_title}}'))
    def test_with_delete_and_i18n_sd(self):
        """Test with delete and i18n template."""
        bot = RedirectRobot('broken', delete=True)
        self.assertEqual(bot.sdtemplate, '{{sd_title}}')
Ejemplo n.º 21
0
from boto3 import Session as _Session

from tests import Mock
from flask_mail import Message as _Message, Mail as _Mail

resources = Mock()
resources.buckets = {}
resources.sqs_messages = {}
resources.queries = []
resources.dynamo = {}
resources.mails = []
resources.socketio = []
resources.requests = []


class Session(_Session):
    def __init__(self, **kwargs):
        self.parent = super(Session, self)
        self.parent.__init__(**kwargs)
        for key, value in kwargs.items():
            setattr(resources, key, value)

    def resource(self,
                 service_name,
                 region_name=None,
                 api_version=None,
                 use_ssl=True,
                 verify=None,
                 endpoint_url=None,
                 aws_access_key_id=None,
                 aws_secret_access_key=None,
Ejemplo n.º 22
0
    def resource(self,
                 service_name,
                 region_name=None,
                 api_version=None,
                 use_ssl=True,
                 verify=None,
                 endpoint_url=None,
                 aws_access_key_id=None,
                 aws_secret_access_key=None,
                 aws_session_token=None,
                 config=None):
        resource = Mock()
        setattr(resources, service_name, resource)

        def queue(QueueName):
            q = Mock()
            if QueueName not in resources.sqs_messages:
                resources.sqs_messages.update({QueueName: []})

            def send_message(MessageBody, MessageGroupId):
                resources.sqs_messages[QueueName].append(
                    QueueMessage(MessageGroupId, MessageBody, QueueName))

            def receive_messages(**kwargs):
                for item in resources.sqs_messages[QueueName]:
                    item.attributes['ApproximateReceiveCount'] += 1
                    yield item

            q.receive_messages = receive_messages
            q.send_message = send_message
            return q

        def dynamo_table(name):
            table = Mock()
            table.name = name

            def query(**kwargs):
                if table.name in resources.dynamo:
                    if 'KeyConditionExpression' in kwargs:
                        return {
                            'Items':
                            filter_dynamo(kwargs['KeyConditionExpression'],
                                          resources.dynamo[table.name])
                        }
                return {'Items': []}

            def scan(**kwargs):
                if table.name in resources.dynamo:
                    if 'FilterExpression' in kwargs:
                        return {
                            'Items':
                            list(
                                filter(
                                    lambda x: x[kwargs['FilterExpression'].name
                                                ]['S'] == kwargs[
                                                    'FilterExpression'].value,
                                    resources.dynamo[table.name]))
                        }
                return {'Items': []}

            table.query = query
            table.scan = scan
            return table

        resource.get_queue_by_name = queue
        resource.Table = dynamo_table
        return resource
Ejemplo n.º 23
0
 def test_next_attach_device_on_aws(self):
     instance = Mock()
     instance.block_device_mapping = {'/dev/sdf': 'foo'}
     device = self.form_class.suggest_next_device_name(self.request, instance)
     self.assertEqual(device, '/dev/sdg')