mock.MagicMock

Here are the examples of the python api mock.MagicMock taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: bsd-cloudinit
Source File: test_windows.py
View license
    def test_write_iso_file(self):
        mock_buff = mock.MagicMock()
        mock_geom = mock.MagicMock()
        mock_geom.BytesPerSector = 2

        mock_phys_disk = mock.MagicMock()
        mock_phys_disk.read.return_value = (mock_buff, 10)

        fake_path = os.path.join('fake', 'path')

        mock_phys_disk.get_geometry.return_value = mock_geom
        with mock.patch('six.moves.builtins.open', mock.mock_open(),
                        create=True) as f:
            self._config_manager._write_iso_file(mock_phys_disk, fake_path,
                                                 10)
            f().write.assert_called_once_with(mock_buff)
        mock_phys_disk.seek.assert_called_once_with(0)
        mock_phys_disk.read.assert_called_once_with(10)

Example 2

Project: chainer
Source File: test_link.py
View license
    def test_serialize(self):
        mocks = {'0': mock.MagicMock(), '1': mock.MagicMock()}
        serializer = mock.MagicMock()
        serializer.__getitem__.side_effect = lambda k: mocks[k]
        self.c1.serialize(serializer)

        self.assertEqual(serializer.call_count, 0)
        self.assertEqual(serializer.__getitem__.call_count, 2)
        serializer.__getitem__.assert_any_call('0')
        serializer.__getitem__.assert_any_call('1')

        mocks['0'].assert_called_with('x', self.l1.x.data)
        mocks['1'].assert_called_with('x', self.l2.x.data)

Example 3

Project: pulp_docker
Source File: test_importer.py
View license
    @skip.skip_broken
    def test_remove_with_tag(self, mock_repo_qs):
        units = [
            mock.MagicMock(type_id=constants.MANIFEST_TYPE_ID),
            mock.MagicMock(type_id=constants.IMAGE_TYPE_ID, unit_key={'image_id': 'foo'},
                           metadata={})
        ]
        mock_repo = mock_repo_qs.get_repo_or_missing_resource.return_value
        mock_repo.scratchpad = {u'tags': [{constants.IMAGE_TAG_KEY: 'apple',
                                           constants.IMAGE_ID_KEY: 'foo'}]}

        DockerImporter().remove_units(mock_repo, units, mock.MagicMock())

        self.assertEqual(mock_repo.scratchpad['tags'], [])

Example 4

Project: python-hwinfo
Source File: test_inspector.py
View license
    def setUp(self):
        device_a = mock.MagicMock()
        device_b = mock.MagicMock()
        device_c = mock.MagicMock()
        device_d = mock.MagicMock()
        device_e = mock.MagicMock()

        device_a.get_pci_class.return_value = '0230'
        device_b.get_pci_class.return_value = '0340'
        device_c.get_pci_class.return_value = '0210'
        device_d.get_pci_class.return_value = '0100'
        device_e.get_pci_class.return_value = '0c04'

        self.devices = [device_a, device_b, device_c, device_d, device_e]

Example 5

Project: pydenticon
Source File: test_pydenticon.py
View license
    def test_init_entropy(self):
        """
        Tests if the constructor properly checks for entropy provided by a
        digest algorithm.
        """

        # Set-up the mock instance.
        hexdigest_method = mock.MagicMock(return_value="aabb")
        digest_instance = mock.MagicMock()
        digest_instance.hexdigest = hexdigest_method

        # Set-up digest function that will always return the same digest
        # instance.
        digest_method = mock.MagicMock(return_value=digest_instance)

        # This should require 23 bits of entropy, while the digest we defined
        # provided 2*8 bits of entropy (2 bytes).
        self.assertRaises(ValueError, Generator, 5, 5, digest=digest_method)

Example 6

Project: downstream-farmer
Source File: test_unit.py
View license
    def setup_run_mocks(self):
        self.client.thread_manager = mock.MagicMock()
        self.client.thread_manager.running = True
        self.client.worker_pool = mock.MagicMock()
        self.client._get_contracts = mock.MagicMock()
        self.client._get_contracts.return_value = [self.test_contract]
        self.client._add_contract = mock.MagicMock()
        self.client.contract_thread = mock.MagicMock()
        self.client.get_total_size = mock.MagicMock()
        self.client.get_total_size.return_value = 0

Example 7

Project: thumbor
Source File: test_base_engine.py
View license
    def setUp(self):
        self.image = (
            (1, 2),
            (3, 4)
        )
        self.context = self.get_context()
        self.engine = BaseEngine(self.context)
        self.engine.flip_horizontally = mock.MagicMock()
        self.engine.flip_horizontally.side_effect = self.flip_horizontally
        self.engine.flip_vertically = mock.MagicMock()
        self.engine.flip_vertically.side_effect = self.flip_vertically
        self.engine.rotate = mock.MagicMock()
        self.engine.rotate.side_effect = self.rotate

Example 8

Project: gunicorn
Source File: test_http.py
View license
def test_http_invalid_response_header():
    """ tests whether http response headers are contains control chars """

    mocked_socket = mock.MagicMock()
    mocked_socket.sendall = mock.MagicMock()

    mocked_request = mock.MagicMock()
    response = Response(mocked_request, mocked_socket, None)

    with pytest.raises(InvalidHeader):
        response.start_response("200 OK", [('foo', 'essai\r\n')])

    response = Response(mocked_request, mocked_socket, None)
    with pytest.raises(InvalidHeaderName):
        response.start_response("200 OK", [('foo\r\n', 'essai')])

Example 9

Project: kplr
Source File: test_api.py
View license
    def setUp(self):
        self.mock_api = mock.MagicMock(spec=API)
        self.mock_api.koi.return_value = mock.MagicMock(spec=KOI)
        self.mock_api.star.return_value = mock.MagicMock(spec=Star)
        self.params = {
            "kepid": "9787239",
            "kepler_name": "Kepler-32 f",
            "koi_number": "952.05",
        }
        self.planet = Planet(self.mock_api, self.params)

Example 10

Project: docker-registry
Source File: test_checksums.py
View license
    def test_append(self):
        self.tar_sum.header_fields = tuple()
        member = mock.MagicMock(size=1)
        tarobj = mock.MagicMock(
            extractfile=mock.MagicMock(side_effect=KeyError))
        self.tar_sum.append(member, tarobj)
        self.assertEqual(len(self.tar_sum.hashes), 1)
        self.assertEqual(
            self.tar_sum.hashes[0],
            'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855')

Example 11

Project: f5-common-python
Source File: test_resource.py
View license
    def test_Collection_removal(self):
        r = Resource(mock.MagicMock())
        r._meta_data['allowed_lazy_attributes'] = []
        r._meta_data['uri'] = 'URI'
        attrs = {'put.return_value': MockResponse({u"generation": 0}),
                 'get.return_value': MockResponse({u"generation": 0})}
        mock_session = mock.MagicMock(**attrs)
        r._meta_data['bigip']._meta_data = {'icr_session': mock_session}
        r.generation = 0
        r.contained = Collection(mock.MagicMock())
        assert 'contained' in r.__dict__
        r.update(a=u"b")
        submitted = r._meta_data['bigip']. \
            _meta_data['icr_session'].put.call_args[1]['json']
        assert 'contained' not in submitted

Example 12

Project: sentry
Source File: test_retries.py
View license
    def test_policy_failure(self):
        bomb = Exception('Boom!')
        callable = mock.MagicMock(side_effect=bomb)

        retry = TimedRetryPolicy(30, delay=lambda i: 10)
        retry.clock = mock.Mock()
        retry.clock.sleep = mock.MagicMock()
        retry.clock.time = mock.MagicMock(side_effect=[0, 15, 25])

        try:
            retry(callable)
        except RetryException as exception:
            assert exception.exception is bomb
        else:
            self.fail('Expected {!r}!'.format(RetryException))

        assert callable.call_count == 2

Example 13

View license
    def test_collect_includes_with_if(self):
        mock_conditiona_block_1 = mock.MagicMock()
        mock_conditiona_block_2 = mock.MagicMock()
        mock_conditiona_block_3 = mock.MagicMock()
        node = pre_ast.If(
            conditional_blocks=[
                mock_conditiona_block_1,
                mock_conditiona_block_2,
                mock_conditiona_block_3,
            ],
        )
        mock_conditiona_block_1.accept.return_value = [33, 42]
        mock_conditiona_block_2.accept.return_value = []
        mock_conditiona_block_3.accept.return_value = ['foo', 'bar']
        actual = self.include_collector.collect_includes(node)
        expected = [33, 42, 'foo', 'bar']
        self.assertEqual(actual, expected)

Example 14

View license
  @patch.object(batchworker.ProgressReporter, 'next_progress_report_interval')
  @patch.object(batchworker.ProgressReporter, 'process_report_status_response')
  def test_progress_reporter_sends_last_update(
      self, mock_report_response, mock_next_progress):  # pylint: disable=unused-argument
    mock_work_item = mock.MagicMock()
    mock_work_executor = mock.MagicMock()
    mock_batch_worker = mock.MagicMock()
    mock_client = mock.MagicMock()
    progress_reporter = batchworker.ProgressReporter(
        mock_work_item, mock_work_executor, mock_batch_worker, mock_client)
    mock_split_result = mock.MagicMock()
    progress_reporter.dynamic_split_result_to_report = mock_split_result

    progress_reporter._stopped = True
    progress_reporter.stop_reporting_progress()
    mock_client.report_status.assert_called_with(
        mock.ANY, mock.ANY, mock.ANY, mock.ANY, mock.ANY, mock_split_result,
        exception_details=mock.ANY, source_operation_response=mock.ANY)

Example 15

Project: permabots
Source File: testcases.py
View license
    def setUp(self):
        with mock.patch("telegram.bot.Bot.set_webhook", callable=mock.MagicMock()):
            with mock.patch("kik.api.KikApi.set_configuration", callable=mock.MagicMock()):
                with mock.patch("messengerbot.MessengerClient.subscribe_app", callable=mock.MagicMock()):
                    with mock.patch("telegram.bot.Bot.get_me", callable=mock.MagicMock()) as mock_get_me:
                        user_dict = {'username': u'Microbot_test_bot', 'first_name': u'Microbot_test', 'id': 204840063}
                        mock_get_me.return_value = User(**user_dict)
                        self.bot = factories.BotFactory()
                        self.telegram_webhook_url = reverse('permabots:telegrambot', kwargs={'hook_id': self.bot.telegram_bot.hook_id})
                        self.kik_webhook_url = reverse('permabots:kikbot', kwargs={'hook_id': self.bot.kik_bot.hook_id})
                        self.messenger_webhook_url = reverse('permabots:messengerbot', kwargs={'hook_id': self.bot.messenger_bot.hook_id})
                        self.telegram_update = factories.TelegramUpdateLibFactory()
                        self._create_kik_api_message()
                        self._create_messenger_api_message()
                        self.kwargs = {'content_type': 'application/json', }

Example 16

Project: django-onmydesk
Source File: test_core.py
View license
    def setUp(self):
        self.gettempdirmocked = self._patch(
            'onmydesk.core.outputs.tempfile.gettempdir', return_value='/tmp')

        self.worksheet_mocked = mock.MagicMock()
        self.workbook_mocked = mock.MagicMock()
        self.workbook_mocked.add_worksheet.return_value = self.worksheet_mocked
        self.workbook_const_mocked = self._patch('onmydesk.core.outputs.xlsxwriter.Workbook',
                                                 return_value=self.workbook_mocked)

        self.iterable_object = [
            ('Alisson', 38),
            ('Joao', 13),
        ]

        uuid4_mocked = mock.MagicMock()
        uuid4_mocked.hex = 'asjkdlajksdlakjdlakjsdljalksdjla'
        self.uuid4_mocked = self._patch(
            'onmydesk.core.outputs.uuid4', return_value=uuid4_mocked)

Example 17

Project: falcon-cors
Source File: test_cors.py
View license
    def test_process_methods_allow_all_allowed(self):
        fake_req = mock.MagicMock()
        fake_resp = mock.MagicMock()
        fake_resource = mock.MagicMock()
        cors = CORS(allow_all_methods=True)
        cors._get_requested_method = mock.Mock(return_value='GET')
        cors._get_resource_methods = mock.Mock(return_value=['GET', 'POST'])
        cors._set_allowed_methods = mock.Mock()
        self.assertEqual(
            cors._process_methods(fake_req, fake_resp, fake_resource),
            True
        )
        cors._set_allowed_methods.assert_called_once_with(fake_resp, ['GET', 'POST'])

Example 18

Project: apispec
Source File: test_core.py
View license
    def test_multiple_definition_helpers_w_different_signatures(self, spec):
        def helper1(spec, name, spam, **kwargs):
            return mock.MagicMock()

        def helper2(spec, name, eggs, **kwargs):
            return mock.MagicMock()

        spec.register_definition_helper(helper1)
        spec.register_definition_helper(helper2)

        spec.definition('SpammitySpam', eggs=mock.MagicMock())

Example 19

Project: python-engineio
Source File: test_server.py
View license
    def test_connect_event(self):
        s = server.Server()
        s._generate_id = mock.MagicMock(return_value='123')
        mock_event = mock.MagicMock()
        s.on('connect')(mock_event)
        environ = {'REQUEST_METHOD': 'GET', 'QUERY_STRING': ''}
        start_response = mock.MagicMock()
        s.handle_request(environ, start_response)
        mock_event.assert_called_once_with('123', environ)
        self.assertEqual(len(s.sockets), 1)

Example 20

Project: postcodeinfo
Source File: test_s3_cache.py
View license
    def setUp(self):
        self.mock_key = mock.MagicMock('mock Key')
        self.mock_key.get_contents_to_filename = mock.MagicMock(return_value='contents')
        self.mock_key.set_contents_from_filename = mock.MagicMock(return_value='contents set')
        self.mock_key.delete = mock.MagicMock(return_value='deleted')
        self.root_dir = RandomTempDir()
        self.temp_file_path = self.root_dir.temp_file_path()

Example 21

View license
@pytest.fixture(autouse=True)
def patch_i18n_country_data(monkeypatch, tmpdir):
    manager_dict = {'PL': 'datÄ…', 'US': 'data'}
    all_countries = ['PL', 'US']
    data_dir = tmpdir.join('data')
    monkeypatch.setattr('i18naddress.downloader.ThreadPool', mock.MagicMock())
    monkeypatch.setattr('i18naddress.downloader.work_queue', mock.MagicMock())
    monkeypatch.setattr(
        'i18naddress.downloader.get_countries', lambda: all_countries)
    monkeypatch.setattr(
        'i18naddress.downloader.VALIDATION_DATA_DIR', str(data_dir))
    monkeypatch.setattr(
        'i18naddress.downloader.DATA_PATH',
        os.path.join(str(data_dir), '%s.json'))
    manager = mock.MagicMock()
    manager.dict.return_value = manager_dict
    monkeypatch.setattr('i18naddress.downloader.manager', manager)

Example 22

Project: ndkale
Source File: test_publisher.py
View license
    def test_publish_invalid_delay_sec(self):
        """Test publish with invalid delay_sec value."""

        sqs_inst = sqs.SQSTalk()
        sqs_inst._connection = mock.MagicMock()

        mock_publisher = publisher.Publisher(sqs_inst)
        mock_publisher._get_or_create_queue = mock.MagicMock()
        payload = {'args': [], 'kwargs': {}}

        mock_task_class = mock.MagicMock()
        mock_task_class.time_limit = 2

        delay_sec = settings.SQS_MAX_TASK_DELAY_SEC + 1
        with mock.patch('kale.message.KaleMessage') as mock_message:
            mock_message.create_message.return_value = mock.MagicMock()
            with self.assertRaises(exceptions.InvalidTaskDelayException):
                mock_publisher.publish(mock_task_class, 1, payload,
                                       delay_sec=delay_sec)

Example 23

Project: nose2
Source File: test_collector.py
View license
    def test_collector_sets_testLoader_in_session(self):
        """
        session.testLoader needs to be set so that plugins that use this
        field (like Layers) dont break.
        """
        test = collector.collector()
        mock_session = mock.MagicMock()
        mock_loader = mock.MagicMock()
        mock_runner = mock.MagicMock()
        test._get_objects = mock.Mock(return_value=(mock_session,
                                                    mock_loader,
                                                    mock_runner))
        test._collector(None)
        self.assertTrue(mock_session.testLoader is mock_loader)

Example 24

Project: uflash
Source File: test_uflash.py
View license
def test_find_microbit_nt_missing():
    """
    Simulate being on os.name == 'nt' and a disk with a volume name 'MICROBIT'
    does not exist for a micro:bit device.
    """
    mock_windll = mock.MagicMock()
    mock_windll.kernel32 = mock.MagicMock()
    mock_windll.kernel32.GetVolumeInformationW = mock.MagicMock()
    mock_windll.kernel32.GetVolumeInformationW.return_value = None
    with mock.patch('os.name', 'nt'):
        with mock.patch('os.path.exists', return_value=True):
            return_value = ctypes.create_unicode_buffer(1024)
            with mock.patch('ctypes.create_unicode_buffer',
                            return_value=return_value):
                ctypes.windll = mock_windll
                assert uflash.find_microbit() is None

Example 25

View license
    @staticmethod
    def _build_mock_cnas():
        """Builds a set of mock client network adapters."""
        cna1 = mock.MagicMock()
        cna1.loc_code, cna1.mac = 'a', 'AABBCCDDEEFF'

        cna2 = mock.MagicMock()
        cna2.loc_code, cna2.mac = 'b', 'AABBCCDDEE11'

        cna3 = mock.MagicMock()
        cna3.loc_code, cna3.mac = 'c', 'AABBCCDDEE22'

        return [cna1, cna2, cna3]

Example 26

View license
    def setUp(self):
        self._mock_wintypes = mock.MagicMock()
        self._mock_pywintypes = mock.MagicMock()
        self._mock_win32 = mock.MagicMock()
        self._moves_mock = mock.MagicMock()

        self._module_patcher = mock.patch.dict(
            'sys.modules',
            {'ctypes': self._mock_wintypes,
             'ctypes.wintypes': self._mock_wintypes,
             'pywintypes': self._mock_pywintypes,
             'win32com': self._mock_win32,
             'six.moves': self._moves_mock})
        self._module_patcher.start()
        self._winreg_mock = self._moves_mock.winreg

        winrmlistener = importlib.import_module('cloudbaseinit.plugins.'
                                                'windows.winrmlistener')
        self._winrmlistener = winrmlistener.ConfigWinRMListenerPlugin()

Example 27

View license
    def setUp(self):
        super(LiveMigrationOpsTestCase, self).setUp()
        self.context = 'fake_context'
        self._livemigrops = livemigrationops.LiveMigrationOps()
        self._livemigrops._livemigrutils = mock.MagicMock()
        self._livemigrops._pathutils = mock.MagicMock()
        self._livemigrops._block_dev_man = mock.MagicMock()
        self._pathutils = self._livemigrops._pathutils

Example 28

View license
    def setUp(self):
        super(TestConnectionManager, self).setUp()
        self.client = mock.MagicMock()
        self.client.session.get_auth_headers.return_value = {
            connection_manager.SwiftConnectionManager.AUTH_HEADER_NAME:
                "fake_token"}

        self.location = mock.create_autospec(swift_store.StoreLocation)
        self.context = mock.MagicMock()
        self.conf = mock.MagicMock()

Example 29

Project: ironic-inspector
Source File: test_migrations.py
View license
    def setUp(self):
        super(TestWalkVersions, self).setUp()
        self.engine = mock.MagicMock()
        self.migration_ext = mock.MagicMock()
        self.config = mock.MagicMock()
        self.versions = [mock.Mock(revision='2b2'), mock.Mock(revision='1a1')]

Example 30

View license
        def setUp(self):
            super(TestThreadedDriver, self).setUp()
            cfg.CONF.set_override('request_poll_interval', 1, group='octavia')
            cfg.CONF.set_override('request_poll_timeout', 5, group='octavia')
            self.driver.req.get = mock.MagicMock()
            self.succ_completion = mock.MagicMock()
            self.fail_completion = mock.MagicMock()
            self.context = mock.MagicMock()
            ctx_patcher = mock.patch('neutron.context.get_admin_context',
                                     return_value=self.context)
            ctx_patcher.start()
            self.addCleanup(ctx_patcher.stop)
            self.driver.load_balancer.successful_completion = (
                self.succ_completion)
            self.driver.load_balancer.failed_completion = self.fail_completion

Example 31

View license
    def test_spider_closed_parses_with_lxml(self):
        self.export_sitemap.exporter = mock.MagicMock()
        self.export_sitemap.exporter.finish_exporting = mock.MagicMock()
        self.export_sitemap.files[self.spider] = mock.MagicMock()

        with mock.patch.object(pipelines.lxml, 'etree'):
            with mock.patch.object(pipelines.lxml.etree,
                                   'parse') as mocked_lxml_parse:
                with mock.patch.object(pipelines, 'open'):
                    self.export_sitemap.spider_closed(self.spider)

        self.assertTrue(mocked_lxml_parse.called)

Example 32

Project: os-cloud-config
Source File: test_nodes.py
View license
    def test_populate_node_mapping_ironic(self):
        client = mock.MagicMock()
        node1 = mock.MagicMock()
        node1.to_dict.return_value = {'uuid': 'abcdef'}
        node2 = mock.MagicMock()
        node2.to_dict.return_value = {'uuid': 'fedcba'}
        ironic_node = collections.namedtuple('node', ['uuid', 'driver',
                                             'driver_info'])
        ironic_port = collections.namedtuple('port', ['address'])
        node1_detail = ironic_node('abcdef', 'pxe_ssh', None)
        node2_detail = ironic_node('fedcba', 'ipmi',
                                   {'ipmi_address': '10.0.1.2'})
        client.node.get.side_effect = (node1_detail, node2_detail)
        client.node.list_ports.return_value = [ironic_port('aaa')]
        client.node.list.return_value = [node1, node2]
        expected = {'mac': {'aaa': 'abcdef'},
                    'pm_addr': {'10.0.1.2': 'fedcba'}}
        self.assertEqual(expected, nodes._populate_node_mapping(client))

Example 33

View license
    def test_delete_local_port_1(self):
        # contains device_owner
        db_port = mock.MagicMock()
        db_port.get = mock.MagicMock()

        local_port = mock.MagicMock()
        local_port.get = mock.MagicMock(
            return_value="network:router_interface")

        self.powervc_neutron_agent.pvc = mock.MagicMock()
        self.powervc_neutron_agent.pvc.create_port = mock.MagicMock()

        self.powervc_neutron_agent._delete_local_port(local_port, db_port)
        self.powervc_neutron_agent.pvc.create_port.assert_called_once_with(
            local_port)

Example 34

Project: python-zaqarclient
Source File: fakes.py
View license
    def setUp(self):
        super(TestMessaging, self).setUp()

        self.messaging_client = mock.MagicMock()
        # TODO(flwang): It would be nice if we can figure out a better way to
        # get the mocked request and transport.
        req_trans = (mock.MagicMock(), mock.MagicMock())
        self.messaging_client._request_and_transport.return_value = req_trans
        self.app.client_manager.messaging = self.messaging_client

Example 35

Project: tempest
Source File: test_cred_client.py
View license
    def setUp(self):
        super(TestCredClientV2, self).setUp()
        self.identity_client = mock.MagicMock()
        self.projects_client = mock.MagicMock()
        self.users_client = mock.MagicMock()
        self.roles_client = mock.MagicMock()
        self.creds_client = cred_client.V2CredsClient(self.identity_client,
                                                      self.projects_client,
                                                      self.users_client,
                                                      self.roles_client)

Example 36

Project: wsme
Source File: test_args.py
View license
    def test_args_from_body(self):

        funcdef = mock.MagicMock()
        body = mock.MagicMock()
        mimetype = "application/json"
        funcdef.ignore_extra_args = True
        json.parse = mock.MagicMock()
        json.parse.side_effect = (exc.UnknownArgument(""))
        resp = args.args_from_body(funcdef, body, mimetype)
        self.assertEqual(resp, ((), {}))

Example 37

Project: bt
Source File: test_algos.py
View license
def test_rebalance_over_time():
    target = mock.MagicMock()
    rb = mock.MagicMock()

    algo = algos.RebalanceOverTime(n=2)
    # patch in rb function
    algo._rb = rb

    target.temp = {}
    target.temp['weights'] = {'a': 1, 'b': 0}

    a = mock.MagicMock()
    a.weight = 0.
    b = mock.MagicMock()
    b.weight = 1.
    target.children = {'a': a, 'b': b}

    assert algo(target)
    w = target.temp['weights']
    assert len(w) == 2
    assert w['a'] == 0.5
    assert w['b'] == 0.5

    assert rb.called
    called_tgt = rb.call_args[0][0]
    called_tgt_w = called_tgt.temp['weights']
    assert len(called_tgt_w) == 2
    assert called_tgt_w['a'] == 0.5
    assert called_tgt_w['b'] == 0.5

    # update weights for next call
    a.weight = 0.5
    b.weight = 0.5

    # clear out temp - same as would Strategy
    target.temp = {}

    assert algo(target)
    w = target.temp['weights']
    assert len(w) == 2
    assert w['a'] == 1.
    assert w['b'] == 0.

    assert rb.call_count == 2

    # update weights for next call
    # should do nothing now
    a.weight = 1
    b.weight = 0

    # clear out temp - same as would Strategy
    target.temp = {}

    assert algo(target)
    # no diff in call_count since last time
    assert rb.call_count == 2

Example 38

Project: pypowervm
Source File: test_validation.py
View license
    def setUp(self):
        super(TestValidator, self).setUp()

        def _bld_mgd_sys(proc_units_avail=20.0, mem_free=32768,
                         system_name='default_sys_name',
                         max_procs_per_aix_linux_lpar=10,
                         max_sys_procs_limit=15,
                         max_vcpus_per_aix_linux_lpar=10,
                         max_sys_vcpus_limit=15):
            # Build a fake managed system wrapper
            mngd_sys = mock.MagicMock()
            mngd_sys.system_name = system_name
            mngd_sys.proc_units_avail = proc_units_avail
            mngd_sys.memory_free = mem_free
            mngd_sys.max_procs_per_aix_linux_lpar = (
                max_procs_per_aix_linux_lpar)
            mngd_sys.max_sys_procs_limit = (
                max_sys_procs_limit)
            mngd_sys.max_vcpus_per_aix_linux_lpar = (
                max_vcpus_per_aix_linux_lpar)
            mngd_sys.max_sys_vcpus_limit = (
                max_sys_vcpus_limit)
            mocked = mock.MagicMock(spec=mgd_sys.System, return_value=mngd_sys)
            return mocked()

        def _bld_lpar(proc_units=1.0, min_mem=512, des_mem=2048, max_mem=4096,
                      has_dedicated=False, name='default', rmc_state='active',
                      mem_dlpar=True, proc_dlpar=True, state='running',
                      env='AIX/Linux', proc_compat='Default', srr_enabled=True,
                      min_vcpus=1, des_vcpus=2, max_vcpus=4,
                      min_proc_units=0.1, max_proc_units=1.0, pool_id=None,
                      exp_factor=0.0, ame_enabled=False):
            lpar_w = mock.MagicMock()
            # name, states, env, etc.
            lpar_w.name = name
            lpar_w.state = state
            lpar_w.rmc_state = rmc_state
            lpar_w.env = env
            lpar_w.proc_compat_mode = proc_compat
            lpar_w.srr_enabled = srr_enabled
            # Proc
            lpar_w.proc_config.has_dedicated = has_dedicated
            if has_dedicated:
                lpar_w.proc_config.dedicated_proc_cfg.desired = proc_units
                lpar_w.proc_config.dedicated_proc_cfg.max = max_vcpus
                lpar_w.proc_config.dedicated_proc_cfg.min = min_vcpus
            else:
                lpar_w.proc_config.shared_proc_cfg.desired_units = proc_units
                lpar_w.proc_config.shared_proc_cfg.desired_virtual = des_vcpus
                lpar_w.proc_config.shared_proc_cfg.max_virtual = max_vcpus
                lpar_w.proc_config.shared_proc_cfg.min_virtual = min_vcpus
                lpar_w.proc_config.shared_proc_cfg.pool_id = (
                    pool_id if pool_id else 0)
                lpar_w.proc_config.shared_proc_cfg.min_units = min_proc_units
                lpar_w.proc_config.shared_proc_cfg.max_units = max_proc_units
            # Mem
            lpar_w.mem_config.desired = des_mem
            lpar_w.mem_config.min = min_mem
            lpar_w.mem_config.max = max_mem
            lpar_w.mem_config.exp_factor = exp_factor
            # Can Modify
            if (state != bp.LPARState.NOT_ACTIVATED
               and rmc_state != bp.RMCState.ACTIVE):
                    lpar_w.can_modify_proc.return_value = (False, 'Bad RMC')
                    lpar_w.can_modify_mem.return_value = (False, 'Bad RMC')
            else:
                # Doesn't matter what the message is unless it's bad
                # so always make it bad
                lpar_w.can_modify_proc.return_value = (proc_dlpar,
                                                       'Bad proc DLPAR')
                lpar_w.can_modify_mem.return_value = (mem_dlpar,
                                                      'Bad mem DLPAR')
            mocked = mock.MagicMock(spec_set=lpar.LPAR, return_value=lpar_w)
            return mocked()

        self.mngd_sys = _bld_mgd_sys()
        self.lpar_21_procs = _bld_lpar(proc_units=21.0, name='lpar_21_procs')
        self.lpar_1_proc = _bld_lpar()
        self.lpar_11_vcpus = _bld_lpar(des_vcpus=11, name='11_vcpus')
        self.lpar_16_max_vcpus = _bld_lpar(max_vcpus=16, name='16_max_vcpus')
        self.lpar_1_proc_ded = _bld_lpar(has_dedicated=True, name='1_proc_ded')
        self.lpar_11_proc_ded = _bld_lpar(proc_units=11, has_dedicated=True,
                                          name='11_proc_ded')
        self.lpar_16_proc_max_ded = _bld_lpar(max_vcpus=16, has_dedicated=True,
                                              name='16_proc_max_ded')
        self.lpar_21_proc_ded = _bld_lpar(proc_units=21, has_dedicated=True,
                                          name='21_proc_ded')
        self.lpar_no_rmc = _bld_lpar(rmc_state='inactive')
        self.lpar_bad_mem_dlpar = _bld_lpar(mem_dlpar=False)
        self.lpar_bad_proc_dlpar = _bld_lpar(proc_dlpar=False)
        self.lpar_48g_mem = _bld_lpar(des_mem=48000, name='lpar_48g_mem')

        self.lpar_1_min_vcpus = _bld_lpar(min_vcpus=1, name='1_min_vcpus')
        self.lpar_2_min_vcpus = _bld_lpar(min_vcpus=2, name='2_min_vcpus')
        self.lpar_1_min_proc_units = _bld_lpar(min_proc_units=0.1,
                                               name='0.1_min_procs')
        self.lpar_3_min_proc_units = _bld_lpar(min_proc_units=0.3,
                                               name='0.3_min_procs')
        self.lpar_6_max_proc_units = _bld_lpar(max_proc_units=0.6,
                                               name='0.6_max_procs')
        self.lpar_9_max_proc_units = _bld_lpar(max_proc_units=0.9,
                                               name='0.9_max_procs')
        self.lpar_6_max_vcpus = _bld_lpar(max_vcpus=6, name='6_max_vcpus')
        self.lpar_8_max_vcpus = _bld_lpar(max_vcpus=8, name='8_max_vcpus')
        self.lpar_512mb_min_mem = _bld_lpar(min_mem=512, name='512_min_mem')
        self.lpar_1gb_min_mem = _bld_lpar(min_mem=1024, name='1gb_min_mem')
        self.lpar_6g_max_mem = _bld_lpar(max_mem=6144, name='6gb_max_mem')
        self.lpar_8g_max_mem = _bld_lpar(max_mem=8192, name='8gb_max_mem')
        self.lpar_default_spp = _bld_lpar(pool_id=0, name='default_spp')
        self.lpar_non_default_spp = _bld_lpar(pool_id=2,
                                              name='non_default_spp')
        self.lpar_power8_proc_compat = _bld_lpar(proc_compat="POWER8",
                                                 name='power8_compat_mode')
        self.lpar_srr_disabled = _bld_lpar(srr_enabled=False,
                                           name='srr_disabled')
        self.lpar_1_proc_ded_inactive = _bld_lpar(has_dedicated=True,
                                                  name='1_proc_ded_inactive',
                                                  state='not activated')
        self.lpar_22_procs = _bld_lpar(proc_units=22.0, name='lpar_22_procs')
        self.lpar_4_proc_ded = _bld_lpar(proc_units=4.0,
                                         has_dedicated=True, name='4_proc_ded')
        self.lpar_22_proc_ded = _bld_lpar(proc_units=22, has_dedicated=True,
                                          name='21_proc_ded')
        self.lpar_4g_mem = _bld_lpar(des_mem=4096, name='4gb_mem')
        self.lpar_6g_mem = _bld_lpar(des_mem=6144, name='6gb_mem')
        self.lpar_1dot6_proc_units = _bld_lpar(proc_units=1.6,
                                               name='1.6_procs')
        self.lpar_2dot2_proc_units = _bld_lpar(proc_units=2.2,
                                               name='2.2_procs')
        self.lpar_1_vcpus = _bld_lpar(des_vcpus=1, name='lpar_1_vcpus')
        self.lpar_not_activated = _bld_lpar(name='lpar_not_activated',
                                            state='not activated')
        self.lpar_running = _bld_lpar(name='lpar_running', state='running')
        self.lpar_starting = _bld_lpar(name='lpar_starting', state='starting')
        self.lpar_ame_2 = _bld_lpar(name='ame_2', exp_factor=2.0,
                                    ame_enabled=True)
        self.lpar_ame_3 = _bld_lpar(name='ame_3', exp_factor=3.0,
                                    ame_enabled=True)

Example 39

Project: pulp_python
Source File: test_sync.py
View license
    def test_generate_download_requests(self):
        """
        Ensure correct operation from generate_download_requests().
        """
        repo = mock.MagicMock()
        conduit = mock.MagicMock()
        config = mock.MagicMock()
        working_dir = '/some/dir'
        config.get.return_value = 'mock/feed'

        step = sync.SyncStep(repo, conduit, config, working_dir)
        u1 = models.Package(name='foo', version='1.2.0', path='url/1.2.tar.gz')
        u2 = models.Package(name='foo', version='1.3.0', path='url/1.3.tar.gz')
        u1._feed_url = u2._feed_url = "feed/"
        step.get_local_units_step.units_to_download.extend([u1, u2])

        requests = step.generate_download_requests()

        self.assertTrue(isinstance(requests, types.GeneratorType))
        # For the remainder of our tests, it will be more useful if requests is a list
        requests = list(requests)
        self.assertEqual(len(requests), 2)
        request_urls = [r.url for r in requests]
        self.assertEqual(request_urls, ['mock/feed/packages/url/1.2.tar.gz',
                                        'mock/feed/packages/url/1.3.tar.gz'])

        # The destinations should both have been paths constructed from the filename
        request_destinations = [r.destination for r in requests]
        self.assertEqual(request_destinations, ['/some/dir/1.2.tar.gz', '/some/dir/1.3.tar.gz'])
        requests_data = [r.data for r in requests]
        self.assertEqual(requests_data, step.get_local_units_step.units_to_download)

Example 40

Project: mysql
Source File: test.py
View license
    def test_failover_locked_this_node_is_primary(self):
        """
        Given another node is running a failover, wait for that failover.
        Given this this node is marked primary, the node will update its
        ContainerPilot config as required.
        """
        def query_results(*args, **kwargs):
            yield ()
            yield () # and after two hits we've set up replication
            yield [{'Master_Server_Id': 'node1', 'Master_Host': '192.168.1.101'}]

        self.node.mysql = MySQL(envs=get_environ())
        self.node.mysql._conn = mock.MagicMock()
        self.node.mysql.query = mock.MagicMock(side_effect=query_results())
        self.node.mysql.failover = mock.MagicMock()

        def consul_get_primary_results(*args, **kwargs):
            yield UnknownPrimary()
            yield UnknownPrimary()
            yield ('node1', '192.168.1.101')

        def lock_sequence(*args, **kwargs):
            yield True
            yield False

        self.node.consul = Consul(envs=get_environ())
        self.node.consul.client = mock.MagicMock()
        self.node.consul.put = mock.MagicMock()
        self.node.consul.get_primary = mock.MagicMock(
            side_effect=consul_get_primary_results())
        self.node.consul.lock_failover = mock.MagicMock(return_value=False)
        self.node.consul.unlock_failover = mock.MagicMock()
        self.node.consul.is_locked = mock.MagicMock(side_effect=lock_sequence())

        with mock.patch('time.sleep'): # cuts 3 sec from test run
            manage.on_change(self.node)

        self.assertEqual(self.node.consul.get_primary.call_count, 2)
        self.node.consul.lock_failover.assert_called_once()
        self.assertFalse(self.node.consul.client.health.service.called)
        self.assertFalse(self.node.consul.unlock_failover.called)
        self.node.consul.put.assert_called_once()
        self.node.cp.reload.assert_called_once()
        self.assertEqual(self.node.cp.state, PRIMARY)

Example 41

Project: mysql
Source File: test.py
View license
    def test_failover_locked_another_node_is_primary(self):
        """
        Given another node is running a failover, wait for that failover.
        Given this this node is not marked primary, the node will not
        update its ContainerPilot config.
        """
        def query_results(*args, **kwargs):
            yield ()
            yield () # and after two hits we've set up replication
            yield [{'Master_Server_Id': 'node2', 'Master_Host': '192.168.1.102'}]

        self.node.mysql = MySQL(envs=get_environ())
        self.node.mysql._conn = mock.MagicMock()
        self.node.mysql.query = mock.MagicMock(side_effect=query_results())
        self.node.mysql.failover = mock.MagicMock()

        def consul_get_primary_results(*args, **kwargs):
            yield UnknownPrimary()
            yield UnknownPrimary()
            yield ('node2', '192.168.1.102')

        def lock_sequence(*args, **kwargs):
            yield True
            yield False

        self.node.consul = Consul(envs=get_environ())
        self.node.consul.client = mock.MagicMock()
        self.node.consul.put = mock.MagicMock()
        self.node.consul.get_primary = mock.MagicMock(
            side_effect=consul_get_primary_results())
        self.node.consul.lock_failover = mock.MagicMock(return_value=False)
        self.node.consul.unlock_failover = mock.MagicMock()
        self.node.consul.is_locked = mock.MagicMock(side_effect=lock_sequence())

        with mock.patch('time.sleep'): # cuts 3 sec from test run
            manage.on_change(self.node)

        self.assertEqual(self.node.consul.get_primary.call_count, 2)
        self.node.consul.lock_failover.assert_called_once()
        self.assertFalse(self.node.consul.client.health.service.called)
        self.assertFalse(self.node.consul.unlock_failover.called)
        self.assertFalse(self.node.consul.put.called)
        self.assertFalse(self.node.cp.reload.called)
        self.assertEqual(self.node.cp.state, REPLICA)

Example 42

Project: stacker
Source File: test_build.py
View license
    def test_launch_stack_step_statuses(self):
        mock_provider = mock.MagicMock()
        mock_stack = mock.MagicMock()

        context = self._get_context()
        build_action = build.Action(context, provider=mock_provider)
        plan = build_action._generate_plan()
        _, step = plan.list_pending()[0]
        step.stack = mock.MagicMock()
        step.stack.locked = False

        # mock provider shouldn't return a stack at first since it hasn't been
        # launched
        mock_provider.get_stack.return_value = None
        with mock.patch.object(build_action, "s3_stack_push"):
            # initial status should be PENDING
            self.assertEqual(step.status, PENDING)
            # initial run should return SUBMITTED since we've passed off to CF
            status = step.run()
            step.set_status(status)
            self.assertEqual(status, SUBMITTED)
            self.assertEqual(status.reason, "creating new stack")

            # provider should now return the CF stack since it exists
            mock_provider.get_stack.return_value = mock_stack
            # simulate that we're still in progress
            mock_provider.is_stack_in_progress.return_value = True
            mock_provider.is_stack_completed.return_value = False
            status = step.run()
            step.set_status(status)
            # status should still be SUBMITTED since we're waiting for it to
            # complete
            self.assertEqual(status, SUBMITTED)
            self.assertEqual(status.reason, "creating new stack")
            # simulate completed stack
            mock_provider.is_stack_completed.return_value = True
            mock_provider.is_stack_in_progress.return_value = False
            status = step.run()
            step.set_status(status)
            self.assertEqual(status, COMPLETE)
            self.assertEqual(status.reason, "creating new stack")

            # simulate stack should be skipped
            mock_provider.is_stack_completed.return_value = False
            mock_provider.is_stack_in_progress.return_value = False
            mock_provider.update_stack.side_effect = StackDidNotChange
            status = step.run()
            step.set_status(status)
            self.assertEqual(status, SKIPPED)
            self.assertEqual(status.reason, "nochange")

            # simulate an update is required
            mock_provider.reset_mock()
            mock_provider.update_stack.side_effect = None
            step.set_status(PENDING)
            status = step.run()
            step.set_status(status)
            self.assertEqual(status, SUBMITTED)
            self.assertEqual(status.reason, "updating existing stack")
            self.assertEqual(mock_provider.update_stack.call_count, 1)

Example 43

Project: anaconda
Source File: test_driver_updates.py
View license
    def setUp(self):
        # an iterable that returns fake mountpoints, for mocking mount()
        self.fakemount = ["/mnt/DD-%i" % n for n in range(1,10)]
        # an iterable that returns fake repos, for mocking find_repos()
        self.frepo = {
            '/mnt/DD-1': ['/mnt/DD-1/repo1'],
            '/mnt/DD-2': ['/mnt/DD-2/repo1', '/mnt/DD-2/repo2'],
        }
        # fake iso listings for iso_dir
        self.fiso = {
            '/mnt/DD-1': [],
            '/mnt/DD-2': [],
            '/mnt/DD-3': [],
        }
        # a context-manager object to be returned by the mock mounted()
        mounted_ctx = mock.MagicMock(
            __enter__=mock.MagicMock(side_effect=self.fakemount), # mount
            __exit__=mock.MagicMock(return_value=None),           # umount
        )
        self.moddict = {}
        # set up our patches
        patches = (
            mock.patch("driver_updates.mounted", return_value=mounted_ctx),
            mock.patch("driver_updates.find_repos", side_effect=self.frepo.get),
            mock.patch("driver_updates.find_isos", side_effect=self.fiso.get),
            mock.patch("driver_updates.extract_drivers", return_value=True),
            mock.patch('driver_updates.grab_driver_files',
                                side_effect=lambda: self.moddict),
        )
        self.mocks = {p.attribute:p.start() for p in patches}
        for p in patches: self.addCleanup(p.stop)

Example 44

Project: pappy-proxy
Source File: test_proxy.py
View license
def test_mpc_socks_ssl_creds(mocker):
    mock_config(mocker)
    tcp_endpoint_instance = mock.MagicMock()
    socks_endpoint_instance = mock.MagicMock()
    wrapper_instance = mock.MagicMock()
    tcp_endpoint = mocker.patch('twisted.internet.endpoints.TCP4ClientEndpoint', return_value=tcp_endpoint_instance)
    socks_endpoint = mocker.patch('txsocksx.client.SOCKS5ClientEndpoint', return_value=socks_endpoint_instance)
    wrapper_endpoint = mocker.patch('txsocksx.tls.TLSWrapClientEndpoint', return_value=wrapper_instance)

    target_host = 'fakehost'
    target_port = 1337

    socks_host = 'fakesockshost'
    socks_port = 1447
    socks_user = 'username'
    socks_password = 'password'
    socks_config = {'host':socks_host, 'port':socks_port,
                    'username':socks_user, 'password':socks_password}

    make_proxied_connection('fakefactory', target_host, target_port, True, socks_config=socks_config)

    tcp_ep_calls = tcp_endpoint.mock_calls[0]
    assert tcp_ep_calls[1][1] == socks_host
    assert tcp_ep_calls[1][2] == socks_port

    socks_ep_calls = socks_endpoint.mock_calls[0]
    assert socks_ep_calls[1][0] == target_host
    assert socks_ep_calls[1][1] == target_port
    assert socks_ep_calls[1][2] is tcp_endpoint_instance
    assert socks_ep_calls[2]['methods'] == {'login': (socks_user, socks_password), 'anonymous': ()}

    wrapper_calls = wrapper_endpoint.mock_calls[0]
    assert isinstance(wrapper_calls[1][0], ssl.ClientContextFactory)
    assert wrapper_calls[1][1] is socks_endpoint_instance

    connectcall = wrapper_instance.connect
    assert len(connectcall.mock_calls) == 1

Example 45

Project: scalarizr
Source File: test_raid.py
View license
    def test_ensure_from_snapshot_autodetect(self, mdadm, lvm2, storage2,
                                                                                     exists, rm, tfile, b64, op):
        exists.side_effect = [True]
        disks_snaps = [dict(type='loop', size=0.01)]*2
        disks =  [mock.MagicMock(), mock.MagicMock()]
        storage2.snapshot.side_effect = disks
        storage2.volume.side_effect = disks
        mdadm.mdfind.return_value = '/dev/md2'
        lv_info = mock.MagicMock()
        lvm2.lvs.return_value = {'test': lv_info}

        raid_vol = raid.RaidVolume(type='raid',
                                                           snap=dict(vg='test', level=1,
                                                           disks=disks_snaps,
                                                           pv_uuid='pvuuid',
                                                           lvm_group_cfg='base64_encoded_cfg'))

        raid_vol.ensure()
        self.assertSequenceEqual(raid_vol.disks, disks)

        for d in raid_vol.disks:
            assert d.ensure.call_count == 1
        mdadm.mdfind.assert_called_once_with(
                                        *[r.device for r in raid_vol.disks])
        lvm2.pvs.assert_called_once_with('/dev/md2')

        tfile.mktemp.assert_called_once_with()
        tmpfile = tfile.mktemp.return_value
        op.assert_called_once_with(tmpfile, 'w')
        f = op.return_value.__enter__.return_value
        f.write.assert_called_once_with(b64.b64decode.return_value)
        b64.b64decode.assert_called_once_with('base64_encoded_cfg')
        lvm2.vgcfgrestore.assert_called_once_with('test', file=tmpfile)
        rm.assert_called_once_with(tmpfile)

        lvm2.lvs.assert_called_once_with('test')
        lvm2.lvpath.assert_called_once_with('test', lv_info.lv_name)
        lvm2.vgchange.assert_called_once_with('test', available='y')

        exists.assert_called_with(lvm2.lvpath.return_value)

Example 46

Project: tchannel-python
Source File: test_peer.py
View license
@pytest.mark.gen_test
def test_peer_connection_failure():
    # Test connecting a peer when the first connection attempt fails.

    MockConnection = mock.MagicMock()
    connection = mock.MagicMock()

    called = [False]

    with mock.patch.object(tpeer.Peer, 'connection_class', MockConnection):

        @gen.coroutine
        def try_connect(*args, **kwargs):
            if not called[0]:
                # If this is the first call, fail.
                called[0] = True
                raise ZeroDivisionError('great sadness')
            else:
                raise gen.Return(connection)

        MockConnection.outgoing.side_effect = try_connect

        peer = tpeer.Peer(mock.MagicMock(), 'localhost:4040')

        future = peer.connect()
        with pytest.raises(ZeroDivisionError) as excinfo:
            yield future

        assert 'great sadness' in str(excinfo)

        got = yield peer.connect()
        assert got is connection

        assert MockConnection.outgoing.call_count == 2

Example 47

Project: ripozo
Source File: base.py
View license
    def test_multiple_subclasses(self):
        """
        tests whether multiple classes can inherit from the same
        abstract class
        """
        props = dict(hello='world')
        class T1(ResourceBase):
            @apimethod(methods=['GET'])
            def hello(cls, *args, **kwargs):
                return cls(properties=dict(hello='world'))

        endpoint = T1.endpoint_dictionary()['hello'][0]
        self.assertEqual(endpoint['route'], '/t1/')
        self.assertListEqual(endpoint['methods'], ['GET'])
        self.assertDictEqual(props, T1.hello(mock.MagicMock()).properties)

        class T2(T1):
            pass

        class T3(T1):
            pass

        class T4(T2):
            pass

        endpoint = T1.endpoint_dictionary()['hello'][0]
        self.assertEqual(endpoint['route'], '/t1/')
        self.assertListEqual(endpoint['methods'], ['GET'])
        self.assertDictEqual(props, T1.hello(mock.MagicMock()).properties)

        endpoint = T2.endpoint_dictionary()['hello'][0]
        self.assertEqual(endpoint['route'], '/t2/')
        self.assertListEqual(endpoint['methods'], ['GET'])
        self.assertDictEqual(props, T1.hello(mock.MagicMock()).properties)

        endpoint = T3.endpoint_dictionary()['hello'][0]
        self.assertEqual(endpoint['route'], '/t3/')
        self.assertListEqual(endpoint['methods'], ['GET'])
        self.assertDictEqual(props, T1.hello(mock.MagicMock()).properties)

        endpoint = T4.endpoint_dictionary()['hello'][0]
        self.assertEqual(endpoint['route'], '/t4/')
        self.assertListEqual(endpoint['methods'], ['GET'])
        self.assertDictEqual(props, T1.hello(mock.MagicMock()).properties)

Example 48

View license
    def test__rebalance_groups_partition_cnt_case2(self):
        # 1 over-balanced, 2 under-balanced replication-groups
        # rg1 has 4 partitions
        # rg2 has 1 partition
        # rg3 has 1 partition
        # All rg's are balanced(based on replica-count) initially
        # Result: rg's will be balanced for partition-count
        assignment = dict(
            [
                ((u'T1', 1), ['0', '2']),
                ((u'T3', 1), ['0']),
                ((u'T3', 0), ['0']),
                ((u'T2', 0), ['0', '5']),
            ]
        )
        brokers = {
            '0': mock.MagicMock(),
            '2': mock.MagicMock(),
            '5': mock.MagicMock(),
        }
        ct = self.build_cluster_topology(assignment, brokers)
        # Re-balance brokers
        ct._rebalance_groups_partition_cnt()

        # Verify all replication-groups have same partition-count
        assert len(ct.rgs['rg1'].partitions) == len(ct.rgs['rg2'].partitions)
        assert len(ct.rgs['rg1'].partitions) == len(ct.rgs['rg3'].partitions)
        _, total_movements = \
            calculate_partition_movement(assignment, ct.assignment)
        # Verify minimum partition movements 2
        assert total_movements == 2
        net_imbal, _ = get_replication_group_imbalance_stats(
            ct.rgs.values(),
            ct.partitions.values(),
        )
        # Verify replica-count imbalance remains 0
        assert net_imbal == 0

Example 49

Project: pyrox
Source File: pipeline_test.py
View license
    def test_response_methods_pass_optional_request(self):
        resp_head = mock.MagicMock()
        resp_body = mock.MagicMock()
        req_head = mock.MagicMock()
        msg_part = mock.MagicMock()
        out = mock.MagicMock()

        assertEqual = self.assertEqual

        class ResponseFilterUsesRequest():
            def __init__(self):
                self.on_resp_head_called = False
                self.on_resp_body_called = False

            def were_expected_calls_made(self):
                return self.on_resp_head_called and \
                       self.on_resp_body_called

            @filtering.handles_response_head
            def on_response_head(self, response_head, request_head):
                assertEqual(resp_head, response_head)
                assertEqual(req_head, request_head)
                self.on_resp_head_called = True
                
            @filtering.handles_response_body
            def on_response_body(self, message_part, output, request_head):
                assertEqual(msg_part, message_part)
                assertEqual(out, output)
                assertEqual(req_head, request_head)
                self.on_resp_body_called = True


        pipeline = filtering.HttpFilterPipeline()

        resp_filter = ResponseFilterUsesRequest()
        pipeline.add_filter(resp_filter)

        pipeline.on_response_head(resp_head, req_head)
        pipeline.on_response_body(msg_part, out, req_head)
        self.assertTrue(resp_filter.were_expected_calls_made())

Example 50

Project: crossbar
Source File: test_broker.py
View license
    def test_publish_closed_session(self):
        """
        ensure a session doesn't get Events if it's closed
        (see also issue #431)
        """
        # we want to trigger a deeply-nested condition in
        # processPublish in class Broker -- lets try w/o refactoring
        # anything first...

        class TestSession(ApplicationSession):
            pass
        session0 = TestSession()
        session1 = TestSession()
        router = mock.MagicMock()
        broker = Broker(router)

        # let's just "cheat" our way a little to the right state by
        # injecting our subscription "directly" (e.g. instead of
        # faking out an entire Subscribe etc. flow
        # ...so we need _subscriptions_map to have at least one
        # subscription (our test one) for the topic we'll publish to
        broker._subscription_map.add_observer(session0, u'test.topic')

        # simulate the session state we want, which is that a
        # transport is connected (._transport != None) but there
        # _session_id *is* None (not joined yet, or left already)
        self.assertIs(None, session0._session_id)
        session0._transport = mock.MagicMock()
        session0._transport.get_channel_id = mock.MagicMock(return_value=b'deadbeef')
        session1._session_id = 1234  # "from" session should look connected + joined
        session1._transport = mock.MagicMock()
        session1._transport.channel_id = b'aaaabeef'

        # here's the main "cheat"; we're faking out the
        # router.authorize because we need it to callback immediately
        router.authorize = mock.MagicMock(return_value=txaio.create_future_success(dict(allow=True, cache=False, disclose=True)))

        # now we scan call "processPublish" such that we get to the
        # condition we're interested in (this "comes from" session1
        # beacuse by default publishes don't go to the same session)
        pubmsg = message.Publish(123, u'test.topic')
        broker.processPublish(session1, pubmsg)

        # neither session should have sent anything on its transport
        self.assertEquals(session0._transport.method_calls, [])
        self.assertEquals(session1._transport.method_calls, [])