当前位置: 首页>>代码示例>>Python>>正文


Python Mock.assert_called_once_with方法代码示例

本文整理汇总了Python中unittest.mock.Mock.assert_called_once_with方法的典型用法代码示例。如果您正苦于以下问题:Python Mock.assert_called_once_with方法的具体用法?Python Mock.assert_called_once_with怎么用?Python Mock.assert_called_once_with使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在unittest.mock.Mock的用法示例。


在下文中一共展示了Mock.assert_called_once_with方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_integration

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import assert_called_once_with [as 别名]
    def test_integration(self):
        """
        Simple integration testing.

        Start one thread for the server, then sends a message to it and checks
        that the callback was correctly installed.
        """
        TARGET = ('localhost', 9999)
        callbacks = {'foo': Mock(), 'bar': Mock()}
        default_cb = Mock()

        # Creates the server
        RequestHandler = message.create_request_handler(callbacks, default_cb)
        server = socketserver.UDPServer(TARGET, RequestHandler)

        # Starts the server in another thread
        server_thread = threading.Thread(target=server.serve_forever)
        server_thread.start()

        # Sends the messages
        message.send(TARGET, 'foo', [1, 2, 3])
        message.send(TARGET, 'bar')
        message.send(TARGET, 'other')

        # Terminates the server thread
        server.shutdown()

        # Checks that the callbacks were called
        callbacks['foo'].assert_any_call([1, 2, 3])
        callbacks['bar'].assert_any_call(None)
        default_cb.assert_called_once_with('other', None)
开发者ID:froj,项目名称:simplerpc,代码行数:33,代码来源:test_messages.py

示例2: test_simple_handler

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import assert_called_once_with [as 别名]
    def test_simple_handler(self):
        mock_handler = Mock()
        mock_callback = Mock()

        @TaskHandler('test-task', 1)
        def test_handler(input_data):
            mock_handler()
            return input_data

        data = {'data': 1337}

        with Executor() as executor:
            executor.submit_task(
                {
                    "task_id": "123e4567-e89b-12d3-a456-426655440000",
                    "task_type": "test-task",
                    "task_version": 1,
                    "task_data": data
                },
                mock_callback
            )

        mock_handler.assert_any_call()
        mock_callback.assert_called_once_with(
            "123e4567-e89b-12d3-a456-426655440000",
            task_data=data
        )
开发者ID:CryptidVulpes,项目名称:slamon-python-agent,代码行数:29,代码来源:executor_tests.py

示例3: test_input_text_callback

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import assert_called_once_with [as 别名]
    def test_input_text_callback(self):
        """An input text runs callback with the result as argument"""
        callback_fn = Mock()
        inter = InputText("Content", callback_fn)
        inter.run_callback("Foo Bar Baz")

        callback_fn.assert_called_once_with("Foo Bar Baz")
开发者ID:champ1,项目名称:ubuntu-make,代码行数:9,代码来源:test_interactions.py

示例4: TestRollBackCommand

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import assert_called_once_with [as 别名]
class TestRollBackCommand(TestBase):

    def setUp(self):
        super(TestRollBackCommand, self).setUp()
        with patch("os.path.exists") as m:
            m.return_value = True
            arguments = parse_args(['rollback',])
            self.open_mock = mock_open(read_data='create table users\n-- @down\ndrop table users;')
            self.get_latest_migration_mock = Mock(return_value="002_create_user.sql")
            self.sync_migration_mock = Mock()
            self.remove_migration_record_mock = Mock()
            with patch.object(builtins, 'open', self.open_mock):
                command = RollbackCommand(arguments)
                command.get_latest_migration = self.get_latest_migration_mock
                command.sync_migration = self.sync_migration_mock
                command.remove_migration_record = self.remove_migration_record_mock
                command.run()

    def test_open_file_correct(self):
        self.open_mock.assert_called_with(os.path.join("migrations", "002_create_user.sql"), encoding='utf-8')

    def test_sync_sql(self):
        self.sync_migration_mock.assert_called_once_with(ANY, "\ndrop table users;")

    def test_remove_migration_record(self):
        self.remove_migration_record_mock.assert_called_once_with(ANY, "002_create_user.sql")
开发者ID:erhuabushuo,项目名称:chunyun,代码行数:28,代码来源:test_rollback_command.py

示例5: test_handle_service

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import assert_called_once_with [as 别名]
 def test_handle_service(self):
     handler = Mock()
     handler.return_value = 456
     self.node.register_service('/service', handler)
     self.assertEqual(zmqmsgbus.call.encode_res(456),
                      self.node._service_handle(zmqmsgbus.call.encode_req('/service', 123)))
     handler.assert_called_once_with(123)
开发者ID:cvra,项目名称:zmqmsgbus,代码行数:9,代码来源:test_bus.py

示例6: test_build_bundled_pdf_with_one_pdf

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import assert_called_once_with [as 别名]
    def test_build_bundled_pdf_with_one_pdf(self, logger, get_parser, slack):
        # set up associated data
        sf_pubdef = auth_models.Organization.objects.get(
            slug=constants.Organizations.SF_PUBDEF)
        sub = SubmissionsService.create_for_organizations(
            [sf_pubdef], answers={})
        fillable = mock.fillable_pdf(organization=sf_pubdef)
        data = b'content'
        filled = models.FilledPDF.create_with_pdf_bytes(
            pdf_bytes=data, submission=sub, original_pdf=fillable)
        bundle = BundlesService.create_bundle_from_submissions(
            organization=sf_pubdef, submissions=[sub], skip_pdf=True)

        # set up mocks
        should_have_a_pdf = Mock(return_value=True)
        get_individual_filled_pdfs = Mock(
            return_value=[filled])
        bundle.should_have_a_pdf = should_have_a_pdf
        bundle.get_individual_filled_pdfs = get_individual_filled_pdfs

        # run method
        BundlesService.build_bundled_pdf_if_necessary(bundle)

        # check results
        get_parser.assert_not_called()
        logger.assert_not_called()
        slack.assert_not_called()
        get_individual_filled_pdfs.assert_called_once_with()
        self.assertEqual(bundle.bundled_pdf.read(), data)
开发者ID:pamdinevaCfA,项目名称:intake,代码行数:31,代码来源:test_bundles.py

示例7: test_global_linter_bear_use_stderr

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import assert_called_once_with [as 别名]
    def test_global_linter_bear_use_stderr(self):
        create_arguments_mock = Mock()

        class Handler:

            @staticmethod
            def create_arguments(config_file):
                create_arguments_mock(config_file)
                return ['MAJOR: Test Message\nasd']

        uut = (linter('echo',
                      global_bear=True,
                      output_format='regex',
                      use_stderr=True,
                      output_regex=self.test_program_regex,
                      severity_map=self.test_program_severity_map)
               (Handler)
               ({}, self.section, None))

        results = list(uut.run())
        expected = [Result(uut,
                           'Test Message',
                           severity=RESULT_SEVERITY.MAJOR)]

        self.assertEqual(results, expected)
        create_arguments_mock.assert_called_once_with(None)
开发者ID:Eoghan-Murphy,项目名称:coala,代码行数:28,代码来源:LinterTest.py

示例8: test_authorize

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import assert_called_once_with [as 别名]
def test_authorize(
    mock_gateway, payment_dummy, braintree_success_response, gateway_config
):
    payment = payment_dummy
    mock_response = Mock(return_value=braintree_success_response)
    mock_gateway.return_value = Mock(transaction=Mock(sale=mock_response))

    payment_info = create_payment_information(payment, "auth-token")
    response = authorize(payment_info, gateway_config)
    assert not response.error

    assert response.kind == TransactionKind.AUTH
    assert response.amount == braintree_success_response.transaction.amount
    assert response.currency == braintree_success_response.transaction.currency_iso_code
    assert response.transaction_id == braintree_success_response.transaction.id
    assert response.is_success == braintree_success_response.is_success

    mock_response.assert_called_once_with(
        {
            "amount": str(payment.total),
            "payment_method_nonce": "auth-token",
            "options": {
                "submit_for_settlement": CONFIRM_MANUALLY,
                "three_d_secure": {"required": THREE_D_SECURE_REQUIRED},
            },
            **get_customer_data(payment_info),
        }
    )
开发者ID:mirumee,项目名称:saleor,代码行数:30,代码来源:test_braintree.py

示例9: test_main

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import assert_called_once_with [as 别名]
    def test_main(self):
        """Verify the top-level command can be run."""
        mock_function = Mock(return_value=True)

        cli.main([], mock_function)

        mock_function.assert_called_once_with(root=None)
开发者ID:ntauthority,项目名称:gdm,代码行数:9,代码来源:test_cli.py

示例10: test_gateway_charge

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import assert_called_once_with [as 别名]
def test_gateway_charge(
        mock_get_payment_gateway, mock_handle_fully_paid_order, payment_txn_preauth,
        gateway_params, transaction_token, dummy_response):
    payment_token = transaction_token
    txn = payment_txn_preauth.transactions.first()
    payment = payment_txn_preauth
    assert not payment.captured_amount
    amount = payment.total

    dummy_response['kind'] = TransactionKind.CHARGE
    mock_charge = Mock(return_value=dummy_response)
    mock_get_payment_gateway.return_value = (
        Mock(charge=mock_charge), gateway_params)

    payment_info = create_payment_information(payment, payment_token, amount)
    gateway_charge(payment, payment_token, amount)

    mock_get_payment_gateway.assert_called_once_with(payment.gateway)
    mock_charge.assert_called_once_with(
        payment_information=payment_info, connection_params=gateway_params)

    payment.refresh_from_db()
    assert payment.charge_status == ChargeStatus.FULLY_CHARGED
    assert payment.captured_amount == payment.total
    mock_handle_fully_paid_order.assert_called_once_with(payment.order)
开发者ID:krzysztofwolski,项目名称:saleor,代码行数:27,代码来源:test_payment.py

示例11: test_update_collection_with_background_image

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import assert_called_once_with [as 别名]
def test_update_collection_with_background_image(
        monkeypatch, staff_api_client, collection, permission_manage_products):
    mock_create_thumbnails = Mock(return_value=None)
    monkeypatch.setattr(
        ('saleor.dashboard.collection.forms.'
         'create_collection_background_image_thumbnails.delay'),
        mock_create_thumbnails)

    image_file, image_name = create_image()
    image_alt = 'Alt text for an image.'
    variables = {
        'name': 'new-name',
        'slug': 'new-slug',
        'id': to_global_id('Collection', collection.id),
        'backgroundImage': image_name,
        'backgroundImageAlt': image_alt,
        'isPublished': True}
    body = get_multipart_request_body(
        MUTATION_UPDATE_COLLECTION_WITH_BACKGROUND_IMAGE, variables,
        image_file, image_name)
    response = staff_api_client.post_multipart(
        body, permissions=[permission_manage_products])
    content = get_graphql_content(response)
    data = content['data']['collectionUpdate']
    assert not data['errors']
    slug = data['collection']['slug']
    collection = Collection.objects.get(slug=slug)
    assert collection.background_image
    mock_create_thumbnails.assert_called_once_with(collection.pk)
    assert data['collection']['backgroundImage']['alt'] == image_alt
开发者ID:krzysztofwolski,项目名称:saleor,代码行数:32,代码来源:test_collection.py

示例12: test_add_passes_kwargs_to_item_class_if_item_is_not_in_cart

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import assert_called_once_with [as 别名]
 def test_add_passes_kwargs_to_item_class_if_item_is_not_in_cart(self):
     item = Book.objects.create(name='foo', price=999)
     cart = self.cart
     MockItem = Mock(wraps=cart.item_class)
     with patch.object(cart, 'item_class', MockItem):
         cart.add(item.pk, quantity=1, foo='bar', baz='nox')
         MockItem.assert_called_once_with(item, 1, foo='bar', baz='nox')
开发者ID:EstudioNexos,项目名称:django-easycart,代码行数:9,代码来源:test_cart.py

示例13: test_update_collision_should_activate

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import assert_called_once_with [as 别名]
    def test_update_collision_should_activate(self, mock_pygame,
                                              mock_load_png_sequence):
        """Test that the powerup does activate when it collides with
        the paddle.
        """
        mock_image_1 = Mock()
        mock_image_2 = Mock()
        mock_load_png_sequence.return_value = [(mock_image_1, Mock()),
                                               (mock_image_2, Mock())]
        mock_rect = Mock()
        mock_pygame.Rect.return_value = mock_rect
        mock_rect.move.return_value = mock_rect
        mock_rect.colliderect.return_value = True
        mock_screen = Mock()
        mock_pygame.display.get_surface.return_value = mock_screen
        mock_area = Mock()
        mock_screen.get_rect.return_value = mock_area
        mock_area.contains.return_value = True
        mock_game = Mock()
        mock_game.paddle.exploding = False
        mock_game.paddle.visible = True
        mock_active_powerup = Mock()
        mock_game.active_powerup = mock_active_powerup
        powerup = PowerUp(mock_game, Mock(), 'test_prefix')
        mock_activate = Mock()
        powerup._activate = mock_activate

        powerup.update()

        mock_rect.colliderect.assert_called_once_with(mock_game.paddle.rect)
        mock_active_powerup.deactivate.assert_called_once_with()
        mock_activate.assert_called_once_with()
        self.assertIsNotNone(mock_game.active_powerup)
        mock_game.sprites.remove.assert_called_once_with(powerup)
        self.assertFalse(powerup.visible)
开发者ID:wkeeling,项目名称:arkanoid,代码行数:37,代码来源:test_powerup.py

示例14: test_view_product_image_edit_new_image

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import assert_called_once_with [as 别名]
def test_view_product_image_edit_new_image(
    monkeypatch, admin_client, product_with_image
):
    mock_create_thumbnails = Mock(return_value=None)
    monkeypatch.setattr(
        "saleor.dashboard.product.forms.create_product_thumbnails.delay",
        mock_create_thumbnails,
    )
    product_image = product_with_image.images.all()[0]
    url = reverse(
        "dashboard:product-image-update",
        kwargs={"img_pk": product_image.pk, "product_pk": product_with_image.pk},
    )

    response = admin_client.get(url)

    assert response.status_code == 200

    image, image_name = create_image()
    data = {"image_0": image, "alt": ["description"]}

    response = admin_client.post(url, data, follow=True)

    assert response.status_code == 200
    assert product_with_image.images.count() == 1
    product_image.refresh_from_db()
    assert image_name in product_image.image.name
    assert product_image.alt == "description"
    mock_create_thumbnails.assert_called_once_with(product_image.pk)
开发者ID:mirumee,项目名称:saleor,代码行数:31,代码来源:test_product.py

示例15: test_cmd_checks_for_additional_requirements_defined_by_child

# 需要导入模块: from unittest.mock import Mock [as 别名]
# 或者: from unittest.mock.Mock import assert_called_once_with [as 别名]
    def test_cmd_checks_for_additional_requirements_defined_by_child(self):
        m = Mock()
        self.CMD._additional_requirements = m
        cmd = self.CMD()
        cmd.cmd()

        m.assert_called_once_with()
开发者ID:muppetjones,项目名称:rempipe,代码行数:9,代码来源:test_base.py


注:本文中的unittest.mock.Mock.assert_called_once_with方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。