def setUp(self): # Mock resource model resource1 = MagicMock() resource1.name = 'Resource1' resource1.version = '1.0' resource1.description = 'Test resource 1' resource1.content_type = 'text/plain' resource1.state = 'created' resource1.open = False resource1.get_url.return_value = 'http://localhost/media/resources/resource1' resource2 = MagicMock() resource2.name = 'Resource2' resource2.version = '2.0' resource2.description = 'Test resource 2' resource2.content_type = 'text/plain' resource2.state = 'created' resource2.open = False resource2.get_url.return_value = 'http://localhost/media/resources/resource2' resource3 = MagicMock() resource3.name = 'Resource3' resource3.version = '2.0' resource3.description = 'Test resource 3' resource3.content_type = 'text/plain' resource3.state = 'created' resource3.open = True resource3.get_url.return_value = 'http://localhost/media/resources/resource3' resource4 = MagicMock() resource4.name = 'Resource4' resource4.version = '1.0' resource4.description = 'Test resource 4' resource4.content_type = 'text/plain' resource4.state = 'created' resource4.open = True resource4.get_url.return_value = 'http://localhost/media/resources/resource4' resource4.offerings = ['1111', '2222'] resources_management.Resource = MagicMock() resources_management.Resource.objects.filter.return_value = [ resource1, resource2, resource3, resource4 ] self.user = MagicMock() self.org = MagicMock() self.user.userprofile.current_organization = self.org
def test_ChuteApi_get_chute(ChuteStorage, ChuteContainer): update_manager = MagicMock() api = chute_api.ChuteApi(update_manager) request = MagicMock() request.user = User.get_internal_user() container = MagicMock() container.getStatus.return_value = "running" ChuteContainer.return_value = container chute = MagicMock() chute.name = "test" chute.version = 5 chute.environment = {} chute.resources = {} ChuteStorage.chuteList = {"test": chute} data = api.get_chute(request, chute.name) assert isinstance(data, basestring) result = json.loads(data) assert result['name'] == chute.name assert result['version'] == chute.version
def fixture_mocked_ubiconfig_load_all(): with patch("ubiconfig.get_loader") as get_loader: m = MagicMock() m.file_name = "test" m.version = "7" get_loader.return_value.load_all.return_value = [m] yield get_loader
def test_ChuteApi_get_chutes(ChuteStorage, ChuteContainer): update_manager = MagicMock() api = chute_api.ChuteApi(update_manager) request = MagicMock() container = MagicMock() container.getStatus.return_value = "running" ChuteContainer.return_value = container storage = MagicMock() ChuteStorage.return_value = storage chute = MagicMock() chute.environment = {} chute.name = "test" chute.state = "running" chute.resources = {} chute.version = 5 chute.get_owner.return_value = "paradrop" storage.getChuteList.return_value = [chute] data = api.get_chutes(request) assert isinstance(data, basestring) result = json.loads(data) assert result[0]['name'] == chute.name assert result[0]['version'] == chute.version
def test_create_request_with_right_context_params(self, parent_breadcrumbs_from, api_breadcrumb_filters, settings): http_request = MagicMock() mock_api = MagicMock() mock_api.name = 'api_name' mock_api.version = '1.0.0.1' http_request.user.is_anonymous.return_value = False request_body = MagicMock() settings.TIME_ZONE = expected_timezone = MagicMock() request = api_request_builder.build_request(http_request=http_request, url='candidates', api=mock_api, request_data={}, request_body=request_body) assert_that(request.context_params, has_entry('protocol', 'http')) assert_that(request.context_params, has_entry('url', 'candidates')) assert_that(request.context_params, has_entry('timezone', expected_timezone)) assert_that(request.context_params, has_entry('api_version', mock_api.version)) assert_that(request.context_params, has_entry('api_name', mock_api.name))
def test_external_network_cmds_no_ext(self): ds = { 'deploy_options': { 'sdn_controller': 'opendaylight', 'dataplane': 'ovs' } } cidr = MagicMock() cidr.version = 6 ns_dict = { 'apex': { 'networks': { 'admin': { 'introspection_range': (0, 1), 'nic_mapping': { 'compute': { 'vlan': '123' } }, 'gateway': 'gw', 'cidr': cidr } } } } ns = MagicMock() ns.enabled_network_list = ['admin'] ns.__getitem__.side_effect = lambda i: ns_dict.get(i, MagicMock()) cmds = ' '.join(external_network_cmds(ns, ds)) assert_in('--external', cmds) assert_in('--allocation-pool start=0,end=1', cmds) assert_in('--network external', cmds) assert_in('--provider-network-type vlan', cmds)
def test_ChuteApi_get_chute(ChuteStorage, ChuteContainer): update_manager = MagicMock() api = chute_api.ChuteApi(update_manager) request = MagicMock() request.user = User.get_internal_user() container = MagicMock() container.getStatus.return_value = "running" ChuteContainer.return_value = container chute = MagicMock() chute.name = "test" chute.state = "running" chute.version = 5 chute.environment = {} chute.resources = {} ChuteStorage.chuteList = { "test": chute } data = api.get_chute(request, chute.name) assert isinstance(data, basestring) result = json.loads(data) assert result['name'] == chute.name assert result['version'] == chute.version
def test_delete_missing(self): """ Deleting a missing package raises 400 """ context = MagicMock() context.name = 'pkg1' context.version = '1.1' ret = api.delete_package(context, self.request) self.assertTrue(isinstance(ret, HTTPBadRequest))
def test_make_django_model_for_divider(self): patch( 'concrete_datastore.concrete.models.get_common_fields', side_effect=[{ 'uid': models.UUIDField(primary_key=True, default=uuid.uuid4), 'modification_date': models.DateTimeField(auto_now=True, # default=timezone.now ), 'creation_date': models.DateTimeField(auto_now_add=True, # default=timezone.now ), 'public': models.BooleanField(default=True), }], ).start() meta_model = MagicMock() divider = 'divider' key = 'key' value = MagicMock() value.f_type = str('ForeignKey') value.f_args = {'to': 'self', 'on_delete': 'CASCADE'} meta_model.get_model_name = MagicMock(return_value=str('divider')) meta_model.get_property = MagicMock(return_value=str('attribute')) meta_model.get_fields = MagicMock(return_value=((key, value), )) meta_model.version = None make_django_model(meta_model=meta_model, divider=divider)
def test_ChuteApi_get_chutes(ChuteStorage, ChuteContainer): update_manager = MagicMock() api = chute_api.ChuteApi(update_manager) request = MagicMock() container = MagicMock() container.getStatus.return_value = "running" ChuteContainer.return_value = container storage = MagicMock() ChuteStorage.return_value = storage chute = MagicMock() chute.environment = {} chute.name = "test" chute.resources = {} chute.version = 5 chute.get_owner.return_value = "paradrop" storage.getChuteList.return_value = [chute] data = api.get_chutes(request) assert isinstance(data, basestring) result = json.loads(data) assert result[0]['name'] == chute.name assert result[0]['version'] == chute.version
def setUp(self): # Create Mocks cdr_manager.RSSAdaptorThread = MagicMock() self._conn = MagicMock() cdr_manager.get_database_connection = MagicMock() cdr_manager.get_database_connection.return_value = self._conn self._conn.wstore_organization.find_and_modify.side_effect = [{'correlation_number': 1}, {'correlation_number': 2}] self._order = MagicMock() self._order.order_id = '1' self._order.owner_organization.name = 'customer' self._contract = MagicMock() self._contract.revenue_class = 'one time' self._contract.offering = '61004aba5e05acc115f022f0' self._contract.item_id = '3' self._contract.pricing_model = { 'general_currency': 'EUR' } offering = MagicMock() offering.pk = '61004aba5e05acc115f022f0' offering.off_id = '4' offering.name = 'offering' offering.version = '1.0' offering.owner_organization.name = 'provider' offering.owner_organization.pk = '61004aba5e05acc115f022f0' cdr_manager.Offering = MagicMock() cdr_manager.Offering.objects.get.return_value = offering
def test_external_network_cmds(self): cidr = MagicMock() cidr.version = 6 ns_dict = { 'networks': { 'external': [{ 'floating_ip_range': (0, 1), 'nic_mapping': { 'compute': { 'vlan': 'native' } }, 'gateway': 'gw', 'cidr': cidr }] } } ns = MagicMock() ns.enabled_network_list = ['external'] ns.__getitem__.side_effect = lambda i: ns_dict.get(i, MagicMock()) cmds = ' '.join(external_network_cmds(ns)) assert_in('--external', cmds) assert_in('--allocation-pool start=0,end=1', cmds) assert_in('--gateway gw', cmds) assert_in('--network external', cmds)
def test_external_network_cmds_nosdn_fdio(self): ds = {'deploy_options': {'sdn_controller': False, 'dataplane': 'fdio'}} cidr = MagicMock() cidr.version = 6 ns_dict = { 'networks': { 'external': [{ 'floating_ip_range': (0, 1), 'nic_mapping': { 'compute': { 'vlan': 'native' } }, 'gateway': 'gw', 'cidr': cidr }] } } ns = MagicMock() ns.enabled_network_list = ['external'] ns.__getitem__.side_effect = lambda i: ns_dict.get(i, MagicMock()) cmds = ' '.join(external_network_cmds(ns, ds)) assert_in('--external', cmds) assert_in('--allocation-pool start=0,end=1', cmds) assert_in('--gateway gw', cmds) assert_in('--network external', cmds) assert_in('--provider-physical-network external', cmds)
def test_authorization_create_error(): client = MagicMock() client.version = 2 client.directory.directory = {} with pytest.raises(ACMEProtocolException) as exc: Authorization.create(client, 'dns', 'example.com') assert exc.value.msg == 'ACME endpoint does not support pre-authorization.'
def test_challenge_from_to_json(): client = MagicMock() data = { 'url': 'xxx', 'type': 'type', 'status': 'valid', } client.version = 2 challenge = Challenge.from_json(client, data) assert challenge.data == data assert challenge.type == 'type' assert challenge.url == 'xxx' assert challenge.status == 'valid' assert challenge.token is None assert challenge.to_json() == data data = { 'type': 'type', 'status': 'valid', 'token': 'foo', } challenge = Challenge.from_json(None, data, url='xxx') assert challenge.data == data assert challenge.type == 'type' assert challenge.url == 'xxx' assert challenge.status == 'valid' assert challenge.token == 'foo' assert challenge.to_json() == data data = { 'uri': 'xxx', 'type': 'type', 'status': 'valid', } client.version = 1 challenge = Challenge.from_json(client, data) assert challenge.data == data assert challenge.type == 'type' assert challenge.url == 'xxx' assert challenge.status == 'valid' assert challenge.token is None assert challenge.to_json() == data
def test_unixhost_get_version(self): uobject = MagicMock(spec=UnixHost) uobject.shell.return_value.response.return_value = " test" self.assertIsNone(UnixHost.get_version(uobject)) uobject.shell.return_value.response.return_value = "15.1" self.assertEqual(UnixHost.get_version(uobject), "15.1") uobject.version = "17.2" self.assertEqual(UnixHost.get_version(uobject), "17.2")
def import_mock(name, i_globals={}, i_locals={}, fromlist=[], level=-1, orig_import=__import__): # _psutil_linux and _psutil_posix are the C bindings; use a mock for those if name in ('_psutil_linux', '_psutil_posix') or level >= 1 and ('_psutil_linux' in fromlist or '_psutil_posix' in fromlist): m = MagicMock() # the import system will ask us for our own name m._psutil_linux = m m._psutil_posix = m # there's a version safety check in psutil/__init__.py; this skips it m.version = version return m return orig_import(name, i_globals, i_locals, fromlist, level)
def test_get_version(mock_glob, mock_require): require_mock = MagicMock() require_mock.version = 'netshowlibver' require_mock.location = '/var/me' mock_require.return_value = [require_mock] mock_glob.return_value = [ '/var/me/linux'] get_version() mock_require.assert_called_with('netshow-linux-lib') mock_glob.assert_called_with( '/var/me/../../../share/netshow-lib/providers/*')
async def test_process_command_subscribe(): self_ = MagicMock() self_.version = (3, 1) async def subscribe(*args): self_.check(*args) self_.subscribe = subscribe await StreamConnection._process_command(self_, b'SUBSCRIBE', b'data') self_.check.assert_called_once_with(b'data')
async def test_process_command_cancel(): self_ = MagicMock() self_.version = (3, 1) async def unsubscribe(*args): self_.check(*args) self_.unsubscribe = unsubscribe await StreamConnection._process_command(self_, b'CANCEL', b'data') self_.check.assert_called_once_with(b'data')
def test_prepare_environment(core): chute = MagicMock() chute.name = "test" chute.version = 5 chute.environment = {'CUSTOM_VARIABLE': 42} core.info.pdid = 'halo42' env = dockerapi.prepare_environment(chute) assert env['PARADROP_CHUTE_NAME'] == chute.name assert env['PARADROP_CHUTE_VERSION'] == chute.version assert env['PARADROP_ROUTER_ID'] == core.info.pdid assert env['CUSTOM_VARIABLE'] == 42
def test_build_changed_url_encoding(): """ Test create_chroot """ maintainer = MagicMock() maintainer.firstname.return_value = "John" maintainer.lastname.return_value = "Snow" hook = MagicMock() hook.enabled.return_value = True hook.skip_ssl = True hook.method = "get" hook.url = "http://nonsense.invalid/get/{{ build.version|urlencode }}" hook.body = "" srcrepo = MagicMock() srcrepo.hooks = [hook] srcrepo.id.return_value = 111 srcrepo.url.return_value = "git://url" srcrepo.name.return_value = "srcpkg" build = MagicMock() build.maintainer.return_value = maintainer build.sourcerepository = srcrepo build.startstamp = "NOW" build.endstamp = "NOW" build.id = 1337 build.buildtype = "deb" build.ci_branch = "master" build.git_ref = "1337" build.sourcename = "srcpkg" build.version = "0.0.0+git1-1337<>" build.buildstate = "successful" build.url = "/blah" build.raw_log_url = "/blub" with patch("molior.molior.notifier.Configuration") as cfg, patch( "molior.molior.notifier.trigger_hook") as trigger_hook: cfg.return_value.hostname = "localhorst" loop = asyncio.get_event_loop() loop.run_until_complete(build_changed(build)) trigger_hook.assert_called_with( "get", "http://nonsense.invalid/get/{}".format(quote_plus(build.version)), skip_ssl=True, body="", )
def test_removeImage_worker(Client): client = MagicMock() Client.return_value = client chute = MagicMock() chute.name = "test" chute.version = 1 dockerapi._removeImage(chute) assert client.remove_image.called_once_with(image="test:1") # Current behavior is to eat the exception, so this call should not raise # anything. client.remove_image.side_effect = Exception("Image does not exist.") dockerapi._removeImage(chute)
def create_fake_import(self, name, version='1', check_items=True, install_status=InstallationStatuses.INSTALL_OK, uninstall_status=InstallationStatuses.UNINSTALL_OK): filenames = [] filenames.append('%s.py' % FAKE_NAME1) import_mock = MagicMock() fake_package = MagicMock() fake_package.name = name fake_package.version = version fake_package.check_items.return_value = check_items fake_package.install.return_value = install_status fake_package.uninstall.return_value = uninstall_status import_mock.Formula.return_value = fake_package return filenames, import_mock
def _mock_resource(self, info, provider): # Mock resource model resource = MagicMock() resource.pk = info['pk'] resource.provider = provider resource.version = info['version'] resource.content_type = info['content_type'] resource.state = info['state'] resource.download_link = info['download_link'] resource.resource_type = info['type'] resource.meta_info = {} resource.get_url.return_value = info['download_link'] resource.get_uri.return_value = info['uri'] return resource
def test_order_from_json(): client = MagicMock() data = { 'status': 'valid', 'identifiers': [], 'authorizations': [], } client.version = 2 order = Order.from_json(client, data, 'xxx') assert order.data == data assert order.url == 'xxx' assert order.status == 'valid' assert order.identifiers == [] assert order.finalize_uri is None assert order.certificate_uri is None assert order.authorization_uris == [] assert order.authorizations == {}
def test_getImageName(): chute = MagicMock() chute.name = "test" chute.version = 1 chute.external_image = "registry.exis.io/test:2" result = dockerapi.getImageName(chute) assert result == chute.external_image del chute.external_image result = dockerapi.getImageName(chute) assert result == "test:1" # For compatibility with older behavior, this should return name:latest # when version is not defined. del chute.version result = dockerapi.getImageName(chute) assert result == "test:latest"
def test_wait_for_finalization_error(): client = MagicMock() client.version = 2 data = { 'status': 'invalid', 'identifiers': [], 'authorizations': [], } order = Order.from_json(client, data, 'xxx') client.get_request = MagicMock(return_value=(data, {})) with pytest.raises(ACMEProtocolException) as exc: order.wait_for_finalization(client) assert exc.value.msg.startswith( 'Failed to wait for order to complete; got status "invalid". The JSON result: ' ) assert exc.value.module_fail_args == {}
def test_create_request_with_right_request_params(self, parent_breadcrumbs_from, breadcrumb_filters, settings): http_request = MagicMock() mock_api = MagicMock() mock_api.name = 'api_name' mock_api.version = '1.0.0.1' mock_user = http_request.user request_body = MagicMock() http_request.user.is_anonymous.return_value = False breadcrumb_filters.return_value = expected_req_params = {'bar': 'baz'} request = api_request_builder.build_request(http_request=http_request, url='candidates', api=mock_api, request_data={}, request_body=request_body) assert_that(request.user, equal_to(mock_user)) assert_that(request.request_params, equal_to(expected_req_params))
def test_prepare_environment(core): chute = MagicMock() chute.name = "test" chute.version = 5 chute.get_environment.return_value = {"CHUTE_VARIABLE": "test"} core.info.pdid = 'halo42' update = MagicMock() update.new = chute service = MagicMock() service.environment = {"CUSTOM_VARIABLE": 42} env = dockerapi.prepare_environment(update, service) assert env['PARADROP_CHUTE_NAME'] == chute.name assert env['PARADROP_CHUTE_VERSION'] == chute.version assert env['PARADROP_ROUTER_ID'] == core.info.pdid assert env['CUSTOM_VARIABLE'] == 42 assert env['CHUTE_VARIABLE'] == 'test'
def test_migration_removed(self, mock_get_packages, mock_getLogger): """ ensure that if a migration raises the MigrationRemovedError, it bubbles up. """ mock_package = MagicMock() mock_package.current_version = 6 mock_package.latest_available_version = 7 mock_package.name = 'foo' mock_migration = MagicMock() mock_migration.version = 7 mock_package.unapplied_migrations = [mock_migration] e = models.MigrationRemovedError('0006', '1.2.0', '1.1.0', 'foo') mock_package.apply_migration.side_effect = e mock_get_packages.return_value = [mock_package] options = MagicMock() options.dry_run = False with self.assertRaises(models.MigrationRemovedError) as assertion: manage.migrate_database(options) self.assertTrue(assertion.exception is e)
def test_authorization_from_to_json(): client = MagicMock() client.version = 2 data = { 'challenges': [], 'status': 'valid', 'identifier': { 'type': 'dns', 'value': 'example.com', }, } authz = Authorization.from_json(client, data, 'xxx') assert authz.url == 'xxx' assert authz.status == 'valid' assert authz.identifier == 'example.com' assert authz.identifier_type == 'dns' assert authz.challenges == [] assert authz.to_json() == { 'uri': 'xxx', 'challenges': [], 'status': 'valid', 'identifier': { 'type': 'dns', 'value': 'example.com', }, } data = { 'challenges': [{ 'url': 'xxxyyy', 'type': 'type', 'status': 'valid', }], 'status': 'valid', 'identifier': { 'type': 'dns', 'value': 'example.com', }, 'wildcard': True, } authz = Authorization.from_json(client, data, 'xxx') assert authz.url == 'xxx' assert authz.status == 'valid' assert authz.identifier == '*.example.com' assert authz.identifier_type == 'dns' assert len(authz.challenges) == 1 assert authz.challenges[0].data == { 'url': 'xxxyyy', 'type': 'type', 'status': 'valid', } assert authz.to_json() == { 'uri': 'xxx', 'challenges': [{ 'url': 'xxxyyy', 'type': 'type', 'status': 'valid', }], 'status': 'valid', 'identifier': { 'type': 'dns', 'value': 'example.com', }, 'wildcard': True, } client.version = 1 data = { 'challenges': [], 'identifier': { 'type': 'dns', 'value': 'example.com', }, } authz = Authorization.from_json(client, data, 'xxx') assert authz.url == 'xxx' assert authz.status == 'pending' assert authz.identifier == 'example.com' assert authz.identifier_type == 'dns' assert authz.challenges == [] assert authz.to_json() == { 'uri': 'xxx', 'challenges': [], 'identifier': { 'type': 'dns', 'value': 'example.com', }, }
def test_wait_for_validation_error(): client = MagicMock() client.version = 2 data = { 'challenges': [ { 'url': 'xxxyyy1', 'type': 'dns-01', 'status': 'invalid', 'error': { 'type': 'dns-failed', 'subproblems': [ { 'type': 'subproblem', 'detail': 'example.com DNS-01 validation failed', }, ] }, }, { 'url': 'xxxyyy2', 'type': 'http-01', 'status': 'invalid', 'error': { 'type': 'http-failed', 'subproblems': [ { 'type': 'subproblem', 'detail': 'example.com HTTP-01 validation failed', }, ] }, }, { 'url': 'xxxyyy3', 'type': 'something-else', 'status': 'valid', }, ], 'status': 'invalid', 'identifier': { 'type': 'dns', 'value': 'example.com', }, } client.get_request = MagicMock(return_value=(data, {})) authz = Authorization.from_json(client, data, 'xxx') with pytest.raises(ACMEProtocolException) as exc: authz.wait_for_validation(client, 'dns') assert exc.value.msg == ( 'Failed to validate challenge for dns:example.com: Status is "invalid". Challenge dns-01: Error dns-failed Subproblems:\n' '(dns-01.0) Error subproblem: "example.com DNS-01 validation failed"; Challenge http-01: Error http-failed Subproblems:\n' '(http-01.0) Error subproblem: "example.com HTTP-01 validation failed".' ) data = data.copy() data['uri'] = 'xxx' assert exc.value.module_fail_args == { 'identifier': 'dns:example.com', 'authorization': data, }
def test_plugin_must_have_version(self): SomePlugin = MagicMock() SomePlugin.version = None SomePlugin.__name__ = "test" with pytest.raises(PluginMustHaveVersion): self.app.plugins.install_plugins(SomePlugin)
def setUp(self): # Mock resource model resource1 = MagicMock() resource1.name = 'Resource1' resource1.version = '1.0' resource1.description = 'Test resource 1' resource1.content_type = 'text/plain' resource1.state = 'created' resource1.open = False resource1.get_url.return_value = 'http://localhost/media/resources/resource1' resource1.resource_type = 'API' resource1.meta_info = {} resource2 = MagicMock() resource2.name = 'Resource2' resource2.version = '2.0' resource2.description = 'Test resource 2' resource2.content_type = 'text/plain' resource2.state = 'created' resource2.open = False resource2.get_url.return_value = 'http://localhost/media/resources/resource2' resource2.resource_type = 'API' resource2.meta_info = {} resource3 = MagicMock() resource3.name = 'Resource3' resource3.version = '2.0' resource3.description = 'Test resource 3' resource3.content_type = 'text/plain' resource3.state = 'created' resource3.open = True resource3.get_url.return_value = 'http://localhost/media/resources/resource3' resource3.resource_type = 'API' resource3.meta_info = {} resource4 = MagicMock() resource4.name = 'Resource4' resource4.version = '1.0' resource4.description = 'Test resource 4' resource4.content_type = 'text/plain' resource4.state = 'created' resource4.open = True resource4.get_url.return_value = 'http://localhost/media/resources/resource4' resource4.resource_type = 'API' resource4.offerings = ['1111', '2222'] resource4.meta_info = {} resources_management.Resource = MagicMock() def resource_filter(provider=None, open=None): if provider != self.org: return [] if open is None: result = [ resource1, resource2, resource3, resource4 ] elif not open: result = [ resource1, resource2 ] else: result = [ resource3, resource4 ] return result resources_management.Resource.objects.filter = resource_filter self.user = MagicMock() self.org = MagicMock() self.user.userprofile.current_organization = self.org