mock.patch.multiple

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

51 Examples 7

3 Source : testntpd.py
with MIT License
from diamond-next

    def test_should_fail_gracefully(self, publish_mock):
        ntpq_data = Mock(return_value='')
        ntpdc_kerninfo_data = Mock(return_value='')
        ntpdc_sysinfo_data = Mock(return_value='')
        collector_mock = patch.multiple(
            NtpdCollector,
            get_ntpq_output=ntpq_data,
            get_ntpdc_kerninfo_output=ntpdc_kerninfo_data,
            get_ntpdc_sysinfo_output=ntpdc_sysinfo_data)

        collector_mock.start()
        self.collector.collect()
        collector_mock.stop()

        self.assertPublishedMany(publish_mock, {})

##########################################################################
if __name__ == "__main__":

3 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_force_preemptive(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fake_resp):
            auth = requests_gssapi.HTTPKerberosAuth(force_preemptive=True)

            request = requests.Request(url="http://www.example.org")

            auth.__call__(request)

            self.assertTrue('Authorization' in request.headers)
            self.assertEqual(request.headers.get('Authorization'),
                             b64_negotiate_response)

    def test_no_force_preemptive(self):

3 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_no_force_preemptive(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fake_resp):
            auth = requests_gssapi.HTTPKerberosAuth()

            request = requests.Request(url="http://www.example.org")

            auth.__call__(request)

            self.assertTrue('Authorization' not in request.headers)

    def test_generate_request_header(self):

3 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_generate_request_header(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fake_resp):
            response = requests.Response()
            response.url = "http://www.example.org/"
            response.headers = {'www-authenticate': b64_negotiate_token}
            host = urlparse(response.url).hostname
            auth = requests_gssapi.HTTPKerberosAuth()
            self.assertEqual(
                auth.generate_request_header(response, host),
                b64_negotiate_response)
            fake_init.assert_called_with(
                name=gssapi_sname("[email protected]"),
                creds=None, mech=None, flags=gssflags, usage="initiate")
            fake_resp.assert_called_with(b"token")

    def test_generate_request_header_init_error(self):

3 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_generate_request_header_init_error(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fail_resp):
            response = requests.Response()
            response.url = "http://www.example.org/"
            response.headers = {'www-authenticate': b64_negotiate_token}
            host = urlparse(response.url).hostname
            auth = requests_gssapi.HTTPKerberosAuth()
            self.assertRaises(requests_gssapi.exceptions.SPNEGOExchangeError,
                              auth.generate_request_header, response, host)
            fake_init.assert_called_with(
                name=gssapi_sname("[email protected]"),
                usage="initiate", flags=gssflags, creds=None, mech=None)

    def test_generate_request_header_step_error(self):

3 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_generate_request_header_step_error(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fail_resp):
            response = requests.Response()
            response.url = "http://www.example.org/"
            response.headers = {'www-authenticate': b64_negotiate_token}
            host = urlparse(response.url).hostname
            auth = requests_gssapi.HTTPKerberosAuth()
            self.assertRaises(requests_gssapi.exceptions.SPNEGOExchangeError,
                              auth.generate_request_header, response, host)
            fake_init.assert_called_with(
                name=gssapi_sname("[email protected]"),
                usage="initiate", flags=gssflags, creds=None, mech=None)
            fail_resp.assert_called_with(b"token")

    def test_authenticate_user(self):

3 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_authenticate_server(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fake_resp):
            response_ok = requests.Response()
            response_ok.url = "http://www.example.org/"
            response_ok.status_code = 200
            response_ok.headers = {
                'www-authenticate': b64_negotiate_server,
                'authorization': b64_negotiate_response}

            auth = requests_gssapi.HTTPKerberosAuth()
            auth.context = {"www.example.org": gssapi.SecurityContext}
            result = auth.authenticate_server(response_ok)

            self.assertTrue(result)
            fake_resp.assert_called_with(b"servertoken")

    def test_handle_other(self):

3 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_handle_response_200_mutual_auth_required_failure(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fake_resp):
            response_ok = requests.Response()
            response_ok.url = "http://www.example.org/"

            response_ok.status_code = 200
            response_ok.headers = {}

            auth = requests_gssapi.HTTPKerberosAuth(
                mutual_authentication=REQUIRED)
            auth.context = {"www.example.org": "CTX"}

            self.assertRaises(requests_gssapi.MutualAuthenticationError,
                              auth.handle_response, response_ok)

            self.assertFalse(fake_resp.called)

    def test_handle_response_200_mutual_auth_required_failure_2(self):

3 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_handle_response_200_mutual_auth_optional_soft_failure(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fake_resp):
            response_ok = requests.Response()
            response_ok.url = "http://www.example.org/"
            response_ok.status_code = 200

            auth = requests_gssapi.HTTPKerberosAuth(
                requests_gssapi.OPTIONAL)
            auth.context = {"www.example.org": gssapi.SecurityContext}

            r = auth.handle_response(response_ok)

            self.assertEqual(r, response_ok)

            self.assertFalse(fake_resp.called)

    def test_handle_response_500_mutual_auth_required_failure(self):

3 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_generate_request_header_custom_service(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fake_resp):
            response = requests.Response()
            response.url = "http://www.example.org/"
            response.headers = {'www-authenticate': b64_negotiate_token}
            host = urlparse(response.url).hostname
            auth = requests_gssapi.HTTPKerberosAuth(service="barfoo")
            auth.generate_request_header(response, host),
            fake_init.assert_called_with(
                name=gssapi_sname("[email protected]"),
                usage="initiate", flags=gssflags, creds=None, mech=None)
            fake_resp.assert_called_with(b"token")

    def test_delegation(self):

3 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_principal_override(self):
        with patch.multiple("gssapi.Credentials", __new__=fake_creds), \
             patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fake_resp):
            response = requests.Response()
            response.url = "http://www.example.org/"
            response.headers = {'www-authenticate': b64_negotiate_token}
            host = urlparse(response.url).hostname
            auth = requests_gssapi.HTTPKerberosAuth(principal="user@REALM")
            auth.generate_request_header(response, host)
            fake_creds.assert_called_with(gssapi.creds.Credentials,
                                          usage="initiate",
                                          name=gssapi_uname("user@REALM", ))
            fake_init.assert_called_with(
                name=gssapi_sname("[email protected]"),
                usage="initiate", flags=gssflags,
                creds=b"fake creds", mech=None)

    def test_realm_override(self):

3 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_realm_override(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fake_resp):
            response = requests.Response()
            response.url = "http://www.example.org/"
            response.headers = {'www-authenticate': b64_negotiate_token}
            host = urlparse(response.url).hostname
            auth = requests_gssapi.HTTPKerberosAuth(
                hostname_override="otherhost.otherdomain.org")
            auth.generate_request_header(response, host)
            fake_init.assert_called_with(
                name=gssapi_sname("[email protected]"),
                usage="initiate", flags=gssflags, creds=None, mech=None)
            fake_resp.assert_called_with(b"token")

    def test_opportunistic_auth(self):

3 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_opportunistic_auth(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fake_resp):
            auth = requests_gssapi.HTTPSPNEGOAuth(opportunistic_auth=True)

            request = requests.Request(url="http://www.example.org")

            auth.__call__(request)

            self.assertTrue('Authorization' in request.headers)
            self.assertEqual(request.headers.get('Authorization'),
                             b64_negotiate_response)

    def test_explicit_creds(self):

3 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_explicit_creds(self):
        with patch.multiple("gssapi.Credentials", __new__=fake_creds), \
             patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fake_resp):
            response = requests.Response()
            response.url = "http://www.example.org/"
            response.headers = {'www-authenticate': b64_negotiate_token}
            host = urlparse(response.url).hostname
            creds = gssapi.Credentials()
            auth = requests_gssapi.HTTPSPNEGOAuth(creds=creds)
            auth.generate_request_header(response, host)
            fake_init.assert_called_with(
                name=gssapi_sname("[email protected]"),
                usage="initiate", flags=gssflags,
                creds=b"fake creds", mech=None)
            fake_resp.assert_called_with(b"token")

    def test_explicit_mech(self):

3 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_explicit_mech(self):
        with patch.multiple("gssapi.Credentials", __new__=fake_creds), \
             patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fake_resp):
            response = requests.Response()
            response.url = "http://www.example.org/"
            response.headers = {'www-authenticate': b64_negotiate_token}
            host = urlparse(response.url).hostname
            fake_mech = b'fake mech'
            auth = requests_gssapi.HTTPSPNEGOAuth(mech=fake_mech)
            auth.generate_request_header(response, host)
            fake_init.assert_called_with(
                name=gssapi_sname("[email protected]"),
                usage="initiate", flags=gssflags,
                creds=None, mech=b'fake mech')
            fake_resp.assert_called_with(b"token")

    def test_target_name(self):

3 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_target_name(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fake_resp):
            response = requests.Response()
            response.url = "http://www.example.org/"
            response.headers = {'www-authenticate': b64_negotiate_token}
            host = urlparse(response.url).hostname
            auth = requests_gssapi.HTTPSPNEGOAuth(
                target_name="[email protected]")
            auth.generate_request_header(response, host)
            fake_init.assert_called_with(
                name=gssapi_sname("[email protected]"),
                usage="initiate", flags=gssflags, creds=None, mech=None)
            fake_resp.assert_called_with(b"token")


if __name__ == '__main__':

3 Source : testpatch.py
with GNU General Public License v3.0
from guohuadeng

    def test_patch_multiple_no_kwargs(self):
        self.assertRaises(ValueError, patch.multiple, foo_name)
        self.assertRaises(ValueError, patch.multiple, Foo)


    def test_patch_multiple_create_mocks(self):

3 Source : testpatch.py
with GNU General Public License v3.0
from guohuadeng

    def test_patch_multiple_create(self):
        patcher = patch.multiple(Foo, blam='blam')
        self.assertRaises(AttributeError, patcher.start)

        patcher = patch.multiple(Foo, blam='blam', create=True)
        patcher.start()
        try:
            self.assertEqual(Foo.blam, 'blam')
        finally:
            patcher.stop()

        self.assertFalse(hasattr(Foo, 'blam'))


    def test_patch_multiple_spec_set(self):

3 Source : testpatch.py
with GNU General Public License v3.0
from guohuadeng

    def test_patch_multiple_spec_set(self):
        # if spec_set works then we can assume that spec and autospec also
        # work as the underlying machinery is the same
        patcher = patch.multiple(Foo, foo=DEFAULT, spec_set=['a', 'b'])
        result = patcher.start()
        try:
            self.assertEqual(Foo.foo, result['foo'])
            Foo.foo.a(1)
            Foo.foo.b(2)
            Foo.foo.a.assert_called_with(1)
            Foo.foo.b.assert_called_with(2)
            self.assertRaises(AttributeError, setattr, Foo.foo, 'c', None)
        finally:
            patcher.stop()


    def test_patch_multiple_new_callable(self):

3 Source : testpatch.py
with GNU General Public License v3.0
from guohuadeng

    def test_patch_multiple_new_callable(self):
        class Thing(object):
            pass

        patcher = patch.multiple(
            Foo, f=DEFAULT, g=DEFAULT, new_callable=Thing
        )
        result = patcher.start()
        try:
            self.assertIs(Foo.f, result['f'])
            self.assertIs(Foo.g, result['g'])
            self.assertIsInstance(Foo.f, Thing)
            self.assertIsInstance(Foo.g, Thing)
            self.assertIsNot(Foo.f, Foo.g)
        finally:
            patcher.stop()


    def test_nested_patch_failure(self):

3 Source : testpatch.py
with GNU General Public License v3.0
from guohuadeng

    def test_patch_multiple_string_subclasses(self):
        for base in (str, unicode):
            Foo = type('Foo', (base,), {'fish': 'tasty'})
            foo = Foo()
            @patch.multiple(foo, fish='nearly gone')
            def test():
                self.assertEqual(foo.fish, 'nearly gone')

            test()
            self.assertEqual(foo.fish, 'tasty')


    @patch('mock.patch.TEST_PREFIX', 'foo')

3 Source : test_shell.py
with GNU General Public License v3.0
from kk7ds

    def _run(self, cmdline, expect_fail=False):
        out = FakeOutput()
        with mock.patch.multiple('sys', stdout=out, stderr=out, stdin=out):
            rc = shell.main(shlex.split(cmdline))
        print(out.getvalue())
        if not expect_fail:
            self.assertEqual(0, rc)
        else:
            self.assertNotEqual(0, rc)
        return out.getvalue()

    def test_first_run(self):

3 Source : test_shell.py
with GNU General Public License v3.0
from kk7ds

    def _run(self, cmdline, mock_cookies, expect_fail=False):
        mock_cookies.return_value.__enter__.return_value = self.cookies
        out = FakeOutput()
        with mock.patch.multiple('sys', stdout=out, stderr=out, stdin=out):
            rc = shell.main(shlex.split(cmdline))
        print(out.getvalue())
        if not expect_fail:
            self.assertEqual(0, rc)
        else:
            self.assertNotEqual(0, rc)
        return out.getvalue()

    def _import_sample_gpx(self):

3 Source : test_managers.py
with BSD 3-Clause "New" or "Revised" License
from W1ldPo1nter

    def test_iter(self):
        queryset = ApplicationWithClassBasedProperties.objects.order_by('pk')
        iterable = DummyIterable(queryset)
        mock_setup = Mock()
        mock_postprocess = Mock(side_effect=lambda obj: obj)
        with patch.multiple(iterable, _setup_queryable_properties=mock_setup,
                            _postprocess_queryable_properties=mock_postprocess):
            applications = list(iterable)
        assert applications == list(queryset)
        mock_setup.assert_called_once_with()
        assert mock_postprocess.call_count == len(applications)
        for application in applications:
            mock_postprocess.assert_any_call(application)


class TestLegacyOrderingMixin(object):

0 Source : test_calculate_electricity_cost.py
with MIT License
from BottlecapDave

async def test_when_electricity_consumption_available_then_calculation_returned(latest_date):
  # Arrange
  
  period_from = datetime.strptime("2022-02-28T00:00:00Z", "%Y-%m-%dT%H:%M:%S%z")
  period_to = datetime.strptime("2022-03-01T00:00:00Z", "%Y-%m-%dT%H:%M:%S%z")

  # Rate price is in pence
  expected_rate_price = 50

  async def async_mocked_get_electricity_rates(*args, **kwargs):
    return create_rate_data(period_from, period_to, [expected_rate_price])

  expected_standing_charge = {
    "value_exc_vat": 1,
    "value_inc_vat": 2
  }

  async def async_mocked_get_electricity_standing_charge(*args, **kwargs):
    return expected_standing_charge

  with mock.patch.multiple(OctopusEnergyApiClient, async_get_electricity_rates=async_mocked_get_electricity_rates, async_get_electricity_standing_charge=async_mocked_get_electricity_standing_charge):
    client = OctopusEnergyApiClient("NOT_REAL")
    tariff_code = "E-1R-SUPER-GREEN-24M-21-07-30-A"
    
    consumption_data = create_consumption_data(period_from, period_to)
    assert consumption_data != None
    assert len(consumption_data) == 48
    assert consumption_data[-1]["interval_end"] == period_to
    assert consumption_data[0]["interval_start"] == period_from

    # Act
    consumption_cost = await async_calculate_electricity_cost(
      client,
      consumption_data,
      latest_date,
      period_from,
      period_to,
      tariff_code
    )

    # Assert
    assert consumption_cost != None

    assert len(consumption_cost["charges"]) == 48

    assert consumption_cost["standing_charge"] == expected_standing_charge["value_inc_vat"]
    assert consumption_cost["total_without_standing_charge"] == round((48 * expected_rate_price) / 100, 2)
    assert consumption_cost["total"] == round(((48 * expected_rate_price) + expected_standing_charge["value_inc_vat"]) / 100, 2)
    assert consumption_cost["last_calculated_timestamp"] == consumption_data[-1]["interval_end"]

    # Make sure our data is returned in 30 minute increments
    expected_valid_from = period_from
    for item in consumption_cost["charges"]:
      expected_valid_to = expected_valid_from + timedelta(minutes=30)

      assert "from" in item
      assert item["from"] == expected_valid_from
      assert "to" in item
      assert item["to"] == expected_valid_to

      expected_valid_from = expected_valid_to

@pytest.mark.asyncio

0 Source : test_calculate_electricity_cost.py
with MIT License
from BottlecapDave

async def test_when_electricity_consumption_starting_at_latest_date_then_calculation_returned():
  # Arrange
  period_from = datetime.strptime("2022-02-28T00:00:00Z", "%Y-%m-%dT%H:%M:%S%z")
  period_to = datetime.strptime("2022-03-01T00:00:00Z", "%Y-%m-%dT%H:%M:%S%z")

  # Rate price is in pence
  expected_rate_price = 50

  async def async_mocked_get_electricity_rates(*args, **kwargs):
    return create_rate_data(period_from, period_to, [expected_rate_price])

  expected_standing_charge = {
    "value_exc_vat": 1,
    "value_inc_vat": 2
  }

  async def async_mocked_get_electricity_standing_charge(*args, **kwargs):
    return expected_standing_charge

  with mock.patch.multiple(OctopusEnergyApiClient, async_get_electricity_rates=async_mocked_get_electricity_rates, async_get_electricity_standing_charge=async_mocked_get_electricity_standing_charge):
    client = OctopusEnergyApiClient("NOT_REAL")
    tariff_code = "E-1R-SUPER-GREEN-24M-21-07-30-A"
    latest_date = None
    
    consumption_data = create_consumption_data(period_from, period_to, True)
    assert consumption_data != None
    assert len(consumption_data) > 0
    assert consumption_data[0]["interval_end"] == period_to
    assert consumption_data[-1]["interval_start"] == period_from

    # Make sure we have rates and standing charges available
    rates = await client.async_get_electricity_rates(tariff_code, period_from, period_to)
    assert rates != None
    assert len(rates) > 0

    standard_charge_result = await client.async_get_electricity_standing_charge(tariff_code, period_from, period_to)
    assert standard_charge_result != None

    # Act
    consumption_cost = await async_calculate_electricity_cost(
      client,
      consumption_data,
      latest_date,
      period_from,
      period_to,
      tariff_code
    )

    # Assert
    assert consumption_cost != None

    assert len(consumption_cost["charges"]) == 48

    assert consumption_cost["standing_charge"] == expected_standing_charge["value_inc_vat"]

    # Total is reported in pounds and pence, but rate prices are in pence, so we need to calculate our expected value
    assert consumption_cost["total_without_standing_charge"] == round((48 * expected_rate_price) / 100, 2)
    assert consumption_cost["total"] == round(((48 * expected_rate_price) + expected_standing_charge["value_inc_vat"]) / 100, 2)
    assert consumption_cost["last_calculated_timestamp"] == consumption_data[0]["interval_end"]

    # Make sure our data is returned in 30 minute increments
    expected_valid_from = period_from
    for item in consumption_cost["charges"]:
      expected_valid_to = expected_valid_from + timedelta(minutes=30)

      assert "from" in item
      assert item["from"] == expected_valid_from
      assert "to" in item
      assert item["to"] == expected_valid_to

      expected_valid_from = expected_valid_to

0 Source : test_calculate_gas_cost.py
with MIT License
from BottlecapDave

async def test_when_gas_consumption_available_then_calculation_returned(is_smets1_meter, latest_date):
  # Arrange
  
  period_from = datetime.strptime("2022-02-28T00:00:00Z", "%Y-%m-%dT%H:%M:%S%z")
  period_to = datetime.strptime("2022-03-01T00:00:00Z", "%Y-%m-%dT%H:%M:%S%z")

  # Price is in pence
  expected_rate_price = 50

  async def async_mocked_get_gas_rates(*args, **kwargs):
    return create_rate_data(period_from, period_to, [expected_rate_price])

  expected_standing_charge = {
    "value_exc_vat": 1,
    "value_inc_vat": 2
  }

  async def async_mocked_get_gas_standing_charge(*args, **kwargs):
    return expected_standing_charge

  with mock.patch.multiple(OctopusEnergyApiClient, async_get_gas_rates=async_mocked_get_gas_rates, async_get_gas_standing_charge=async_mocked_get_gas_standing_charge):
    client = OctopusEnergyApiClient("NOT_REAL")

    tariff_code = "G-1R-SUPER-GREEN-24M-21-07-30-A"
    
    consumption_data = create_consumption_data(period_from, period_to)
    assert consumption_data != None
    assert len(consumption_data) > 0
    assert consumption_data[-1]["interval_end"] == period_to
    assert consumption_data[0]["interval_start"] == period_from

    # Make sure we have rates and standing charges available
    rates = await client.async_get_gas_rates(tariff_code, period_from, period_to)
    assert rates != None
    assert len(rates) > 0

    standard_charge_result = await client.async_get_gas_standing_charge(tariff_code, period_from, period_to)
    assert standard_charge_result != None

    # Act
    consumption_cost = await async_calculate_gas_cost(
      client,
      consumption_data,
      latest_date,
      period_from,
      period_to,
      {
        "tariff_code": tariff_code,
        "is_smets1_meter": is_smets1_meter
      }
    )

    # Assert
    assert consumption_cost != None
    assert len(consumption_cost["charges"]) == 48

    assert consumption_cost["standing_charge"] == expected_standing_charge["value_inc_vat"]
    
    assert consumption_cost["last_calculated_timestamp"] == consumption_data[-1]["interval_end"]
    
    # Check that for SMETS2 meters, we convert the data from m3 to kwh
    if is_smets1_meter:
      
      # Total is reported in pounds and pence, but rate prices are in pence, so we need to calculate our expected value
      assert consumption_cost["total_without_standing_charge"] == round((48 * expected_rate_price) / 100, 2)
      assert consumption_cost["total"] == round(((48 * expected_rate_price) + expected_standing_charge["value_inc_vat"]) / 100, 2)
    else:
      # Total is reported in pounds and pence, but rate prices are in pence, so we need to calculate our expected value
      expected_total_values = 11.363
      assert consumption_cost["total_without_standing_charge"] == round((expected_total_values * 48 * expected_rate_price) / 100, 2)
      assert consumption_cost["total"] == round(((expected_total_values * 48 * expected_rate_price) + expected_standing_charge["value_inc_vat"]) / 100, 2)

    # Make sure our data is returned in 30 minute increments
    expected_valid_from = period_from
    for item in consumption_cost["charges"]:
      expected_valid_to = expected_valid_from + timedelta(minutes=30)

      assert "from" in item
      assert item["from"] == expected_valid_from
      assert "to" in item
      assert item["to"] == expected_valid_to

      expected_valid_from = expected_valid_to

@pytest.mark.asyncio

0 Source : test_calculate_gas_cost.py
with MIT License
from BottlecapDave

async def test_when_gas_consumption_starting_at_latest_date_then_calculation_returned():
  # Arrange
  period_from = datetime.strptime("2022-02-28T00:00:00Z", "%Y-%m-%dT%H:%M:%S%z")
  period_to = datetime.strptime("2022-03-01T00:00:00Z", "%Y-%m-%dT%H:%M:%S%z")

  # Price is in pence
  expected_rate_price = 50

  async def async_mocked_get_gas_rates(*args, **kwargs):
    return create_rate_data(period_from, period_to, [expected_rate_price])

  expected_standing_charge = {
    "value_exc_vat": 1,
    "value_inc_vat": 2
  }

  async def async_mocked_get_gas_standing_charge(*args, **kwargs):
    return expected_standing_charge

  with mock.patch.multiple(OctopusEnergyApiClient, async_get_gas_rates=async_mocked_get_gas_rates, async_get_gas_standing_charge=async_mocked_get_gas_standing_charge):
    client = OctopusEnergyApiClient("NOT_REAL")
    tariff_code = "G-1R-SUPER-GREEN-24M-21-07-30-A"
    latest_date = None
    is_smets1_meter = True
    
    consumption_data = create_consumption_data(period_from, period_to, True)
    assert consumption_data != None
    assert len(consumption_data) > 0
    assert consumption_data[0]["interval_end"] == period_to
    assert consumption_data[-1]["interval_start"] == period_from

    # Make sure we have rates and standing charges available
    rates = await client.async_get_gas_rates(tariff_code, period_from, period_to)
    assert rates != None
    assert len(rates) > 0

    standard_charge_result = await client.async_get_gas_standing_charge(tariff_code, period_from, period_to)
    assert standard_charge_result != None

    # Act
    consumption_cost = await async_calculate_gas_cost(
      client,
      consumption_data,
      latest_date,
      period_from,
      period_to,
      {
        "tariff_code": tariff_code,
        "is_smets1_meter": is_smets1_meter
      }
    )

    # Assert
    assert consumption_cost != None
    assert len(consumption_cost["charges"]) == 48

    assert consumption_cost["last_calculated_timestamp"] == consumption_data[0]["interval_end"]
    assert consumption_cost["standing_charge"] == expected_standing_charge["value_inc_vat"]

    # Total is reported in pounds and pence, but rate prices are in pence, so we need to calculate our expected value
    assert consumption_cost["total_without_standing_charge"] == round((48 * expected_rate_price) / 100, 2)
    assert consumption_cost["total"] == round(((48 * expected_rate_price) + expected_standing_charge["value_inc_vat"]) / 100, 2)

    # Make sure our data is returned in 30 minute increments
    expected_valid_from = period_from
    for item in consumption_cost["charges"]:
      expected_valid_to = expected_valid_from + timedelta(minutes=30)

      assert "from" in item
      assert item["from"] == expected_valid_from
      assert "to" in item
      assert item["to"] == expected_valid_to

      expected_valid_from = expected_valid_to

0 Source : test_streaming.py
with MIT License
from dalinhuang99

    def test_read_empty_buffer(self):
        """
        Requests can be closed by twitter.
        The ReadBuffer should not loop infinitely when this happens.
        Instead it should return and let the outer _read_loop handle it.
        """

        # If the test fails, we are in danger of an infinite loop
        # so we need to do some work to block that from happening
        class InfiniteLoopException(Exception):
            pass

        self.called_count = 0
        call_limit = 5
        def on_read(chunk_size):
            self.called_count += 1

            if self.called_count > call_limit:
                # we have failed
                raise InfiniteLoopException("Oops, read() was called a bunch of times")

            return ""

        # Create a fake stream
        stream = six.BytesIO(six.b(''))

        # Mock it's read function so it can't be called too many times
        mock_read = MagicMock(side_effect=on_read)

        try:
            stream.close()
            with patch.multiple(stream, create=True, read=mock_read):
                # Now the stream can't call 'read' more than call_limit times
                # and it looks like a requests stream that is closed
                buf = ReadBuffer(stream, 50)
                buf.read_line("\n")
        except InfiniteLoopException:
            self.fail("ReadBuffer.read_line tried to loop infinitely.")

        # The mocked function not have been called at all since the stream looks closed
        self.assertEqual(mock_read.call_count, 0)

    def test_read_unicode_tweet(self):

0 Source : testntpd.py
with MIT License
from diamond-next

    def test_should_work_wtih_real_data(self, publish_mock):
        ntpq_data = Mock(
            return_value=self.getFixture('ntpq').getvalue())
        ntpdc_kerninfo_data = Mock(
            return_value=self.getFixture('ntpdc_kerninfo').getvalue())
        ntpdc_sysinfo_data = Mock(
            return_value=self.getFixture('ntpdc_sysinfo').getvalue())
        collector_mock = patch.multiple(
            NtpdCollector,
            get_ntpq_output=ntpq_data,
            get_ntpdc_kerninfo_output=ntpdc_kerninfo_data,
            get_ntpdc_sysinfo_output=ntpdc_sysinfo_data)

        collector_mock.start()
        self.collector.collect()
        collector_mock.stop()

        metrics = {
            'jitter': 0.026,
            'when': 39,
            'stratum': 2,
            'reach': 377,
            'delay': 0.127,
            'poll': 1024,
            'max_error': 0.039793,
            'est_error': 5.1e-05,
            'frequency': -14.24,
            'offset': -5.427e-06,
            'root_distance': 0.07663,
            'root_dispersion': 0.09311
        }

        self.setDocExample(collector=self.collector.__class__.__name__,
                           metrics=metrics,
                           defaultpath=self.collector.config['path'])
        self.assertPublishedMany(publish_mock, metrics)

    @patch.object(Collector, 'publish')

0 Source : test_msvc.py
with GNU General Public License v3.0
from ezaquarii

def mock_reg(hkcu=None, hklm=None):
    """
    Return a mock for distutils.msvc9compiler.Reg, patched
    to mock out the functions that access the registry.
    """

    _winreg = getattr(distutils.msvc9compiler, '_winreg', None)
    winreg = getattr(distutils.msvc9compiler, 'winreg', _winreg)

    hives = {
        winreg.HKEY_CURRENT_USER: hkcu or {},
        winreg.HKEY_LOCAL_MACHINE: hklm or {},
    }

    @classmethod
    def read_keys(cls, base, key):
        """Return list of registry keys."""
        hive = hives.get(base, {})
        return [
            k.rpartition('\\')[2]
            for k in hive if k.startswith(key.lower())
        ]

    @classmethod
    def read_values(cls, base, key):
        """Return dict of registry keys and values."""
        hive = hives.get(base, {})
        return dict(
            (k.rpartition('\\')[2], hive[k])
            for k in hive if k.startswith(key.lower())
        )

    return mock.patch.multiple(
        distutils.msvc9compiler.Reg,
        read_keys=read_keys, read_values=read_values)


class TestModulePatch:

0 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_authenticate_user(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fake_resp):
            response_ok = requests.Response()
            response_ok.url = "http://www.example.org/"
            response_ok.status_code = 200
            response_ok.headers = {'www-authenticate': b64_negotiate_server}

            connection = Mock()
            connection.send = Mock(return_value=response_ok)

            raw = Mock()
            raw.release_conn = Mock(return_value=None)

            request = requests.Request()
            response = requests.Response()
            response.request = request
            response.url = "http://www.example.org/"
            response.headers = {'www-authenticate': b64_negotiate_token}
            response.status_code = 401
            response.connection = connection
            response._content = ""
            response.raw = raw
            auth = requests_gssapi.HTTPKerberosAuth()
            r = auth.authenticate_user(response)

            self.assertTrue(response in r.history)
            self.assertEqual(r, response_ok)
            self.assertEqual(request.headers['Authorization'],
                             b64_negotiate_response)
            connection.send.assert_called_with(request)
            raw.release_conn.assert_called_with()
            fake_init.assert_called_with(
                name=gssapi_sname("[email protected]"),
                flags=gssflags, usage="initiate", creds=None, mech=None)
            fake_resp.assert_called_with(b"token")

    def test_handle_401(self):

0 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_handle_401(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fake_resp):
            response_ok = requests.Response()
            response_ok.url = "http://www.example.org/"
            response_ok.status_code = 200
            response_ok.headers = {'www-authenticate': b64_negotiate_server}

            connection = Mock()
            connection.send = Mock(return_value=response_ok)

            raw = Mock()
            raw.release_conn = Mock(return_value=None)

            request = requests.Request()
            response = requests.Response()
            response.request = request
            response.url = "http://www.example.org/"
            response.headers = {'www-authenticate': b64_negotiate_token}
            response.status_code = 401
            response.connection = connection
            response._content = ""
            response.raw = raw
            auth = requests_gssapi.HTTPKerberosAuth()
            r = auth.handle_401(response)

            self.assertTrue(response in r.history)
            self.assertEqual(r, response_ok)
            self.assertEqual(request.headers['Authorization'],
                             b64_negotiate_response)
            connection.send.assert_called_with(request)
            raw.release_conn.assert_called_with()
            fake_init.assert_called_with(
                name=gssapi_sname("[email protected]"),
                creds=None, mech=None, flags=gssflags, usage="initiate")
            fake_resp.assert_called_with(b"token")

    def test_authenticate_server(self):

0 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_handle_other(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fake_resp):
            response_ok = requests.Response()
            response_ok.url = "http://www.example.org/"
            response_ok.status_code = 200
            response_ok.headers = {
                'www-authenticate': b64_negotiate_server,
                'authorization': b64_negotiate_response}

            auth = requests_gssapi.HTTPKerberosAuth(
                mutual_authentication=REQUIRED)
            auth.context = {"www.example.org": gssapi.SecurityContext}

            r = auth.handle_other(response_ok)

            self.assertEqual(r, response_ok)
            fake_resp.assert_called_with(b"servertoken")

    def test_handle_response_200(self):

0 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_handle_response_200(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fake_resp):
            response_ok = requests.Response()
            response_ok.url = "http://www.example.org/"
            response_ok.status_code = 200
            response_ok.headers = {
                'www-authenticate': b64_negotiate_server,
                'authorization': b64_negotiate_response}

            auth = requests_gssapi.HTTPKerberosAuth(
                mutual_authentication=REQUIRED)
            auth.context = {"www.example.org": gssapi.SecurityContext}

            r = auth.handle_response(response_ok)

            self.assertEqual(r, response_ok)
            fake_resp.assert_called_with(b"servertoken")

    def test_handle_response_200_mutual_auth_required_failure(self):

0 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_handle_response_200_mutual_auth_required_failure_2(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fail_resp):
            response_ok = requests.Response()
            response_ok.url = "http://www.example.org/"
            response_ok.status_code = 200
            response_ok.headers = {
                'www-authenticate': b64_negotiate_server,
                'authorization': b64_negotiate_response}

            auth = requests_gssapi.HTTPKerberosAuth(
                mutual_authentication=REQUIRED)
            auth.context = {"www.example.org": gssapi.SecurityContext}

            self.assertRaises(requests_gssapi.MutualAuthenticationError,
                              auth.handle_response, response_ok)

            fail_resp.assert_called_with(b"servertoken")

    def test_handle_response_200_mutual_auth_optional_hard_failure(self):

0 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_handle_response_200_mutual_auth_optional_hard_failure(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fail_resp):
            response_ok = requests.Response()
            response_ok.url = "http://www.example.org/"
            response_ok.status_code = 200
            response_ok.headers = {
                'www-authenticate': b64_negotiate_server,
                'authorization': b64_negotiate_response}

            auth = requests_gssapi.HTTPKerberosAuth(
                requests_gssapi.OPTIONAL)
            auth.context = {"www.example.org": gssapi.SecurityContext}

            self.assertRaises(requests_gssapi.MutualAuthenticationError,
                              auth.handle_response, response_ok)

            fail_resp.assert_called_with(b"servertoken")

    def test_handle_response_200_mutual_auth_optional_soft_failure(self):

0 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_handle_response_500_mutual_auth_required_failure(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fail_resp):
            response_500 = requests.Response()
            response_500.url = "http://www.example.org/"
            response_500.status_code = 500
            response_500.headers = {}
            response_500.request = "REQUEST"
            response_500.connection = "CONNECTION"
            response_500._content = "CONTENT"
            response_500.encoding = "ENCODING"
            response_500.raw = "RAW"
            response_500.cookies = "COOKIES"

            auth = requests_gssapi.HTTPKerberosAuth(
                mutual_authentication=REQUIRED)
            auth.context = {"www.example.org": "CTX"}

            r = auth.handle_response(response_500)

            self.assertTrue(
                isinstance(r, requests_gssapi.gssapi_.SanitizedResponse))
            self.assertNotEqual(r, response_500)
            self.assertNotEqual(r.headers, response_500.headers)
            self.assertEqual(r.status_code, response_500.status_code)
            self.assertEqual(r.encoding, response_500.encoding)
            self.assertEqual(r.raw, response_500.raw)
            self.assertEqual(r.url, response_500.url)
            self.assertEqual(r.reason, response_500.reason)
            self.assertEqual(r.connection, response_500.connection)
            self.assertEqual(r.content, '')
            self.assertNotEqual(r.cookies, response_500.cookies)

            self.assertFalse(fail_resp.called)

            # re-test with error response sanitizing disabled
            auth = requests_gssapi.HTTPKerberosAuth(
                sanitize_mutual_error_response=False)
            auth.context = {"www.example.org": "CTX"}

            r = auth.handle_response(response_500)

            self.assertFalse(
                isinstance(r, requests_gssapi.gssapi_.SanitizedResponse))

    def test_handle_response_500_mutual_auth_optional_failure(self):

0 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_handle_response_500_mutual_auth_optional_failure(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fail_resp):
            response_500 = requests.Response()
            response_500.url = "http://www.example.org/"
            response_500.status_code = 500
            response_500.headers = {}
            response_500.request = "REQUEST"
            response_500.connection = "CONNECTION"
            response_500._content = "CONTENT"
            response_500.encoding = "ENCODING"
            response_500.raw = "RAW"
            response_500.cookies = "COOKIES"

            auth = requests_gssapi.HTTPKerberosAuth(
                requests_gssapi.OPTIONAL)
            auth.context = {"www.example.org": "CTX"}

            r = auth.handle_response(response_500)

            self.assertEqual(r, response_500)

            self.assertFalse(fail_resp.called)

    def test_handle_response_401(self):

0 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_handle_response_401(self):
        # Get a 401 from server, authenticate, and get a 200 back.
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fake_resp):
            response_ok = requests.Response()
            response_ok.url = "http://www.example.org/"
            response_ok.status_code = 200
            response_ok.headers = {'www-authenticate': b64_negotiate_server}

            connection = Mock()
            connection.send = Mock(return_value=response_ok)

            raw = Mock()
            raw.release_conn = Mock(return_value=None)

            request = requests.Request()
            response = requests.Response()
            response.request = request
            response.url = "http://www.example.org/"
            response.headers = {'www-authenticate': b64_negotiate_token}
            response.status_code = 401
            response.connection = connection
            response._content = ""
            response.raw = raw

            auth = requests_gssapi.HTTPKerberosAuth()
            auth.handle_other = Mock(return_value=response_ok)

            r = auth.handle_response(response)

            self.assertTrue(response in r.history)
            auth.handle_other.assert_called_once_with(response_ok)
            self.assertEqual(r, response_ok)
            self.assertEqual(request.headers['Authorization'],
                             b64_negotiate_response)
            connection.send.assert_called_with(request)
            raw.release_conn.assert_called_with()
            fake_init.assert_called_with(
                name=gssapi_sname("[email protected]"),
                usage="initiate", flags=gssflags, creds=None, mech=None)
            fake_resp.assert_called_with(b"token")

    def test_handle_response_401_rejected(self):

0 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_handle_response_401_rejected(self):
        # Get a 401 from server, authenticate, and get another 401 back.
        # Ensure there is no infinite recursion.
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fake_resp):
            connection = Mock()

            def connection_send(self, *args, **kwargs):
                reject = requests.Response()
                reject.url = "http://www.example.org/"
                reject.status_code = 401
                reject.connection = connection
                return reject

            connection.send.side_effect = connection_send

            raw = Mock()
            raw.release_conn.return_value = None

            request = requests.Request()
            response = requests.Response()
            response.request = request
            response.url = "http://www.example.org/"
            response.headers = {'www-authenticate': b64_negotiate_token}
            response.status_code = 401
            response.connection = connection
            response._content = ""
            response.raw = raw

            auth = requests_gssapi.HTTPKerberosAuth()

            r = auth.handle_response(response)

            self.assertEqual(r.status_code, 401)
            self.assertEqual(request.headers['Authorization'],
                             b64_negotiate_response)
            connection.send.assert_called_with(request)
            raw.release_conn.assert_called_with()
            fake_init.assert_called_with(
                name=gssapi_sname("[email protected]"),
                usage="initiate", flags=gssflags, creds=None, mech=None)
            fake_resp.assert_called_with(b"token")

    def test_generate_request_header_custom_service(self):

0 Source : test_requests_gssapi.py
with Apache License 2.0
from gethue

    def test_delegation(self):
        with patch.multiple("gssapi.SecurityContext", __init__=fake_init,
                            step=fake_resp):
            response_ok = requests.Response()
            response_ok.url = "http://www.example.org/"
            response_ok.status_code = 200
            response_ok.headers = {'www-authenticate': b64_negotiate_server}

            connection = Mock()
            connection.send = Mock(return_value=response_ok)

            raw = Mock()
            raw.release_conn = Mock(return_value=None)

            request = requests.Request()
            response = requests.Response()
            response.request = request
            response.url = "http://www.example.org/"
            response.headers = {'www-authenticate': b64_negotiate_token}
            response.status_code = 401
            response.connection = connection
            response._content = ""
            response.raw = raw
            auth = requests_gssapi.HTTPKerberosAuth(service="HTTP",
                                                    delegate=True)
            r = auth.authenticate_user(response)

            self.assertTrue(response in r.history)
            self.assertEqual(r, response_ok)
            self.assertEqual(request.headers['Authorization'],
                             b64_negotiate_response)
            connection.send.assert_called_with(request)
            raw.release_conn.assert_called_with()
            fake_init.assert_called_with(
                name=gssapi_sname("[email protected]"),
                usage="initiate", flags=gssdelegflags, creds=None, mech=None)
            fake_resp.assert_called_with(b"token")

    def test_principal_override(self):

0 Source : testpatch.py
with GNU General Public License v3.0
from guohuadeng

    def test_patch_multiple(self):
        original_foo = Foo
        original_f = Foo.f
        original_g = Foo.g

        patcher1 = patch.multiple(foo_name, f=1, g=2)
        patcher2 = patch.multiple(Foo, f=1, g=2)

        for patcher in patcher1, patcher2:
            patcher.start()
            try:
                self.assertIs(Foo, original_foo)
                self.assertEqual(Foo.f, 1)
                self.assertEqual(Foo.g, 2)
            finally:
                patcher.stop()

            self.assertIs(Foo, original_foo)
            self.assertEqual(Foo.f, original_f)
            self.assertEqual(Foo.g, original_g)


        @patch.multiple(foo_name, f=3, g=4)
        def test():
            self.assertIs(Foo, original_foo)
            self.assertEqual(Foo.f, 3)
            self.assertEqual(Foo.g, 4)

        test()


    def test_patch_multiple_no_kwargs(self):

0 Source : testpatch.py
with GNU General Public License v3.0
from guohuadeng

    def test_patch_multiple_create_mocks(self):
        original_foo = Foo
        original_f = Foo.f
        original_g = Foo.g

        @patch.multiple(foo_name, f=DEFAULT, g=3, foo=DEFAULT)
        def test(f, foo):
            self.assertIs(Foo, original_foo)
            self.assertIs(Foo.f, f)
            self.assertEqual(Foo.g, 3)
            self.assertIs(Foo.foo, foo)
            self.assertTrue(is_instance(f, MagicMock))
            self.assertTrue(is_instance(foo, MagicMock))

        test()
        self.assertEqual(Foo.f, original_f)
        self.assertEqual(Foo.g, original_g)


    def test_patch_multiple_create_mocks_different_order(self):

0 Source : testpatch.py
with GNU General Public License v3.0
from guohuadeng

    def test_patch_multiple_stacked_decorators(self):
        original_foo = Foo
        original_f = Foo.f
        original_g = Foo.g

        @patch.multiple(foo_name, f=DEFAULT)
        @patch.multiple(foo_name, foo=DEFAULT)
        @patch(foo_name + '.g')
        def test1(g, **kwargs):
            _test(g, **kwargs)

        @patch.multiple(foo_name, f=DEFAULT)
        @patch(foo_name + '.g')
        @patch.multiple(foo_name, foo=DEFAULT)
        def test2(g, **kwargs):
            _test(g, **kwargs)

        @patch(foo_name + '.g')
        @patch.multiple(foo_name, f=DEFAULT)
        @patch.multiple(foo_name, foo=DEFAULT)
        def test3(g, **kwargs):
            _test(g, **kwargs)

        def _test(g, **kwargs):
            f = kwargs.pop('f')
            foo = kwargs.pop('foo')
            self.assertFalse(kwargs)

            self.assertIs(Foo, original_foo)
            self.assertIs(Foo.f, f)
            self.assertIs(Foo.g, g)
            self.assertIs(Foo.foo, foo)
            self.assertTrue(is_instance(f, MagicMock))
            self.assertTrue(is_instance(g, MagicMock))
            self.assertTrue(is_instance(foo, MagicMock))

        test1()
        test2()
        test3()
        self.assertEqual(Foo.f, original_f)
        self.assertEqual(Foo.g, original_g)


    def test_patch_multiple_create_mocks_patcher(self):

0 Source : testpatch.py
with GNU General Public License v3.0
from guohuadeng

    def test_patch_multiple_create_mocks_patcher(self):
        original_foo = Foo
        original_f = Foo.f
        original_g = Foo.g

        patcher = patch.multiple(foo_name, f=DEFAULT, g=3, foo=DEFAULT)

        result = patcher.start()
        try:
            f = result['f']
            foo = result['foo']
            self.assertEqual(set(result), set(['f', 'foo']))

            self.assertIs(Foo, original_foo)
            self.assertIs(Foo.f, f)
            self.assertIs(Foo.foo, foo)
            self.assertTrue(is_instance(f, MagicMock))
            self.assertTrue(is_instance(foo, MagicMock))
        finally:
            patcher.stop()

        self.assertEqual(Foo.f, original_f)
        self.assertEqual(Foo.g, original_g)


    def test_patch_multiple_decorating_class(self):

0 Source : testpatch.py
with GNU General Public License v3.0
from guohuadeng

    def test_patch_multiple_decorating_class(self):
        test = self
        original_foo = Foo
        original_f = Foo.f
        original_g = Foo.g

        class SomeTest(object):

            def _test(self, f, foo):
                test.assertIs(Foo, original_foo)
                test.assertIs(Foo.f, f)
                test.assertEqual(Foo.g, 3)
                test.assertIs(Foo.foo, foo)
                test.assertTrue(is_instance(f, MagicMock))
                test.assertTrue(is_instance(foo, MagicMock))

            def test_two(self, f, foo):
                self._test(f, foo)
            def test_one(self, f, foo):
                self._test(f, foo)

        SomeTest = patch.multiple(
            foo_name, f=DEFAULT, g=3, foo=DEFAULT
        )(SomeTest)

        thing = SomeTest()
        thing.test_one()
        thing.test_two()

        self.assertEqual(Foo.f, original_f)
        self.assertEqual(Foo.g, original_g)


    def test_patch_multiple_create(self):

0 Source : testpatch.py
with GNU General Public License v3.0
from guohuadeng

    def test_wrapped_patch_multiple(self):
        decorated = patch.multiple('sys', modules={})(function)
        self.assertIs(decorated.__wrapped__, function)

    def test_stopall_lifo(self):

0 Source : test_shell.py
with GNU General Public License v3.0
from kk7ds

    def test_upload_existing_folder(self, mock_delete, mock_put, mock_upload):
        mock_upload.return_value = {'id': '105', 'properties': {
            'name': 'foo.gpx'}}

        folders_copy = copy.deepcopy(FakeClient.FOLDERS)
        folders_copy.append({'id': '105',
                             'title': 'foo.gpx',
                             'folder': None,
                             'properties': {}})

        waypoints_copy = copy.deepcopy(FakeClient.WAYPOINTS)
        waypoints_copy.append({'id': '010', 'folder': '105', 'title': 'wpt8'})
        waypoints_copy.append({'id': '011', 'folder': '105', 'title': 'wpt9'})

        tracks_copy = copy.deepcopy(FakeClient.TRACKS)
        tracks_copy.append({'id': '210', 'folder': '105', 'title': 'trk8'})
        tracks_copy.append({'id': '211', 'folder': '105', 'title': 'trk9'})

        with mock.patch.multiple(FakeClient,
                                 FOLDERS=folders_copy,
                                 WAYPOINTS=waypoints_copy,
                                 TRACKS=tracks_copy):
            self._run('upload --existing-folder folder1 foo.gpx')

        expected = copy.deepcopy(FakeClient.FOLDERS[0])
        expected['parent'] = None
        expected['children'] = ['103']
        expected['maps'] = []
        expected['waypoints'] = ['002', '010', '011']
        expected['tracks'] = ['210', '211']
        expected['properties'] = {'time_created': '2019-01-01T02:03:04Z'}
        mock_put.assert_called_once_with('folder', expected)
        mock_delete.assert_called_once_with('folder', '105')

    @mock.patch.object(FakeClient, 'upload_file')

0 Source : test_shell.py
with GNU General Public License v3.0
from kk7ds

    def test_upload_new_folder(self, mock_create, mock_delete, mock_put,
                               mock_upload):
        mock_upload.return_value = {'id': '105', 'properties': {
            'name': 'foo.gpx'}}

        folders_copy = copy.deepcopy(FakeClient.FOLDERS)
        folders_copy.append({'id': '105',
                             'title': 'foo.gpx',
                             'folder': None,
                             'properties': {}})
        folders_copy.append({'id': '106',
                             'title': 'newfolder',
                             'folder': None,
                             'properties': {'name': 'newfolder'}})

        mock_create.return_value = folders_copy[-1]

        waypoints_copy = copy.deepcopy(FakeClient.WAYPOINTS)
        waypoints_copy.append({'id': '010', 'folder': '105', 'title': 'wpt8'})
        waypoints_copy.append({'id': '011', 'folder': '105', 'title': 'wpt9'})

        tracks_copy = copy.deepcopy(FakeClient.TRACKS)
        tracks_copy.append({'id': '210', 'folder': '105', 'title': 'trk8'})
        tracks_copy.append({'id': '211', 'folder': '105', 'title': 'trk9'})

        with mock.patch.multiple(FakeClient,
                                 FOLDERS=folders_copy,
                                 WAYPOINTS=waypoints_copy,
                                 TRACKS=tracks_copy):
            self._run('upload --new-folder newfolder foo.gpx')

        expected = copy.deepcopy(folders_copy[-1])
        expected['parent'] = None
        expected['children'] = []
        expected['maps'] = []
        expected['waypoints'] = ['010', '011']
        expected['tracks'] = ['210', '211']
        expected['properties'] = {'time_created': '2019-01-01T02:03:04Z'}
        mock_put.assert_called_once_with('folder', expected)
        mock_delete.assert_called_once_with('folder', '105')

    @mock.patch.object(FakeClient, 'upload_file')

See More Examples