Python mock.DEFAULT Examples

The following are 30 code examples of mock.DEFAULT(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module mock , or try the search function .
Example #1
Source File: test_ExcludeRegionState.py    From OctoPrint-ExcludeRegionPlugin with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_processNonMove_deltaE_zero_notExcluding(self):
        """Test _processNonMove when deltaE is 0 and not excluding."""
        mockLogger = mock.Mock()
        unit = ExcludeRegionState(mockLogger)

        with mock.patch.multiple(
            unit,
            recordRetraction=mock.DEFAULT,
            recoverRetractionIfNeeded=mock.DEFAULT
        ) as mocks:
            unit.excluding = False
            unit.feedRate = 100

            result = unit._processNonMove("G0 E0 F100", 0)  # pylint: disable=protected-access

            mocks["recordRetraction"].assert_not_called()
            mocks["recoverRetractionIfNeeded"].assert_not_called()
            self.assertEqual(
                result, ["G0 E0 F100"],
                "The result should be a list containing the command"
            ) 
Example #2
Source File: test_ExcludeRegionPlugin.py    From OctoPrint-ExcludeRegionPlugin with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_handleAddExcludeRegion_ValueError(self):
        """Test _handleAddExcludeRegion when state.addRegion raises a ValueError."""
        unit = create_plugin_instance()
        with mock.patch.multiple(
            unit,
            state=mock.DEFAULT,
            _notifyExcludedRegionsChanged=mock.DEFAULT
        ) as mocks:
            mocks["state"].addRegion.side_effect = ValueError("ExpectedError")

            mockRegion = mock.Mock()

            result = unit._handleAddExcludeRegion(mockRegion)  # pylint: disable=protected-access

            mocks["state"].addRegion.assert_called_with(mockRegion)
            mocks["_notifyExcludedRegionsChanged"].assert_not_called()

            self.assertEqual(
                result, ("ExpectedError", 409),
                "A 409 error response tuple should be returned"
            ) 
Example #3
Source File: test_ExcludeRegionPlugin.py    From OctoPrint-ExcludeRegionPlugin with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_handleDeleteExcludeRegion_success_not_found(self):
        """Test _handleDeleteExcludeRegion when state.deleteRegion returns False."""
        unit = create_plugin_instance()
        with mock.patch.multiple(
            unit,
            state=mock.DEFAULT,
            _notifyExcludedRegionsChanged=mock.DEFAULT
        ) as mocks:
            mocks["state"].deleteRegion.return_value = False

            result = unit._handleDeleteExcludeRegion("someId")  # pylint: disable=protected-access

            mocks["state"].deleteRegion.assert_called_with("someId")
            mocks["_notifyExcludedRegionsChanged"].assert_not_called()

            self.assertIsNone(result, "The result should be None") 
Example #4
Source File: test_ExcludeRegionPlugin.py    From OctoPrint-ExcludeRegionPlugin with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_handleAddExcludeRegion_success(self):
        """Test _handleAddExcludeRegion when state.addRegion succeeds."""
        unit = create_plugin_instance()
        with mock.patch.multiple(
            unit,
            state=mock.DEFAULT,
            _notifyExcludedRegionsChanged=mock.DEFAULT
        ) as mocks:
            mockRegion = mock.Mock()

            result = unit._handleAddExcludeRegion(mockRegion)  # pylint: disable=protected-access

            mocks["state"].addRegion.assert_called_with(mockRegion)
            mocks["_notifyExcludedRegionsChanged"].assert_called()

            self.assertIsNone(result, "The result should be None") 
Example #5
Source File: test_ExcludeRegionPlugin.py    From OctoPrint-ExcludeRegionPlugin with GNU Affero General Public License v3.0 6 votes vote down vote up
def _test_on_event_stopPrinting(self, eventType, clearRegions):
        """Test the on_event method when an event is received that indicates printing stopped."""
        unit = create_plugin_instance()
        with mock.patch.multiple(
            unit,
            state=mock.DEFAULT,
            _notifyExcludedRegionsChanged=mock.DEFAULT
        ) as mocks:
            simulate_isActivePrintJob(unit, True)
            unit.clearRegionsAfterPrintFinishes = clearRegions

            mockPayload = mock.Mock()

            result = unit.on_event(eventType, mockPayload)

            self.assertFalse(unit.isActivePrintJob, "isActivePrintJob should report False")
            self.assertIsNone(result, "The result should be None")

            if (clearRegions):
                mocks['state'].resetState.assert_called_with(True)
                mocks['_notifyExcludedRegionsChanged'].assert_called_with()
            else:
                mocks['state'].resetState.assert_not_called()
                mocks['_notifyExcludedRegionsChanged'].assert_not_called() 
Example #6
Source File: test_inventory.py    From openstack-ansible with Apache License 2.0 6 votes vote down vote up
def test_group_with_hosts_and_children_fails(self):
        """Integration test making sure the whole script fails."""
        env = self._create_bad_env(self.env)

        config = get_config()

        kwargs = {
            'load_environment': mock.DEFAULT,
            'load_user_configuration': mock.DEFAULT
        }

        with mock.patch.multiple('osa_toolkit.filesystem', **kwargs) as mocks:
            mocks['load_environment'].return_value = env
            mocks['load_user_configuration'].return_value = config

            with self.assertRaises(di.GroupConflict):
                get_inventory() 
Example #7
Source File: test_ExcludeRegionState_processExtendedGcode.py    From OctoPrint-ExcludeRegionPlugin with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_processExtendedGcode_notExcluding_matchExists(self):
        """Test processExtendedGcode when not excluding and a matching entry exists."""
        mockLogger = mock.Mock()
        mockLogger.isEnabledFor.return_value = False  # For coverage of logging condition
        unit = ExcludeRegionState(mockLogger)

        with mock.patch.multiple(
            unit,
            extendedExcludeGcodes=mock.DEFAULT,
            _processExtendedGcodeEntry=mock.DEFAULT
        ) as mocks:
            unit.excluding = False
            mockEntry = mock.Mock(name="entry")
            mockEntry.mode = "expectedMode"
            mocks["extendedExcludeGcodes"].get.return_value = mockEntry

            result = unit.processExtendedGcode(AnyIn(["G1 X1 Y2", "G1 Y2 X1"]), "G1", None)

            mocks["extendedExcludeGcodes"].get.assert_not_called()
            mocks["_processExtendedGcodeEntry"].assert_not_called()
            self.assertIsNone(result, "The return value should be None") 
Example #8
Source File: test_ExcludeRegionState_processExtendedGcode.py    From OctoPrint-ExcludeRegionPlugin with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_processExtendedGcode_excluding_matchExists(self):
        """Test processExtendedGcode when excluding and a matching entry exists."""
        mockLogger = mock.Mock()
        unit = ExcludeRegionState(mockLogger)

        with mock.patch.multiple(
            unit,
            extendedExcludeGcodes=mock.DEFAULT,
            _processExtendedGcodeEntry=mock.DEFAULT
        ) as mocks:
            unit.excluding = True
            mockEntry = mock.Mock(name="entry")
            mockEntry.mode = "expectedMode"
            mocks["extendedExcludeGcodes"].get.return_value = mockEntry
            mocks["_processExtendedGcodeEntry"].return_value = "expectedResult"

            result = unit.processExtendedGcode("G1 X1 Y2", "G1", None)

            mocks["extendedExcludeGcodes"].get.assert_called_with("G1")
            mocks["_processExtendedGcodeEntry"].assert_called_with("expectedMode", "G1 X1 Y2", "G1")
            self.assertEqual(
                result, "expectedResult",
                "The expected result of _processExtendedGcodeEntry should be returned"
            ) 
Example #9
Source File: test_ExcludeRegionState_processExtendedGcode.py    From OctoPrint-ExcludeRegionPlugin with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_processExtendedGcode_excluding_noMatch(self):
        """Test processExtendedGcode when excluding and no entry matches."""
        mockLogger = mock.Mock()
        unit = ExcludeRegionState(mockLogger)

        with mock.patch.multiple(
            unit,
            extendedExcludeGcodes=mock.DEFAULT,
            _processExtendedGcodeEntry=mock.DEFAULT
        ) as mocks:
            unit.excluding = True
            mocks["extendedExcludeGcodes"].get.return_value = None

            result = unit.processExtendedGcode("G1 X1 Y2", "G1", None)

            mocks["extendedExcludeGcodes"].get.assert_called_with("G1")
            mocks["_processExtendedGcodeEntry"].assert_not_called()
            self.assertIsNone(result, "The return value should be None") 
Example #10
Source File: mock_.py    From asynq with Apache License 2.0 6 votes vote down vote up
def _patch_object(
    target,
    attribute,
    new=mock.DEFAULT,
    spec=None,
    create=False,
    mocksignature=False,
    spec_set=None,
    autospec=False,
    new_callable=None,
    **kwargs
):
    getter = lambda: target
    return _make_patch_async(
        getter,
        attribute,
        new,
        spec,
        create,
        mocksignature,
        spec_set,
        autospec,
        new_callable,
        kwargs,
    ) 
Example #11
Source File: test_ExcludeRegionPlugin.py    From OctoPrint-ExcludeRegionPlugin with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_handleDeleteExcludeRegion_no_del_while_printing(self):
        """Test _handleDeleteExcludeRegion when modification is NOT allowed while printing."""
        unit = create_plugin_instance()
        with mock.patch.multiple(
            unit,
            state=mock.DEFAULT,
            _notifyExcludedRegionsChanged=mock.DEFAULT
        ) as mocks:
            unit.mayShrinkRegionsWhilePrinting = False
            simulate_isActivePrintJob(unit, True)
            mocks["_notifyExcludedRegionsChanged"] = mock.Mock()

            result = unit._handleDeleteExcludeRegion("someId")  # pylint: disable=protected-access

            mocks["state"].deleteRegion.assert_not_called()
            mocks["_notifyExcludedRegionsChanged"].assert_not_called()

            self.assertEqual(
                result,
                (AnyString(), 409),
                "The result should be a Tuple indicating a 409 error"
            ) 
Example #12
Source File: test_ExcludeRegionPlugin.py    From OctoPrint-ExcludeRegionPlugin with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_handleUpdateExcludeRegion_ValueError(self):
        """Test _handleUpdateExcludeRegion when a ValueError is raised."""
        unit = create_plugin_instance()

        with mock.patch.multiple(
            unit,
            state=mock.DEFAULT,
            _notifyExcludedRegionsChanged=mock.DEFAULT
        ) as mocks:
            unit.mayShrinkRegionsWhilePrinting = False
            simulate_isActivePrintJob(unit, True)
            mocks["state"].replaceRegion.side_effect = ValueError("ExpectedError")

            mockRegion = mock.Mock()

            result = unit._handleUpdateExcludeRegion(mockRegion)  # pylint: disable=protected-access

            mocks["state"].replaceRegion.assert_called_with(mockRegion, True)
            mocks["_notifyExcludedRegionsChanged"].assert_not_called()

            self.assertEqual(
                result, ("ExpectedError", 409),
                "A 409 error response tuple should be returned"
            ) 
Example #13
Source File: test_GcodeHandlers.py    From OctoPrint-ExcludeRegionPlugin with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_handle_G2_radiusTrumpsOffsets(self):
        """Test the _handle_G2 method to ensure offsets (I, J) are ignored if a radius is given."""
        unit = self._createInstance()

        with mock.patch.multiple(
            unit,
            computeArcCenterOffsets=mock.DEFAULT,
            planArc=mock.DEFAULT
        ) as mocks:
            expectedResult = ["Command1"]
            unit.state.processLinearMoves.return_value = expectedResult
            mocks["computeArcCenterOffsets"].return_value = (12, 13)
            mocks["planArc"].return_value = [0, 1, 2, 3]

            result = unit._handle_G2(  # pylint: disable=protected-access
                "G2 R20 I8 J9 X10 Y0",
                "G2",
                None
            )

            mocks["computeArcCenterOffsets"].assert_called_with(10, 0, 20, True)
            mocks["planArc"].assert_called_with(10, 0, 12, 13, True)

            self.assertEqual(result, expectedResult, "A list of one command should be returned") 
Example #14
Source File: test_rds.py    From awslimitchecker with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_find_usage(self):
        mock_conn = Mock()

        with patch('%s.connect' % self.pb) as mock_connect:
            with patch.multiple(
                    self.pb,
                    _find_usage_instances=DEFAULT,
                    _find_usage_subnet_groups=DEFAULT,
                    _find_usage_security_groups=DEFAULT,
                    _update_limits_from_api=DEFAULT,
            ) as mocks:
                cls = _RDSService(21, 43, {}, None)
                cls.conn = mock_conn
                assert cls._have_usage is False
                cls.find_usage()
        assert mock_connect.mock_calls == [call()]
        assert cls._have_usage is True
        for x in [
                '_find_usage_instances',
                '_find_usage_subnet_groups',
                '_find_usage_security_groups',
                '_update_limits_from_api',
        ]:
            assert mocks[x].mock_calls == [call()] 
Example #15
Source File: test_GcodeHandlers.py    From OctoPrint-ExcludeRegionPlugin with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_handle_G2_offsetMode_paramParsing(self):
        """Test _handle_G2 parameter parsing when center point offsets are provided."""
        unit = self._createInstance()

        unit.state.position.X_AXIS.nativeToLogical.return_value = 0
        unit.state.position.X_AXIS.nativeToLogical.return_value = 1

        expectedResult = ["Command1", "Command2"]
        unit.state.processLinearMoves.return_value = expectedResult

        with mock.patch.multiple(
            unit,
            computeArcCenterOffsets=mock.DEFAULT,
            planArc=mock.DEFAULT
        ) as mocks:
            mocks["planArc"].return_value = [4, 5]

            cmd = "G2 I6.1 J6.2 X7 Y8 Z9 E10 F11"
            result = unit._handle_G2(cmd, "G2", None)  # pylint: disable=protected-access

            mocks["computeArcCenterOffsets"].assert_not_called()
            mocks["planArc"].assert_called_with(7, 8, 6.1, 6.2, True)
            unit.state.processLinearMoves.assert_called_with(cmd, 10, 11, 9, 4, 5)

            self.assertEqual(result, expectedResult, "A list of two commands should be returned") 
Example #16
Source File: test_route53.py    From awslimitchecker with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_update_limits_from_api(self):
        """test _update_limits_from_api method calls other methods"""

        mock_conn = Mock()
        with patch('%s.connect' % pb) as mock_connect:
            with patch.multiple(
                    pb,
                    _find_limit_hosted_zone=DEFAULT,
            ) as mocks:
                cls = _Route53Service(21, 43, {}, None)
                cls.conn = mock_conn
                cls._update_limits_from_api()
        assert mock_connect.mock_calls == [call()]
        assert mock_conn.mock_calls == []
        for x in [
            '_find_limit_hosted_zone',
        ]:
            assert mocks[x].mock_calls == [call()] 
Example #17
Source File: test_ExcludeRegionState_processLinearMoves.py    From OctoPrint-ExcludeRegionPlugin with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_processLinearMoves_excluding_pointInExcludedRegion(self):
        """Test processLinearMoves when a point is in an excluded region and currently excluding."""
        mockLogger = mock.Mock()
        unit = ExcludeRegionState(mockLogger)
        unit.excluding = True
        unit.position = create_position(x=1, y=2, z=3, extruderPosition=4)
        unit.feedRate = 4000
        unit.feedRateUnitMultiplier = 1

        with mock.patch.multiple(
            unit,
            isAnyPointExcluded=mock.DEFAULT,
            enterExcludedRegion=mock.DEFAULT
        ) as mocks:
            mocks["isAnyPointExcluded"].return_value = True

            result = unit.processLinearMoves("G1 X10 Y20", None, None, None, 10, 20)

            mocks["isAnyPointExcluded"].assert_called_with(10, 20)
            mocks["enterExcludedRegion"].assert_not_called()
            self.assertEqual(
                result, (None,),
                "The result should indicate to drop/ignore the command"
            ) 
Example #18
Source File: test_ExcludeRegionState_processLinearMoves.py    From OctoPrint-ExcludeRegionPlugin with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_processLinearMoves_excluding_noPointInExcludedRegion(self):
        """Test processLinearMoves when points not in an excluded region and currently excluding."""
        mockLogger = mock.Mock()
        unit = ExcludeRegionState(mockLogger)
        unit.excluding = True
        unit.position = create_position(x=1, y=2, z=3, extruderPosition=4)
        unit.feedRate = 4000
        unit.feedRateUnitMultiplier = 1

        with mock.patch.multiple(
            unit,
            isAnyPointExcluded=mock.DEFAULT,
            exitExcludedRegion=mock.DEFAULT
        ) as mocks:
            mocks["isAnyPointExcluded"].return_value = False
            mocks["exitExcludedRegion"].return_value = ["expectedResult"]

            result = unit.processLinearMoves("G1 X10 Y20", None, None, None, 10, 20)

            mocks["isAnyPointExcluded"].assert_called_with(10, 20)
            mocks["exitExcludedRegion"].assert_called_with("G1 X10 Y20")
            self.assertEqual(
                result, ["expectedResult"],
                "The result of exitExcludedRegion should be returned."
            ) 
Example #19
Source File: test_ExcludeRegionState_processLinearMoves.py    From OctoPrint-ExcludeRegionPlugin with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_processLinearMoves_notExcluding_pointInExcludedRegion(self):
        """Test processLinearMoves with point in an excluded region and excluding=False."""
        mockLogger = mock.Mock()
        unit = ExcludeRegionState(mockLogger)
        unit.excluding = False
        unit.position = create_position(x=1, y=2, z=3, extruderPosition=4)
        unit.feedRate = 4000
        unit.feedRateUnitMultiplier = 1

        with mock.patch.multiple(
            unit,
            isAnyPointExcluded=mock.DEFAULT,
            enterExcludedRegion=mock.DEFAULT
        ) as mocks:
            mocks["isAnyPointExcluded"].return_value = True
            mocks["enterExcludedRegion"].return_value = ["expectedResult"]

            result = unit.processLinearMoves("G1 X10 Y20", None, None, None, 10, 20)

            mocks["isAnyPointExcluded"].assert_called_with(10, 20)
            mocks["enterExcludedRegion"].assert_called_with("G1 X10 Y20")
            self.assertEqual(
                result, ["expectedResult"],
                "The result of enterExcludedRegion should be returned."
            ) 
Example #20
Source File: test_apigateway.py    From awslimitchecker with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_find_usage(self):
        mock_conn = Mock()
        with patch('%s.connect' % pb) as mock_connect:
            with patch.multiple(
                pb,
                autospec=True,
                _find_usage_apis=DEFAULT,
                _find_usage_api_keys=DEFAULT,
                _find_usage_certs=DEFAULT,
                _find_usage_plans=DEFAULT,
                _find_usage_vpc_links=DEFAULT
            ) as mocks:
                cls = _ApigatewayService(21, 43, {}, None)
                cls.conn = mock_conn
                assert cls._have_usage is False
                cls.find_usage()
        assert mock_connect.mock_calls == [call()]
        assert cls._have_usage is True
        assert mock_conn.mock_calls == []
        assert mocks['_find_usage_apis'].mock_calls == [call(cls)]
        assert mocks['_find_usage_api_keys'].mock_calls == [call(cls)]
        assert mocks['_find_usage_certs'].mock_calls == [call(cls)]
        assert mocks['_find_usage_plans'].mock_calls == [call(cls)]
        assert mocks['_find_usage_vpc_links'].mock_calls == [call(cls)] 
Example #21
Source File: test_elasticbeanstalk.py    From awslimitchecker with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_find_usage(self):
        """test find usage method calls other methods"""
        mock_conn = Mock()
        with patch('%s.connect' % pb) as mock_connect:
            with patch.multiple(
                pb,
                _find_usage_applications=DEFAULT,
                _find_usage_application_versions=DEFAULT,
                _find_usage_environments=DEFAULT,
            ) as mocks:
                cls = _ElasticBeanstalkService(21, 43, {}, None)
                cls.conn = mock_conn
                assert cls._have_usage is False
                cls.find_usage()
        assert mock_connect.mock_calls == [call()]
        assert cls._have_usage is True
        assert mock_conn.mock_calls == []
        for x in [
            '_find_usage_applications',
            '_find_usage_application_versions',
            '_find_usage_environments',
        ]:
            assert mocks[x].mock_calls == [call()] 
Example #22
Source File: test_redshift.py    From awslimitchecker with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_find_usage(self):
        """test find usage method calls other methods"""
        mock_conn = Mock()
        with patch('%s.connect' % pb) as mock_connect:
            with patch.multiple(
                pb,
                _find_cluster_manual_snapshots=DEFAULT,
                _find_cluster_subnet_groups=DEFAULT,
            ) as mocks:
                cls = _RedshiftService(21, 43, {}, None)
                cls.conn = mock_conn
                assert cls._have_usage is False
                cls.find_usage()
        assert mock_connect.mock_calls == [call()]
        assert cls._have_usage is True
        assert mock_conn.mock_calls == []
        for x in [
            '_find_cluster_manual_snapshots',
            '_find_cluster_subnet_groups',
        ]:
            assert mocks[x].mock_calls == [call()] 
Example #23
Source File: test_checker.py    From awslimitchecker with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_check_version_not_old(self):
        with patch.multiple(
            'awslimitchecker.checker',
            logger=DEFAULT,
            _get_version_info=DEFAULT,
            TrustedAdvisor=DEFAULT,
            _get_latest_version=DEFAULT,
            autospec=True,
        ) as mocks:
            mocks['_get_version_info'].return_value = self.mock_ver_info
            mocks['_get_latest_version'].return_value = None
            AwsLimitChecker()
        assert mocks['_get_latest_version'].mock_calls == [call()]
        assert mocks['logger'].mock_calls == [
            call.debug('Connecting to region %s', None)
        ] 
Example #24
Source File: test_checker.py    From awslimitchecker with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_check_version_old(self):
        with patch.multiple(
            'awslimitchecker.checker',
            logger=DEFAULT,
            _get_version_info=DEFAULT,
            TrustedAdvisor=DEFAULT,
            _get_latest_version=DEFAULT,
            autospec=True,
        ) as mocks:
            mocks['_get_version_info'].return_value = self.mock_ver_info
            mocks['_get_latest_version'].return_value = '3.4.5'
            AwsLimitChecker()
        assert mocks['_get_latest_version'].mock_calls == [call()]
        assert mocks['logger'].mock_calls == [
            call.warning(
                'You are running awslimitchecker %s, but the latest version'
                ' is %s; please consider upgrading.', '1.2.3', '3.4.5'
            ),
            call.debug('Connecting to region %s', None)
        ] 
Example #25
Source File: test_retry.py    From gax-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_retryable_without_timeout(self, mock_time, mock_exc_to_code):
        mock_time.return_value = 0
        mock_exc_to_code.side_effect = lambda e: e.code

        to_attempt = 3
        mock_call = mock.Mock()
        mock_call.side_effect = ([CustomException('', _FAKE_STATUS_CODE_1)] *
                                 (to_attempt - 1) + [mock.DEFAULT])
        mock_call.return_value = 1729

        retry_options = RetryOptions(
            [_FAKE_STATUS_CODE_1],
            BackoffSettings(0, 0, 0, None, None, None, None))

        my_callable = retry.retryable(mock_call, retry_options)

        self.assertEqual(my_callable(None), 1729)
        self.assertEqual(to_attempt, mock_call.call_count) 
Example #26
Source File: test_retry.py    From gax-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_retryable_with_timeout(self, mock_time, mock_exc_to_code):
        mock_time.return_value = 1
        mock_exc_to_code.side_effect = lambda e: e.code

        mock_call = mock.Mock()
        mock_call.side_effect = [CustomException('', _FAKE_STATUS_CODE_1),
                                 mock.DEFAULT]
        mock_call.return_value = 1729

        retry_options = RetryOptions(
            [_FAKE_STATUS_CODE_1],
            BackoffSettings(0, 0, 0, 0, 0, 0, 0))

        my_callable = retry.retryable(mock_call, retry_options)

        self.assertRaises(errors.RetryError, my_callable)
        self.assertEqual(0, mock_call.call_count) 
Example #27
Source File: test_retry.py    From gax-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_retryable_when_no_codes(self, mock_time, mock_exc_to_code):
        mock_time.return_value = 0
        mock_exc_to_code.side_effect = lambda e: e.code

        mock_call = mock.Mock()
        mock_call.side_effect = [CustomException('', _FAKE_STATUS_CODE_1),
                                 mock.DEFAULT]
        mock_call.return_value = 1729

        retry_options = RetryOptions(
            [],
            BackoffSettings(0, 0, 0, 0, 0, 0, 1))

        my_callable = retry.retryable(mock_call, retry_options)

        try:
            my_callable(None)
            self.fail('Should not have been reached')
        except errors.RetryError as exc:
            self.assertIsInstance(exc.cause, CustomException)

        self.assertEqual(1, mock_call.call_count) 
Example #28
Source File: test_retry.py    From gax-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_retryable_aborts_on_unexpected_exception(
            self, mock_time, mock_exc_to_code):
        mock_time.return_value = 0
        mock_exc_to_code.side_effect = lambda e: e.code

        mock_call = mock.Mock()
        mock_call.side_effect = [CustomException('', _FAKE_STATUS_CODE_2),
                                 mock.DEFAULT]
        mock_call.return_value = 1729

        retry_options = RetryOptions(
            [_FAKE_STATUS_CODE_1],
            BackoffSettings(0, 0, 0, 0, 0, 0, 1))

        my_callable = retry.retryable(mock_call, retry_options)

        try:
            my_callable(None)
            self.fail('Should not have been reached')
        except errors.RetryError as exc:
            self.assertIsInstance(exc.cause, CustomException)

        self.assertEqual(1, mock_call.call_count) 
Example #29
Source File: test_api_callable.py    From gax-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_retry(self, mock_exc_to_code, mock_time):
        mock_exc_to_code.side_effect = lambda e: e.code
        to_attempt = 3
        retry = RetryOptions(
            [_FAKE_STATUS_CODE_1],
            BackoffSettings(0, 0, 0, 0, 0, 0, 1))

        # Succeeds on the to_attempt'th call, and never again afterward
        mock_call = mock.Mock()
        mock_call.side_effect = ([CustomException('', _FAKE_STATUS_CODE_1)] *
                                 (to_attempt - 1) + [mock.DEFAULT])
        mock_call.return_value = 1729
        mock_time.return_value = 0
        settings = _CallSettings(timeout=0, retry=retry)
        my_callable = api_callable.create_api_call(mock_call, settings)
        self.assertEqual(my_callable(None), 1729)
        self.assertEqual(mock_call.call_count, to_attempt) 
Example #30
Source File: conftest.py    From ensime-vim with MIT License 6 votes vote down vote up
def vim():
    """A wide-open mock vim object.

    We'll just have to be careful since we can't import a real vim object to
    use autospec and guarantee that we're calling real APIs.
    """
    def vimeval(expr):
        # Default Editor.isneovim to False.
        # TODO: easy way to override this; neovim mock fixture?
        if expr == "has('nvim')":
            return False
        else:
            return mock.DEFAULT

    attrs = {'eval.side_effect': vimeval}
    return mock.NonCallableMock(name='mockvim', **attrs)