def test_certificate_custom_template_with_unicode_data(self, custom_certs_enabled): """ Tests custom template renders properly with unicode data. """ mode = 'honor' self._add_course_certificates(count=1, signatory_count=2) self._create_custom_template(mode=mode) with patch.dict("django.conf.settings.FEATURES", { "CERTIFICATES_HTML_VIEW": True, "CUSTOM_CERTIFICATE_TEMPLATES_ENABLED": custom_certs_enabled }): test_url = get_certificate_url( user_id=self.user.id, course_id=unicode(self.course.id) ) with patch.dict("django.conf.settings.SOCIAL_SHARING_SETTINGS", { "CERTIFICATE_TWITTER": True, "CERTIFICATE_TWITTER_TEXT": u"nền tảng học tập" }): with patch('django.http.HttpRequest.build_absolute_uri') as mock_abs_uri: mock_abs_uri.return_value = '='.join(['http://localhost/?param', u'é']) with patch('certificates.api.get_course_organizations') as mock_get_orgs: mock_get_orgs.return_value = [] response = self.client.get(test_url) self.assertEqual(response.status_code, 200) if custom_certs_enabled: self.assertContains(response, 'mode: {}'.format(mode)) else: self.assertContains(response, "Tweet this Accomplishment") self.assertContains(response, 'https://twitter.com/intent/tweet')
def test_disk_size(self, mock_exists): path = '/myhome/disk.config' template_output = """image: %(path)s file format: raw virtual size: %(v_size)s (%(vsize_b)s bytes) cluster_size: 65536 disk size: 96K """ for i in range(0, 128): bytes = i * 65336 kbytes = bytes / 1024 mbytes = kbytes / 1024 output = template_output % ({ 'v_size': "%sM" % (mbytes), 'vsize_b': i, 'path': path, }) with mock.patch('nova.utils.execute', return_value=(output, '')) as mock_execute: self._test_disk_size(mock_execute, path, i) output = template_output % ({ 'v_size': "%sK" % (kbytes), 'vsize_b': i, 'path': path, }) with mock.patch('nova.utils.execute', return_value=(output, '')) as mock_execute: self._test_disk_size(mock_execute, path, i)
def test_show_job_update_diff_with_task_diff(self): config = self.get_job_config() self._fake_context.get_job_config = Mock(return_value=config) formatter = DiffFormatter(self._fake_context, config) local_task = self.create_scheduled_tasks()[0].assignedTask.task self._mock_api.get_job_update_diff.return_value = self.get_job_update_diff_result() with contextlib.nested( patch('subprocess.call', return_value=0), patch('json.loads', return_value={})) as (subprocess_patch, _): formatter.show_job_update_diff(self._mock_options.instance_spec.instance, local_task) assert self._mock_api.get_job_update_diff.mock_calls == [ call(config, self._mock_options.instance_spec.instance) ] assert "\n".join(self._fake_context.get_out()) == textwrap.dedent("""\ This job update will: add instances: [10], [12-14] update instances: [11] with diff:\n\n not change instances: [0-9]""") assert subprocess_patch.call_count == 1 assert subprocess_patch.call_args[0][0].startswith( os.environ.get('DIFF_VIEWER', 'diff') + ' ')
def test_certificate_asset_by_slug(self): """ Tests certificate template asset display by slug using static.certificate_asset_url method. """ self._add_course_certificates(count=1, signatory_count=2) self._create_custom_template(mode='honor') test_url = get_certificate_url( user_id=self.user.id, course_id=unicode(self.course.id) ) # render certificate without template asset with patch('certificates.api.get_course_organizations') as mock_get_orgs: mock_get_orgs.return_value = [] response = self.client.get(test_url) self.assertContains(response, '<img class="custom-logo" src="" />') template_asset = CertificateTemplateAsset( description='custom logo', asset='certificate_template_assets/32/test_logo.png', asset_slug='custom-logo', ) template_asset.save() # render certificate with template asset with patch('certificates.api.get_course_organizations') as mock_get_orgs: mock_get_orgs.return_value = [] response = self.client.get(test_url) self.assertContains( response, '<img class="custom-logo" src="{}certificate_template_assets/32/test_logo.png" />'.format( settings.MEDIA_URL ) )
def get_filesystem_encoding_test(self): """ Test the get_filesystem_encoding() function """ with patch('openlp.core.utils.sys.getfilesystemencoding') as mocked_getfilesystemencoding, \ patch('openlp.core.utils.sys.getdefaultencoding') as mocked_getdefaultencoding: # GIVEN: sys.getfilesystemencoding returns "cp1252" mocked_getfilesystemencoding.return_value = 'cp1252' # WHEN: get_filesystem_encoding() is called result = get_filesystem_encoding() # THEN: getdefaultencoding should have been called mocked_getfilesystemencoding.assert_called_with() assert not mocked_getdefaultencoding.called assert result == 'cp1252', 'The result should be "cp1252"' # GIVEN: sys.getfilesystemencoding returns None and sys.getdefaultencoding returns "utf-8" mocked_getfilesystemencoding.return_value = None mocked_getdefaultencoding.return_value = 'utf-8' # WHEN: get_filesystem_encoding() is called result = get_filesystem_encoding() # THEN: getdefaultencoding should have been called mocked_getfilesystemencoding.assert_called_with() mocked_getdefaultencoding.assert_called_with() assert result == 'utf-8', 'The result should be "utf-8"'
def eq_ne_test(self,_,tfile1,path1,tfile2,path2,eq_flag): with patch("__builtin__.open", mock_open(read_data=tfile1)) as m: ltor1 = LocalTorrent(path1) with patch("__builtin__.open", mock_open(read_data=tfile2)) as m: ltor2 = LocalTorrent(path2) self.assertEqual(ltor1.__eq__(ltor2), eq_flag) self.assertEqual(ltor1.__ne__(ltor2), not eq_flag)
def test_net_connect_to_nat(self): # use external fake_client, fake_ctx = self.generate_client_and_context_network() fake_ctx._target.node.properties = { 'use_external_resource': True } with mock.patch( 'vcloud_plugin_common.VcloudAirClient.get', mock.MagicMock(return_value=fake_client) ): public_nat.net_connect_to_nat(ctx=fake_ctx) # no external fake_client, fake_ctx = self.generate_client_and_context_network() fake_ctx._target.node.properties = { 'nat': { 'edge_gateway': 'gateway' }, 'rules': [{ 'type': 'DNAT' }] } fake_client._vdc_gateway.get_public_ips = mock.MagicMock(return_value=[ '10.18.1.1' ]) with mock.patch( 'vcloud_plugin_common.VcloudAirClient.get', mock.MagicMock(return_value=fake_client) ): public_nat.net_connect_to_nat(ctx=fake_ctx) fake_client._vdc_gateway.add_nat_rule.assert_called_with( 'DNAT', '10.18.1.1', 'any', '127.1.1.100 - 127.1.1.200', 'any', 'any' )
def start(self): import mock def unbound_on_Server(host, port, use_ssl, connect_timeout, *a, **kwargs): return self._on_Server(host, port, use_ssl, connect_timeout, *a, **kwargs) self._server_mock = mock.MagicMock() self._server_mock.side_effect = unbound_on_Server self._patcher = mock.patch('ldap3.Server', self._server_mock) self._patcher.start() def unbound_on_Connection(server, user, password, auto_bind, client_strategy, authentication, check_names, auto_referrals, *a, **kwargs): return self._on_Connection(server, user, password, auto_bind, client_strategy, authentication, check_names, auto_referrals, *a, **kwargs) self._patcher2 = mock.patch('ldap3.Connection', unbound_on_Connection) self._patcher2.start()
def test_get_taking_too_long(self): the_time = [time.time()] def mock_time(): return the_time[0] # this is just a convenient place to hang a time jump def mock_is_success(status_int): the_time[0] += 9 * 3600 return status_int // 100 == 2 req = swob.Request.blank( '/v1/AUTH_test/mancon/manifest', environ={'REQUEST_METHOD': 'GET'}) with contextlib.nested( mock.patch('swift.common.utils.time.time', mock_time), mock.patch('swift.common.utils.is_success', mock_is_success), mock.patch.object(dlo, 'is_success', mock_is_success)): status, headers, body, exc = self.call_dlo( req, expect_exception=True) self.assertEqual(status, '200 OK') self.assertEqual(body, 'aaaaabbbbbccccc') self.assertTrue(isinstance(exc, exceptions.SegmentError))
def test_rewrite_etc_hosts(tmpdir): orig_hosts = tmpdir.join("hosts.orig") orig_hosts.write("1.2.3.3 existing\n") new_hosts = tmpdir.join("hosts") orig_hosts.copy(new_hosts) hostmap = { 'myhost': '1.2.3.4', 'myotherhost': '1.2.3.5', } with patch('sshuttle.firewall.HOSTSFILE', new=str(new_hosts)): sshuttle.firewall.rewrite_etc_hosts(hostmap, 10) with new_hosts.open() as f: line = f.readline() s = line.split() assert s == ['1.2.3.3', 'existing'] line = f.readline() s = line.split() assert s == ['1.2.3.4', 'myhost', '#', 'sshuttle-firewall-10', 'AUTOCREATED'] line = f.readline() s = line.split() assert s == ['1.2.3.5', 'myotherhost', '#', 'sshuttle-firewall-10', 'AUTOCREATED'] line = f.readline() assert line == "" with patch('sshuttle.firewall.HOSTSFILE', new=str(new_hosts)): sshuttle.firewall.restore_etc_hosts(10) assert orig_hosts.computehash() == new_hosts.computehash()
def testZipAPI(self): # Check to make sure that the Geocoder API is not used if not needed # Only checks that geocode IS NOT called the second time (zipcode MUST come from somwhere, ensuring that Google API is called the first time) prof_1 = self.Profiles.find_one({'user_id':'1'}) self.assertEquals(prof_1['_id'], '1') #zip creation phase, should make API call and obtain zipcode with mock.patch('main.Profile.detect_home', return_value=(-122.259769,37.871758)) as func1: with mock.patch('main.Profile.detect_home_from_db', return_value=(-122.259769,37.871758)) as func2: Profile.update_profiles(True) self.assertEquals(func1.called, True) self.assertEquals(func2.called, True) func1.reset_mock() func2.reset_mock() prof_1 = self.Profiles.find_one({'user_id':'1'}) self.assertEquals(prof_1['zip'], '94709') #zip should be stored, no API call with mock.patch('main.Profile.Geocoder.reverse_geocode', return_value=None) as func3: Profile.update_profiles(True) self.assertEquals(func3.called, False) prof_1 = self.Profiles.find_one({'user_id':'1'}) self.assertEquals(prof_1['zip'], '94709') with mock.patch('main.Profile.detect_home', return_value=(-122.2584,37.8697)) as func1: #new zip retrieval phase, should make API call and obtain zipcode Profile.update_profiles(True) prof_1 = self.Profiles.find_one({'user_id':'1'}) self.assertEquals(prof_1['zip'], '94720') with mock.patch('main.Profile.Geocoder.reverse_geocode', return_value=None) as func3: #zip should be stored, no API call Profile.update_profiles(True) self.assertEquals(func3.called, False) func3.reset_mock() prof_1 = self.Profiles.find_one({'user_id':'1'}) self.assertEquals(prof_1['zip'], '94720')
def test_run_forever(self): sleep_times = random.randint(5, 10) call_times = sleep_times - 1 class FakeTime(object): def __init__(self): self.times = 0 def sleep(self, sec): self.times += 1 if self.times < sleep_times: time.sleep(0.1) else: # stop forever by an error raise ValueError() def time(self): return time.time() conf = {} test_auditor = auditor.ContainerAuditor(conf, logger=self.logger) with mock.patch("swift.container.auditor.time", FakeTime()): def fake_audit_location_generator(*args, **kwargs): files = os.listdir(self.testdir) return [(os.path.join(self.testdir, f), "", "") for f in files] with mock.patch("swift.container.auditor.audit_location_generator", fake_audit_location_generator): self.assertRaises(ValueError, test_auditor.run_forever) self.assertEqual(test_auditor.container_failures, 2 * call_times) self.assertEqual(test_auditor.container_passes, 3 * call_times)
def run_main(args, exit_code=0, expect_stderr=False): """Run main() of the datalad, do basic checks and provide outputs Parameters ---------- args : list List of string cmdline arguments to pass exit_code : int Expected exit code. Would raise AssertionError if differs expect_stderr : bool or string Whether to expect stderr output. If string -- match Returns ------- stdout, stderr strings Output produced """ with patch('sys.stderr', new_callable=StringIO) as cmerr: with patch('sys.stdout', new_callable=StringIO) as cmout: with assert_raises(SystemExit) as cm: main(["datalad"] + list(args)) assert_equal(cm.exception.code, exit_code) stdout = cmout.getvalue() stderr = cmerr.getvalue() if expect_stderr is False: assert_equal(stderr, "") elif expect_stderr is True: # do nothing -- just return pass else: # must be a string assert_equal(stderr, expect_stderr) return stdout, stderr
def test_parse_dispatch_tab_delimiter(): import six from occams_imports.parsers import parse with mock.patch('occams_imports.parsers.parse.iform_json') as mock_convert: codebook_format = u'iform' delimiter = u'tab' codebook = six.StringIO() mock_convert.convert.return_value = six.StringIO() response = parse.parse_dispatch(codebook, codebook_format, delimiter) codebook.close() assert mock_convert.convert.called == True with mock.patch('occams_imports.parsers.parse.convert_qds_to_occams') \ as mock_convert: codebook_format = u'qds' delimiter = u'comma' codebook = six.StringIO() mock_convert.convert.return_value = six.StringIO() response = parse.parse_dispatch(codebook, codebook_format, delimiter) codebook.close() assert mock_convert.convert.called == True
def test_increase_quota(self): """Tests successful execution of the increase_quota command.""" mock_options = self.setup_mock_options() with contextlib.nested( patch('twitter.common.app.get_options', return_value=mock_options), patch('apache.aurora.admin.admin.make_admin_client', return_value=create_autospec(spec=AuroraClientAPI)), patch('apache.aurora.admin.admin.CLUSTERS', new=self.TEST_CLUSTERS) ) as (_, mock_make_admin_client, _): api = mock_make_admin_client.return_value role = 'test_role' api.get_quota.return_value = self.create_response( ResourceAggregate(20.0, 4000, 6000), ResourceAggregate(15.0, 2000, 3000), ResourceAggregate(6.0, 200, 600), ) api.set_quota.return_value = self.create_simple_success_response() increase_quota([self.TEST_CLUSTER, role, '4.0', '1MB', '1MB']) api.set_quota.assert_called_with(role, 24.0, 4001, 6001) assert type(api.set_quota.call_args[0][1]) == type(float()) assert type(api.set_quota.call_args[0][2]) == type(int()) assert type(api.set_quota.call_args[0][3]) == type(int())
def setUp(self): self._patchers = [ mock.patch("pylib.constants.GetOutDirectory", new=mock.Mock(return_value=TEST_OUT_DIR)), mock.patch("os.path.exists", new=mock.Mock(return_value=True)), ] for p in self._patchers: p.start()
def test_description_is_optional(self, mock_heat_client): """Assert that if heat_template_version is omitted, it's added""" # Note that the 'with x as y, a as b:' syntax was introduced in # python 2.7, and contextlib.nested was deprecated in py2.7 with mock.patch(MOD_NAME + '.HeatStack._get_status') as status_get: with mock.patch(MOD_NAME + '.HeatStack._wait_state') as wait_st: status_get.return_value = 'NOT_FOUND' wait_st.return_value = {} hs = heat_stack.HeatStack(self.mock_murano_obj, None, None, None) hs._heat_client = mock_heat_client hs._name = 'test-stack' hs._description = None hs._template = {'resources': {'test': 1}} hs._parameters = {} hs._applied = False hs.push() expected_template = { 'heat_template_version': '2013-05-23', 'resources': {'test': 1} } mock_heat_client.stacks.create.assert_called_with( stack_name='test-stack', disable_rollback=False, parameters={}, template=expected_template ) self.assertTrue(hs._applied)
def test_floatingip_status(self): with mock.patch('neutron.db.l3_db.L3_NAT_db_mixin.' 'create_floatingip', new=mock.Mock(return_value=self.floatingip)): # create floating-ip with mapped port fip = self.plugin.create_floatingip(self.context, {'floatingip': self.floatingip}) self.plugin.update_floatingip_status.assert_called_once_with( mock.ANY, FLOATINGIP, q_const.FLOATINGIP_STATUS_ACTIVE) self.assertEqual(q_const.FLOATINGIP_STATUS_ACTIVE, fip['status']) # dissociate mapped-port with mock.patch('neutron.db.l3_db.L3_NAT_db_mixin.' 'update_floatingip', new=mock.Mock(return_value=self.floatingip)): self.plugin.update_floatingip_status.reset_mock() self.floatingip.pop('port_id') fip = self.plugin.update_floatingip(self.context, FLOATINGIP, {'floatingip': self.floatingip}) self.plugin.update_floatingip_status.assert_called_once_with( mock.ANY, FLOATINGIP, q_const.FLOATINGIP_STATUS_DOWN) self.assertEqual(q_const.FLOATINGIP_STATUS_DOWN, fip['status']) # re-associate mapped-port with mock.patch('neutron.db.l3_db.L3_NAT_db_mixin.' 'update_floatingip', new=mock.Mock(return_value=self.floatingip)): self.plugin.update_floatingip_status.reset_mock() self.floatingip['port_id'] = PORT fip = self.plugin.update_floatingip(self.context, FLOATINGIP, {'floatingip': self.floatingip}) self.plugin.update_floatingip_status.assert_called_once_with( mock.ANY, FLOATINGIP, q_const.FLOATINGIP_STATUS_ACTIVE) self.assertEqual(q_const.FLOATINGIP_STATUS_ACTIVE, fip['status'])
def _RunFetchBenchmarkDepsTest(self, benchmark_name, expected_fetched_file_paths=None): """Simulates './fetch_benchmark_deps [benchmark_name]' It checks if the paths returned are expected and have corresponding sha1 checksums. The expected result can be omitted if the dependencies of specified benchmarks are subject to changes. Args: benchmark_name: benchmark name expected_fetched_file_paths: the expected result. """ sys.argv[1] = benchmark_name output = StringIO.StringIO() with mock.patch('telemetry.wpr.archive_info.WprArchiveInfo' '.DownloadArchivesIfNeeded') as mock_download: with mock.patch('catapult_base.cloud_storage' '.GetFilesInDirectoryIfChanged') as mock_get: mock_download.return_value = True mock_get.GetFilesInDirectoryIfChanged.return_value = True fetch_benchmark_deps.main(output) for f in output.getvalue().splitlines(): fullpath = os.path.join(fetch_benchmark_deps.GetChromiumDir(), f) sha1path = fullpath + '.sha1' self.assertTrue(os.path.isfile(sha1path)) if expected_fetched_file_paths: self.assertEquals(expected_fetched_file_paths, NormPaths(output.getvalue()))
def test_nova_server_with_use_password(self, cfy_local, *_): test_vars = { 'counter': 0, 'server': mock.MagicMock() } tmp_path = tempfile.NamedTemporaryFile(prefix='key_name') key_path = tmp_path.name def mock_get_server_by_context(_): s = test_vars['server'] if test_vars['counter'] == 0: s.status = nova_plugin.server.SERVER_STATUS_BUILD else: s.status = nova_plugin.server.SERVER_STATUS_ACTIVE test_vars['counter'] += 1 def check_agent_key_path(private_key): self.assertEqual(private_key, key_path) return private_key s.get_password = check_agent_key_path return s with mock.patch('nova_plugin.server.get_server_by_context', mock_get_server_by_context): with mock.patch( 'cloudify.context.BootstrapContext.' 'CloudifyAgent.agent_key_path', new_callable=mock.PropertyMock, return_value=key_path): cfy_local.execute('install', task_retries=5)
def test_generate_and_send_digests_retry_limit(self): """ """ data = json.load( open(join(dirname(__file__), 'cs_notifications.result.json'))) with patch('notifier.tasks.generate_digest_content', return_value=list(Parser.parse(data))) as p: # setting this here because override_settings doesn't seem to # work on celery task configuration decorators expected_num_tries = 1 + settings.FORUM_DIGEST_TASK_MAX_RETRIES mock_backend = Mock(name='mock_backend', send_messages=Mock( side_effect=SESMaxSendingRateExceededError(400, 'Throttling'))) with patch('notifier.connection_wrapper.dj_get_connection', return_value=mock_backend) as p2: # execute task - should fail, retry twice and still fail, then # give up try: task_result = generate_and_send_digests.delay( [usern(n) for n in xrange(2, 11)], datetime.datetime.now(), datetime.datetime.now()) except SESMaxSendingRateExceededError as e: self.assertEqual( mock_backend.send_messages.call_count, expected_num_tries) else: # should have raised self.fail('task did not retry twice before giving up')
def test_staff_upload_download_annotated(self, get_sha1, is_course_staff, get_student_module): # pylint: disable=no-member """ Tests upload and download of annotated staff files. """ get_student_module.return_value = fake_student_module() is_course_staff.return_value = True get_sha1.return_value = SHA1 file_name = 'test.txt' block = self.make_xblock() with self.dummy_upload(file_name) as (upload, expected), mock.patch( "edx_sga.sga.StaffGradedAssignmentXBlock.staff_grading_data", return_value={} ) as staff_grading_data: block.staff_upload_annotated(mock.Mock(params={'annotated': upload, 'module_id': 1})) assert staff_grading_data.called is True with mock.patch( "edx_sga.sga.StaffGradedAssignmentXBlock.file_storage_path", return_value=block.file_storage_path(SHA1, file_name) ): response = block.staff_download_annotated(mock.Mock(params={'module_id': 1})) assert response.body == expected with mock.patch( "edx_sga.sga.StaffGradedAssignmentXBlock.file_storage_path", return_value=block.file_storage_path("", "test_notfound.txt") ): response = block.staff_download_annotated( mock.Mock(params={'module_id': 1}) ) assert response.status_code == 404
def test_run_once(self): def prepare_data_dir(): devices_path = tempfile.mkdtemp() # will be deleted by teardown self.to_delete.append(devices_path) path = os.path.join(devices_path, 'sda1', DATADIR) os.makedirs(path) return devices_path def init_reaper(devices): r = reaper.AccountReaper({'devices': devices}) return r devices = prepare_data_dir() r = init_reaper(devices) with patch('swift.account.reaper.ismount', lambda x: True): with patch( 'swift.account.reaper.AccountReaper.reap_device') as foo: r.run_once() self.assertEqual(foo.called, 1) with patch('swift.account.reaper.ismount', lambda x: False): with patch( 'swift.account.reaper.AccountReaper.reap_device') as foo: r.run_once() self.assertFalse(foo.called)
def test_populate_policy_profile_delete(self): # Patch the Client class with the TestClient class with mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClient): # Patch the _get_total_profiles() method to return a custom value with mock.patch(fake_client.__name__ + '.TestClient._get_total_profiles') as obj_inst: # Return 3 policy profiles obj_inst.return_value = 3 plugin = manager.NeutronManager.get_plugin() plugin._populate_policy_profiles() db_session = db.get_session() profile = n1kv_db_v2.get_policy_profile( db_session, '00000000-0000-0000-0000-000000000001') # Verify that DB contains only 3 policy profiles self.assertEqual('pp-1', profile['name']) profile = n1kv_db_v2.get_policy_profile( db_session, '00000000-0000-0000-0000-000000000002') self.assertEqual('pp-2', profile['name']) profile = n1kv_db_v2.get_policy_profile( db_session, '00000000-0000-0000-0000-000000000003') self.assertEqual('pp-3', profile['name']) self.assertRaises(c_exc.PolicyProfileIdNotFound, n1kv_db_v2.get_policy_profile, db_session, '00000000-0000-0000-0000-000000000004') # Return 2 policy profiles obj_inst.return_value = 2 plugin._populate_policy_profiles() # Verify that the third policy profile is deleted self.assertRaises(c_exc.PolicyProfileIdNotFound, n1kv_db_v2.get_policy_profile, db_session, '00000000-0000-0000-0000-000000000003')
def test_reap_object(self): conf = { 'mount_check': 'false', } r = reaper.AccountReaper(conf, logger=unit.debug_logger()) mock_path = 'swift.account.reaper.direct_delete_object' for policy in POLICIES: r.reset_stats() with patch(mock_path) as fake_direct_delete: with patch('swift.account.reaper.time') as mock_time: mock_time.return_value = 1429117638.86767 r.reap_object('a', 'c', 'partition', cont_nodes, 'o', policy.idx) mock_time.assert_called_once_with() for i, call_args in enumerate( fake_direct_delete.call_args_list): cnode = cont_nodes[i % len(cont_nodes)] host = '%(ip)s:%(port)s' % cnode device = cnode['device'] headers = { 'X-Container-Host': host, 'X-Container-Partition': 'partition', 'X-Container-Device': device, 'X-Backend-Storage-Policy-Index': policy.idx, 'X-Timestamp': '1429117638.86767' } ring = r.get_object_ring(policy.idx) expected = call(dict(ring.devs[i], index=i), 0, 'a', 'c', 'o', headers=headers, conn_timeout=0.5, response_timeout=10) self.assertEqual(call_args, expected) self.assertEqual(policy.object_ring.replicas - 1, i) self.assertEqual(r.stats_objects_deleted, policy.object_ring.replicas)
def setUp(self): super(TestSdnveNeutronAgent, self).setUp() notifier_p = mock.patch(NOTIFIER) notifier_cls = notifier_p.start() self.notifier = mock.Mock() notifier_cls.return_value = self.notifier cfg.CONF.set_override('integration_bridge', 'br_int', group='SDNVE') kwargs = sdnve_neutron_agent.create_agent_config_map(cfg.CONF) class MockFixedIntervalLoopingCall(object): def __init__(self, f): self.f = f def start(self, interval=0): self.f() with contextlib.nested( mock.patch('neutron.plugins.ibm.agent.sdnve_neutron_agent.' 'SdnveNeutronAgent.setup_integration_br', return_value=mock.Mock()), mock.patch('neutron.openstack.common.loopingcall.' 'FixedIntervalLoopingCall', new=MockFixedIntervalLoopingCall)): self.agent = sdnve_neutron_agent.SdnveNeutronAgent(**kwargs)
def test_invalid_certificate_path(self): mock_file_path = "/path/to/cert.pem" with patch("django_auth_adfs.backend.AdfsBackend._public_keys", []): with patch("django_auth_adfs.backend.settings.SIGNING_CERT", mock_file_path): with patch("django_auth_adfs.backend.isfile") as mock_isfile: mock_isfile.return_value = False self.assertRaises(ImproperlyConfigured, AdfsBackend)
def test_finalize_uploaded_assignment( self, finalized_setting, model_change_expected, upload_allowed, get_student_item_dict ): """ Tests that finalize_uploaded_assignment sets a submission to be finalized """ block = self.make_xblock() get_student_item_dict.return_value = { "student_id": 1, "course_id": block.block_course_id, "item_id": block.block_id, "item_type": 'sga', } upload_allowed.return_value = True existing_submitted_at_value = django_now() fake_submission_data = fake_get_submission(**finalized_setting) fake_submission_object = mock.Mock( submitted_at=existing_submitted_at_value, answer=fake_submission_data['answer'] ) with mock.patch( 'edx_sga.sga.Submission.objects.get', return_value=fake_submission_object ), mock.patch( 'edx_sga.sga.StaffGradedAssignmentXBlock.get_submission', return_value=fake_submission_data ), mock.patch( 'edx_sga.sga.StaffGradedAssignmentXBlock.student_state', return_value={} ): block.finalize_uploaded_assignment(mock.Mock()) assert fake_submission_object.answer['finalized'] is True assert (existing_submitted_at_value != fake_submission_object.submitted_at) is model_change_expected assert fake_submission_object.save.called is model_change_expected
def MockEventNotification( response_method, native_filetype_completer = True ): """Mock out the EventNotification client request object, replacing the Response handler's JsonFromFuture with the supplied |response_method|. Additionally mock out YouCompleteMe's FiletypeCompleterExistsForFiletype method to return the supplied |native_filetype_completer| parameter, rather than querying the server""" # We don't want the event to actually be sent to the server, just have it # return success with patch( 'ycm.client.base_request.BaseRequest.PostDataToHandlerAsync', return_value = MagicMock( return_value=True ) ): # We set up a fake a Response (as called by EventNotification.Response) # which calls the supplied callback method. Generally this callback just # raises an apropriate exception, otherwise it would have to return a mock # future object. # # Note: JsonFromFuture is actually part of ycm.client.base_request, but we # must patch where an object is looked up, not where it is defined. # See https://docs.python.org/dev/library/unittest.mock.html#where-to-patch # for details. with patch( 'ycm.client.event_notification.JsonFromFuture', side_effect = response_method ): # Filetype available information comes from the server, so rather than # relying on that request, we mock out the check. The caller decides if # filetype completion is available with patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype', return_value = native_filetype_completer ): yield
def test_prepare_download_submissions( self, is_zip_file_available, downloadable, get_sorted_submissions, zip_student_submissions, ): """ Test prepare download api """ block = self.make_xblock() get_sorted_submissions.return_value = [ { 'submission_id': uuid.uuid4().hex, 'filename': "test_{}.txt".format(uuid.uuid4().hex), 'timestamp': datetime.datetime.now(tz=pytz.utc) } for __ in range(2) ] zip_student_submissions.delay = mock.Mock() with mock.patch( "edx_sga.sga.StaffGradedAssignmentXBlock.is_zip_file_available", return_value=is_zip_file_available ), mock.patch( 'edx_sga.sga.StaffGradedAssignmentXBlock.get_real_user', return_value=self.staff ), mock.patch( 'edx_sga.utils.default_storage.modified_time', return_value=datetime.datetime.now() ): response = block.prepare_download_submissions(None) response_body = json.loads(response.body) assert response_body["downloadable"] is downloadable
def test_end_to_end_missedmessage_hook(self) -> None: """Tests what arguments missedmessage_hook passes into maybe_enqueue_notifications. Combined with the previous test, this ensures that the missedmessage_hook is correct""" user_profile = self.example_user('hamlet') email = user_profile.email self.login(email) def change_subscription_properties(user_profile: UserProfile, stream: Stream, sub: Subscription, properties: Dict[str, bool]) -> None: for property_name, value in properties.items(): do_change_subscription_property(user_profile, sub, stream, property_name, value) result = self.tornado_call(get_events, user_profile, {"apply_markdown": ujson.dumps(True), "client_gravatar": ujson.dumps(True), "event_types": ujson.dumps(["message"]), "user_client": "website", "dont_block": ujson.dumps(True), }) self.assert_json_success(result) queue_id = ujson.loads(result.content)["queue_id"] client_descriptor = get_client_descriptor(queue_id) with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue: # To test the missed_message hook, we first need to send a message msg_id = self.send_stream_message(self.example_email("iago"), "Denmark") # Verify that nothing happens if you call it as not the # "last client descriptor", in which case the function # short-circuits, since the `missedmessage_hook` handler # for garbage-collection is only for the user's last queue. missedmessage_hook(user_profile.id, client_descriptor, False) mock_enqueue.assert_not_called() # Now verify that we called the appropriate enqueue function missedmessage_hook(user_profile.id, client_descriptor, True) mock_enqueue.assert_called_once() args_list = mock_enqueue.call_args_list[0][0] self.assertEqual(args_list, (user_profile.id, msg_id, False, False, False, False, "Denmark", False, True, {'email_notified': False, 'push_notified': False})) # Clear the event queue, before repeating with a private message client_descriptor.event_queue.pop() self.assertTrue(client_descriptor.event_queue.empty()) msg_id = self.send_personal_message(self.example_email("iago"), email) with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue: missedmessage_hook(user_profile.id, client_descriptor, True) mock_enqueue.assert_called_once() args_list = mock_enqueue.call_args_list[0][0] self.assertEqual(args_list, (user_profile.id, msg_id, True, False, False, False, None, False, True, {'email_notified': True, 'push_notified': True})) # Clear the event queue, now repeat with a mention client_descriptor.event_queue.pop() self.assertTrue(client_descriptor.event_queue.empty()) msg_id = self.send_stream_message(self.example_email("iago"), "Denmark", content="@**King Hamlet** what's up?") with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue: # Clear the event queue, before repeating with a private message missedmessage_hook(user_profile.id, client_descriptor, True) mock_enqueue.assert_called_once() args_list = mock_enqueue.call_args_list[0][0] self.assertEqual(args_list, (user_profile.id, msg_id, False, True, False, False, "Denmark", False, True, {'email_notified': True, 'push_notified': True})) stream = get_stream("Denmark", user_profile.realm) sub = Subscription.objects.get(user_profile=user_profile, recipient__type=Recipient.STREAM, recipient__type_id=stream.id) # Clear the event queue, now repeat with stream message with stream_push_notify change_subscription_properties(user_profile, stream, sub, {'push_notifications': True}) client_descriptor.event_queue.pop() self.assertTrue(client_descriptor.event_queue.empty()) msg_id = self.send_stream_message(self.example_email("iago"), "Denmark", content="what's up everyone?") with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue: # Clear the event queue, before repeating with a private message missedmessage_hook(user_profile.id, client_descriptor, True) mock_enqueue.assert_called_once() args_list = mock_enqueue.call_args_list[0][0] self.assertEqual(args_list, (user_profile.id, msg_id, False, False, True, False, "Denmark", False, True, {'email_notified': False, 'push_notified': False})) # Clear the event queue, now repeat with stream message with stream_email_notify change_subscription_properties(user_profile, stream, sub, {'push_notifications': False, 'email_notifications': True}) client_descriptor.event_queue.pop() self.assertTrue(client_descriptor.event_queue.empty()) msg_id = self.send_stream_message(self.example_email("iago"), "Denmark", content="what's up everyone?") with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue: # Clear the event queue, before repeating with a private message missedmessage_hook(user_profile.id, client_descriptor, True) mock_enqueue.assert_called_once() args_list = mock_enqueue.call_args_list[0][0] self.assertEqual(args_list, (user_profile.id, msg_id, False, False, False, True, "Denmark", False, True, {'email_notified': False, 'push_notified': False})) # Clear the event queue, now repeat with stream message with stream_push_notify # on a muted topic, which we should not push notify for change_subscription_properties(user_profile, stream, sub, {'push_notifications': True, 'email_notifications': False}) client_descriptor.event_queue.pop() self.assertTrue(client_descriptor.event_queue.empty()) do_mute_topic(user_profile, stream, sub.recipient, "mutingtest") msg_id = self.send_stream_message(self.example_email("iago"), "Denmark", content="what's up everyone?", topic_name="mutingtest") with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue: # Clear the event queue, before repeating with a private message missedmessage_hook(user_profile.id, client_descriptor, True) mock_enqueue.assert_called_once() args_list = mock_enqueue.call_args_list[0][0] self.assertEqual(args_list, (user_profile.id, msg_id, False, False, False, False, "Denmark", False, True, {'email_notified': False, 'push_notified': False})) # Clear the event queue, now repeat with stream message with stream_email_notify # on a muted stream, which we should not email notify for change_subscription_properties(user_profile, stream, sub, {'push_notifications': False, 'email_notifications': True}) client_descriptor.event_queue.pop() self.assertTrue(client_descriptor.event_queue.empty()) change_subscription_properties(user_profile, stream, sub, {'in_home_view': False}) msg_id = self.send_stream_message(self.example_email("iago"), "Denmark", content="what's up everyone?") with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue: # Clear the event queue, before repeating with a private message missedmessage_hook(user_profile.id, client_descriptor, True) mock_enqueue.assert_called_once() args_list = mock_enqueue.call_args_list[0][0] self.assertEqual(args_list, (user_profile.id, msg_id, False, False, False, False, "Denmark", False, True, {'email_notified': False, 'push_notified': False})) # Clean up the state we just changed (not necessary unless we add more test code below) change_subscription_properties(user_profile, stream, sub, {'push_notifications': True, 'in_home_view': True})
def test_table_cell_delete(self, mock_table, mock_default_context): args = {'command': 'delete', 'name': 'test-table'} mock_table.return_value.delete.side_effect = Exception with mock.patch('sys.stdout', new=StringIO()) as mocked_stdout: google.datalab.bigquery.commands._bigquery._table_cell(args, None) self.assertIn('Failed to delete table test-table', mocked_stdout.getvalue())
def test_sample_cell(self, mock_get_notebook_item, mock_context_default, mock_query_execute, mock_get_table): args = {'query': None, 'table': None, 'view': None, 'fields': None, 'count': 5, 'percent': 1, 'key_field': None, 'order': None, 'profile': None, 'verbose': None, 'method': 'limit'} cell_body = '' with self.assertRaises(Exception): google.datalab.bigquery.commands._bigquery._sample_cell(args, cell_body) args['query'] = 'test_query' mock_get_notebook_item.return_value = None with self.assertRaises(Exception): google.datalab.bigquery.commands._bigquery._sample_cell(args, cell_body) # query passed, no other parameters mock_get_notebook_item.return_value = google.datalab.bigquery.Query('test_sql') google.datalab.bigquery.commands._bigquery._sample_cell(args, cell_body) call_args = mock_query_execute.call_args[0] call_kwargs = mock_query_execute.call_args[1] self.assertEqual(call_args[0]._output_type, 'table') self.assertEqual(call_kwargs['sampling']('test_sql'), google.datalab.bigquery._sampling.Sampling.default()('test_sql')) # test --profile args['profile'] = True mock_query_execute.return_value.result = lambda: pandas.DataFrame({'c': 'v'}, index=['c']) google.datalab.bigquery.commands._bigquery._sample_cell(args, cell_body) call_args = mock_query_execute.call_args[0] self.assertEqual(call_args[0]._output_type, 'dataframe') # test --verbose args['verbose'] = True with mock.patch('sys.stdout', new=StringIO()) as mocked_stdout: google.datalab.bigquery.commands._bigquery._sample_cell(args, cell_body) self.assertEqual(mocked_stdout.getvalue(), 'test_sql\n') args['verbose'] = False # bad query mock_get_notebook_item.return_value = None with self.assertRaises(Exception): google.datalab.bigquery.commands._bigquery._sample_cell(args, cell_body) # table passed args['query'] = None args['table'] = 'test.table' mock_get_notebook_item.return_value = google.datalab.bigquery.Table('test.table') google.datalab.bigquery.commands._bigquery._sample_cell(args, cell_body) # bad table mock_get_table.return_value = None with self.assertRaises(Exception): google.datalab.bigquery.commands._bigquery._sample_cell(args, cell_body) # view passed args['table'] = None args['view'] = 'test_view' mock_get_notebook_item.return_value = google.datalab.bigquery.View('test.view') google.datalab.bigquery.commands._bigquery._sample_cell(args, cell_body) # bad view mock_get_notebook_item.return_value = None with self.assertRaises(Exception): google.datalab.bigquery.commands._bigquery._sample_cell(args, cell_body)
def test_grow_async(self, begin_growth): self.set_callback_mocks() self.assertEqual(self.instance.state, CommunityState.NEW) growth_finish_method = "core.models.organisms.community.Growth.finish" with patch(growth_finish_method, side_effect=self.raise_unfinished) as finish_growth: done = False try: done = self.instance.grow() # start growth self.fail("Growth.finish not patched") except DSProcessUnfinished: pass first_growth = self.instance.growth_set.first() self.assertFalse(done) self.assertEqual(self.instance.growth_set.count(), 3) self.assertIsInstance(self.instance.current_growth, Growth) self.assertEqual(self.instance.current_growth.id, first_growth.id) # first new Growth self.instance.call_begin_callback.assert_called_once_with( "phase1", first_growth.input) self.assertFalse(self.instance.call_finish_callback.called) begin_growth.assert_called_once_with() self.assertEqual(self.instance.state, CommunityState.ASYNC) self.set_callback_mocks() begin_growth.reset_mock() try: done = False done = self.instance.grow() # continue growth in background except DSProcessUnfinished: pass self.assertFalse(done) self.assertEqual(self.instance.growth_set.count(), 3) self.assertIsInstance(self.instance.current_growth, Growth) self.assertFalse(self.instance.call_begin_callback.called) self.assertFalse(self.instance.call_finish_callback.called) self.assertFalse(begin_growth.called) self.assertEqual(self.instance.state, CommunityState.ASYNC) with patch(growth_finish_method, return_value=(first_growth.output, MockErrorQuerySet)) as finish_growth: second_growth = self.instance.growth_set.all()[1] with patch("core.models.organisms.community.Community.next_growth", return_value=second_growth): try: self.instance.grow( ) # first stage done, start second stage self.fail( "Unfinished community didn't raise any exception.") except DSProcessUnfinished: pass self.assertEqual(self.instance.growth_set.count(), 3) self.assertIsInstance(self.instance.current_growth, Growth) self.assertEqual(self.instance.current_growth.id, second_growth.id) self.instance.call_finish_callback.assert_called_once_with( "phase1", first_growth.output, MockErrorQuerySet) self.instance.call_begin_callback.assert_called_once_with( "phase2", second_growth.input) begin_growth.assert_called_once_with() self.assertEqual(self.instance.state, CommunityState.ASYNC) self.set_callback_mocks() begin_growth.reset_mock() with patch(growth_finish_method, return_value=(second_growth.output, MockErrorQuerySet)) as finish_growth: third_growth = self.instance.growth_set.last() with patch("core.models.organisms.community.Community.next_growth", return_value=third_growth): try: self.instance.grow( ) # second stage done, start third stage self.fail( "Unfinished community didn't raise any exception.") except DSProcessUnfinished: pass self.assertEqual(self.instance.growth_set.count(), 3) self.assertIsInstance(self.instance.current_growth, Growth) self.assertEqual(self.instance.current_growth.id, third_growth.id) self.instance.call_finish_callback.assert_called_once_with( "phase2", second_growth.output, MockErrorQuerySet) self.instance.call_begin_callback.assert_called_once_with( "phase3", second_growth.output) begin_growth.assert_called_once_with() self.assertEqual(self.instance.state, CommunityState.ASYNC) self.set_callback_mocks() begin_growth.reset_mock() with patch(growth_finish_method, return_value=(third_growth.output, MockErrorQuerySet)) as finish_growth: self.set_callback_mocks() with patch("core.models.organisms.community.Community.next_growth", side_effect=Growth.DoesNotExist): done = self.instance.grow() # finish growth self.assertTrue(done) self.assertEqual(self.instance.growth_set.count(), 3) self.assertIsInstance(self.instance.current_growth, Growth) self.assertEqual(self.instance.current_growth.id, third_growth.id) self.instance.call_finish_callback.assert_called_once_with( "phase3", third_growth.output, MockErrorQuerySet) self.assertIsInstance(self.instance.kernel, Individual) self.assertFalse(self.instance.call_begin_callback.called) self.assertFalse(begin_growth.called) self.assertEqual(self.instance.state, CommunityState.READY) third_growth.state = "Complete" third_growth.save() self.set_callback_mocks() with patch(growth_finish_method) as finish_growth: done = self.instance.grow() # don't grow further self.assertTrue(done) self.assertEqual(self.instance.growth_set.count(), 3) self.assertIsInstance(self.instance.current_growth, Growth) self.assertEqual(self.instance.current_growth.id, third_growth.id) self.assertFalse(self.instance.call_finish_callback.called) self.assertFalse(self.instance.call_begin_callback.called) self.assertFalse(begin_growth.called) self.assertFalse(finish_growth.called) self.assertEqual(self.instance.state, CommunityState.READY)
def test_create_install_iso(self, mock_grub_dir, mock_command, mock_Temporary, mock_copy, mock_setup_media_loader_directory, mock_BootLoaderConfig, mock_DeviceProvider): temp_squashfs = Mock() temp_squashfs.new_dir.return_value.name = 'temp-squashfs' temp_media_dir = Mock() temp_media_dir.new_dir.return_value.name = 'temp_media_dir' temp_esp_file = Mock() temp_esp_file.new_file.return_value.name = 'temp_esp' tmp_names = [temp_esp_file, temp_squashfs, temp_media_dir] def side_effect(prefix, path): return tmp_names.pop() bootloader_config = mock.Mock() mock_BootLoaderConfig.return_value = bootloader_config mock_Temporary.side_effect = side_effect m_open = mock_open() with patch('builtins.open', m_open, create=True): self.install_image.create_install_iso() self.setup.import_cdroot_files.assert_called_once_with( 'temp_media_dir') self.checksum.md5.assert_called_once_with( 'temp-squashfs/result-image.md5') mock_copy.assert_called_once_with( 'root_dir/boot/initrd-kernel_version', 'temp_media_dir/initrd.system_image') assert m_open.call_args_list == [ call('temp_media_dir/config.isoclient', 'w'), call('initrd_dir/config.vmxsystem', 'w') ] assert m_open.return_value.write.call_args_list == [ call('IMAGE="result-image.raw"\n'), call('IMAGE="result-image.raw"\n') ] kiwi.builder.install.FileSystemSquashFs.assert_called_once_with( custom_args={'compression': mock.ANY}, device_provider=mock_DeviceProvider.return_value, root_dir='temp-squashfs') self.squashed_image.create_on_file.assert_called_once_with( 'target_dir/result-image.raw.squashfs') mock_BootLoaderConfig.assert_called_once_with( 'grub2', self.xml_state, root_dir='root_dir', boot_dir='temp_media_dir', custom_args={'grub_directory_name': mock_grub_dir.return_value}) bootloader_config.setup_install_boot_images.assert_called_once_with( lookup_path='initrd_dir', mbrid=self.mbrid) mock_setup_media_loader_directory.assert_called_once_with( 'initrd_dir', 'temp_media_dir', bootloader_config.get_boot_theme.return_value) bootloader_config.write_meta_data.assert_called_once_with() bootloader_config.setup_install_image_config.assert_called_once_with( mbrid=self.mbrid) bootloader_config.write.assert_called_once_with() bootloader_config._create_embedded_fat_efi_image.assert_called_once_with( 'temp_esp') self.boot_image_task.create_initrd.assert_called_once_with( self.mbrid, 'initrd_kiwi_install', install_initrd=True) self.boot_image_task.cleanup.assert_called_once_with() self.kernel.copy_kernel.assert_called_once_with( 'temp_media_dir/boot/x86_64/loader', '/linux') self.kernel.copy_xen_hypervisor.assert_called_once_with( 'temp_media_dir/boot/x86_64/loader', '/xen.gz') assert mock_command.call_args_list == [ call([ 'cp', '-l', 'target_dir/result-image.x86_64-1.2.3.raw', 'temp-squashfs/result-image.raw' ]), call([ 'mv', 'target_dir/result-image.raw.squashfs', 'temp_media_dir' ]), call(['mv', 'initrd', 'temp_media_dir/boot/x86_64/loader/initrd']) ] self.iso_image.create_on_file.assert_called_once_with( 'target_dir/result-image.x86_64-1.2.3.install.iso') tmp_names = [temp_esp_file, temp_squashfs, temp_media_dir] self.install_image.initrd_system = 'dracut' m_open.reset_mock() with patch('builtins.open', m_open, create=True): self.install_image.create_install_iso() self.boot_image_task.include_module.assert_any_call('kiwi-dump') self.boot_image_task.include_module.assert_any_call('kiwi-dump-reboot') self.boot_image_task.omit_module.call_args_list == [ call('multipath'), call('module1'), call('module2') ] self.boot_image_task.set_static_modules.assert_called_once_with( ['module1', 'module2']) self.boot_image_task.include_file.assert_called_once_with( '/config.bootoptions') assert m_open.call_args_list == [ call('temp_media_dir/config.isoclient', 'w'), ] assert m_open.return_value.write.call_args_list == [ call('IMAGE="result-image.raw"\n') ] mock_BootLoaderConfig.reset_mock() tmp_names = [temp_esp_file, temp_squashfs, temp_media_dir] self.firmware.efi_mode.return_value = None with patch('builtins.open', m_open, create=True): self.install_image.create_install_iso() mock_BootLoaderConfig.assert_called_once_with( 'isolinux', self.xml_state, root_dir='root_dir', boot_dir='temp_media_dir') bootloader_config._create_embedded_fat_efi_image.assert_not_called()
def test_create_install_pxe_archive(self, mock_chmod, mock_symlink, mock_copy, mock_compress, mock_md5, mock_archive, mock_command, mock_Temporary): mock_Temporary.return_value.new_dir.return_value.name = 'tmpdir' archive = mock.Mock() mock_archive.return_value = archive checksum = mock.Mock() mock_md5.return_value = checksum compress = mock.Mock() mock_compress.return_value = compress m_open = mock_open() with patch('builtins.open', m_open, create=True): self.install_image.create_install_pxe_archive() mock_compress.assert_called_once_with( keep_source_on_compress=True, source_filename='target_dir/result-image.x86_64-1.2.3.raw') compress.xz.assert_called_once_with(None) assert mock_command.call_args_list[0] == call([ 'mv', compress.compressed_filename, 'tmpdir/result-image.x86_64-1.2.3.xz' ]) mock_md5.assert_called_once_with( 'target_dir/result-image.x86_64-1.2.3.raw') checksum.md5.assert_called_once_with( 'tmpdir/result-image.x86_64-1.2.3.md5') assert m_open.call_args_list == [ call('initrd_dir/config.vmxsystem', 'w'), call('tmpdir/result-image.x86_64-1.2.3.append', 'w') ] assert m_open.return_value.write.call_args_list == [ call('IMAGE="result-image.raw"\n'), call('pxe=1 custom_kernel_options\n') ] self.kernel.copy_kernel.assert_called_once_with( 'tmpdir', 'pxeboot.result-image.x86_64-1.2.3.kernel') mock_symlink.assert_called_once_with( 'pxeboot.result-image.x86_64-1.2.3.kernel', 'tmpdir/result-image.x86_64-1.2.3.kernel') self.kernel.copy_xen_hypervisor.assert_called_once_with( 'tmpdir', '/pxeboot.result-image.x86_64-1.2.3.xen.gz') self.boot_image_task.create_initrd.assert_called_once_with( self.mbrid, 'initrd_kiwi_install', install_initrd=True) self.boot_image_task.cleanup.assert_called_once_with() assert mock_command.call_args_list[1] == call([ 'mv', 'initrd', 'tmpdir/pxeboot.result-image.x86_64-1.2.3.initrd' ]) mock_chmod.assert_called_once_with( 'tmpdir/pxeboot.result-image.x86_64-1.2.3.initrd', 420) mock_archive.assert_called_once_with( 'target_dir/result-image.x86_64-1.2.3.install.tar') archive.create.assert_called_once_with('tmpdir') mock_chmod.reset_mock() mock_copy.reset_mock() self.install_image.initrd_system = 'dracut' m_open.reset_mock() with patch('builtins.open', m_open, create=True): self.install_image.create_install_pxe_archive() assert mock_copy.call_args_list == [ call('root_dir/boot/initrd-kernel_version', 'tmpdir/result-image.x86_64-1.2.3.initrd'), call('root_dir/config.bootoptions', 'tmpdir/result-image.x86_64-1.2.3.config.bootoptions') ] assert mock_chmod.call_args_list == [ call('tmpdir/result-image.x86_64-1.2.3.initrd', 420), call('tmpdir/pxeboot.result-image.x86_64-1.2.3.initrd', 420) ] assert m_open.call_args_list == [ call('tmpdir/result-image.x86_64-1.2.3.append', 'w'), ] assert m_open.return_value.write.call_args_list == [ call(' '.join([ 'rd.kiwi.install.pxe', 'rd.kiwi.install.image=http://example.com/image.xz', 'custom_kernel_options\n' ])) ] self.boot_image_task.include_module.assert_any_call('kiwi-dump') self.boot_image_task.include_module.assert_any_call('kiwi-dump-reboot') self.boot_image_task.omit_module.call_args_list == [ call('multipath'), call('module1'), call('module2') ] self.boot_image_task.set_static_modules.assert_called_once_with( ['module1', 'module2'])
def setUp(self): self.get_build_targets = mock.patch('kojihub.get_build_targets').start() self.exports = kojihub.RootExports()
def test_api(self): with mock.patch("cuckoo.main.cuckoo_api") as p: p.return_value = None main.main(("--cwd", cwd(), "api"), standalone_mode=False) p.assert_called_once_with("localhost", 8090, False)
def test_submit(self): with mock.patch("cuckoo.main.submit_tasks") as p: p.return_value = [] main.main(( "--cwd", cwd(), "submit", Files.create(cwd(), "a.txt", "hello") ), standalone_mode=False)
def test_clean(self): with mock.patch("cuckoo.main.cuckoo_clean") as p: p.return_value = None main.main(("--cwd", cwd(), "clean"), standalone_mode=False) p.assert_called_once_with()
def test_get_arg_success(test_input, expected): with mock.patch('sys.argv', ["file_name", test_input]): generator = generate.Generator() generator.get_command() assert generator.command == expected
def test_dnsserve(self): with mock.patch("cuckoo.main.cuckoo_dnsserve") as p: p.return_value = None main.main(("--cwd", cwd(), "dnsserve"), standalone_mode=False) p.assert_called_once_with("0.0.0.0", 53, None, None)
def put_tender_complaint_document(self): response = self.app.post( "/tenders/{}/complaints/{}/documents?acc_token={}".format( self.tender_id, self.complaint_id, self.complaint_owner_token ), upload_files=[("file", "name.doc", b"content")], ) self.assertEqual(response.status, "201 Created") self.assertEqual(response.content_type, "application/json") doc_id = response.json["data"]["id"] self.assertIn(doc_id, response.headers["Location"]) response = self.app.put( "/tenders/{}/complaints/{}/documents/{}?acc_token={}".format( self.tender_id, self.complaint_id, doc_id, self.complaint_owner_token ), status=404, upload_files=[("invalid_name", "name.doc", b"content")], ) self.assertEqual(response.status, "404 Not Found") self.assertEqual(response.content_type, "application/json") self.assertEqual(response.json["status"], "error") self.assertEqual(response.json["errors"], [{"description": "Not Found", "location": "body", "name": "file"}]) response = self.app.put( "/tenders/{}/complaints/{}/documents/{}?acc_token={}".format( self.tender_id, self.complaint_id, doc_id, self.tender_token ), upload_files=[("file", "name.doc", b"content2")], status=403, ) self.assertEqual(response.status, "403 Forbidden") self.assertEqual(response.content_type, "application/json") self.assertEqual(response.json["errors"][0]["description"], "Can update document only author") response = self.app.put( "/tenders/{}/complaints/{}/documents/{}?acc_token={}".format( self.tender_id, self.complaint_id, doc_id, self.complaint_owner_token ), upload_files=[("file", "name.doc", b"content2")], ) self.assertEqual(response.status, "200 OK") self.assertEqual(response.content_type, "application/json") self.assertEqual(doc_id, response.json["data"]["id"]) key = response.json["data"]["url"].split("?")[-1] response = self.app.get( "/tenders/{}/complaints/{}/documents/{}?{}".format(self.tender_id, self.complaint_id, doc_id, key) ) self.assertEqual(response.status, "200 OK") self.assertEqual(response.content_type, "application/msword") self.assertEqual(response.content_length, 8) self.assertEqual(response.body, b"content2") response = self.app.get("/tenders/{}/complaints/{}/documents/{}".format(self.tender_id, self.complaint_id, doc_id)) self.assertEqual(response.status, "200 OK") self.assertEqual(response.content_type, "application/json") self.assertEqual(doc_id, response.json["data"]["id"]) self.assertEqual("name.doc", response.json["data"]["title"]) response = self.app.put( "/tenders/{}/complaints/{}/documents/{}?acc_token={}".format( self.tender_id, self.complaint_id, doc_id, self.complaint_owner_token ), "content3", content_type="application/msword", ) self.assertEqual(response.status, "200 OK") self.assertEqual(response.content_type, "application/json") self.assertEqual(doc_id, response.json["data"]["id"]) key = response.json["data"]["url"].split("?")[-1] response = self.app.get( "/tenders/{}/complaints/{}/documents/{}?{}".format(self.tender_id, self.complaint_id, doc_id, key) ) self.assertEqual(response.status, "200 OK") self.assertEqual(response.content_type, "application/msword") self.assertEqual(response.content_length, 8) self.assertEqual(response.body, b"content3") with patch("openprocurement.tender.core.views.complaint.RELEASE_2020_04_19", get_now() - timedelta(days=1)): with patch("openprocurement.tender.core.validation.RELEASE_2020_04_19", get_now() - timedelta(days=1)): response = self.app.patch_json( "/tenders/{}/complaints/{}?acc_token={}".format(self.tender_id, self.complaint_id, self.complaint_owner_token), {"data": {"status": "pending"}}, status=403 ) self.assertEqual( response.json, {"status": "error", "errors": [ {"location": "body", "name": "data", "description": "Can't update complaint from draft to pending status"}]} ) with patch("openprocurement.tender.core.views.complaint.RELEASE_2020_04_19", get_now() + timedelta(days=1)): with patch("openprocurement.tender.core.validation.RELEASE_2020_04_19", get_now() + timedelta(days=1)): response = self.app.patch_json( "/tenders/{}/complaints/{}?acc_token={}".format(self.tender_id, self.complaint_id, self.complaint_owner_token), {"data": {"status": "pending"}}, ) self.assertEqual(response.status, "200 OK") self.assertEqual(response.json["data"]["status"], "pending") response = self.app.put( "/tenders/{}/complaints/{}/documents/{}?acc_token={}".format( self.tender_id, self.complaint_id, doc_id, self.complaint_owner_token ), "content", content_type="application/msword", ) self.assertEqual(response.status, "200 OK") self.assertEqual(response.content_type, "application/json") self.set_status("complete") response = self.app.put( "/tenders/{}/complaints/{}/documents/{}?acc_token={}".format( self.tender_id, self.complaint_id, doc_id, self.complaint_owner_token ), upload_files=[("file", "name.doc", b"content3")], status=403, ) self.assertEqual(response.status, "403 Forbidden") self.assertEqual(response.content_type, "application/json") self.assertEqual( response.json["errors"][0]["description"], "Can't update document in current (complete) tender status" )
def test_get_arg_failure(): with pytest.raises(SystemExit) as pytest_wrapped_e: with mock.patch('sys.argv', ["file_name"]): generate.Generator().get_command() assert pytest_wrapped_e.type == SystemExit assert pytest_wrapped_e.value.code == 1
def secrets_api_mock(): with mock.patch('databricks_cli.secrets.cli.SecretApi') as SecretApiMock: _secrets_api_mock = mock.MagicMock() SecretApiMock.return_value = _secrets_api_mock yield _secrets_api_mock
def patch_tender_complaint_document(self): response = self.app.post( "/tenders/{}/complaints/{}/documents?acc_token={}".format( self.tender_id, self.complaint_id, self.complaint_owner_token ), upload_files=[("file", "name.doc", b"content")], ) self.assertEqual(response.status, "201 Created") self.assertEqual(response.content_type, "application/json") doc_id = response.json["data"]["id"] self.assertIn(doc_id, response.headers["Location"]) response = self.app.patch_json( "/tenders/{}/complaints/{}/documents/{}?acc_token={}".format( self.tender_id, self.complaint_id, doc_id, self.tender_token ), {"data": {"description": "document description"}}, status=403, ) self.assertEqual(response.status, "403 Forbidden") self.assertEqual(response.content_type, "application/json") self.assertEqual(response.json["errors"][0]["description"], "Can update document only author") response = self.app.patch_json( "/tenders/{}/complaints/{}/documents/{}?acc_token={}".format( self.tender_id, self.complaint_id, doc_id, self.complaint_owner_token ), {"data": {"description": "document description"}}, ) self.assertEqual(response.status, "200 OK") self.assertEqual(response.content_type, "application/json") self.assertEqual(doc_id, response.json["data"]["id"]) response = self.app.get("/tenders/{}/complaints/{}/documents/{}".format(self.tender_id, self.complaint_id, doc_id)) self.assertEqual(response.status, "200 OK") self.assertEqual(response.content_type, "application/json") self.assertEqual(doc_id, response.json["data"]["id"]) self.assertEqual("document description", response.json["data"]["description"]) with patch("openprocurement.tender.core.views.complaint.RELEASE_2020_04_19", get_now() + timedelta(days=1)): with patch("openprocurement.tender.core.validation.RELEASE_2020_04_19", get_now() + timedelta(days=1)): response = self.app.patch_json( "/tenders/{}/complaints/{}?acc_token={}".format(self.tender_id, self.complaint_id, self.complaint_owner_token), {"data": {"status": "pending"}}, ) self.assertEqual(response.status, "200 OK") self.assertEqual(response.json["data"]["status"], "pending") response = self.app.patch_json( "/tenders/{}/complaints/{}/documents/{}?acc_token={}".format( self.tender_id, self.complaint_id, doc_id, self.complaint_owner_token ), {"data": {"description": "document description2"}}, ) self.assertEqual(response.status, "200 OK") self.assertEqual(response.content_type, "application/json") self.assertEqual(response.json["data"]["description"], "document description2") self.set_status("complete") response = self.app.patch_json( "/tenders/{}/complaints/{}/documents/{}?acc_token={}".format( self.tender_id, self.complaint_id, doc_id, self.complaint_owner_token ), {"data": {"description": "document description"}}, status=403, ) self.assertEqual(response.status, "403 Forbidden") self.assertEqual(response.content_type, "application/json") self.assertEqual( response.json["errors"][0]["description"], "Can't update document in current (complete) tender status" )
def setUp(self): request = patch('auth.utils.requests', name='test.BaseTestCase') self.req = request.start() self.req.exceptions = requests.exceptions self.req.patcher = request self.addCleanup(request.stop)
def test_deploy_custom_templates( self, mock_check_hypervisor_stats, mock_get_key, mock_create_env, generate_certs_mock, mock_get_templte_contents, mock_process_multiple_env, wait_for_stack_ready_mock, mock_remove_known_hosts, mock_keystone_initialize, mock_sleep, mock_setup_endpoints, mock_create_overcloudrc, mock_generate_overcloud_passwords, mock_create_tempest_deployer_input, mock_deploy_postconfig, mock_breakpoints_cleanup, mock_events): arglist = ['--templates', '/home/stack/tripleo-heat-templates'] verifylist = [ ('templates', '/home/stack/tripleo-heat-templates'), ] mock_generate_overcloud_passwords.return_value = self._get_passwords() clients = self.app.client_manager orchestration_client = clients.orchestration orchestration_client.stacks.get.return_value = fakes.create_tht_stack() mock_events.return_value = [] mock_check_hypervisor_stats.return_value = { 'count': 4, 'memory_mb': 4096, 'vcpus': 8, } mock_get_key.return_value = "PASSWORD" clients.network.api.find_attr.return_value = {"id": "network id"} mock_create_env.return_value = "/fake/path" mock_env = fakes.create_env() mock_process_multiple_env.return_value = [{}, mock_env] mock_get_templte_contents.return_value = [{}, "template"] wait_for_stack_ready_mock.return_value = True parsed_args = self.check_parser(self.cmd, arglist, verifylist) baremetal = clients.baremetal baremetal.node.list.return_value = range(10) with mock.patch('tempfile.mkstemp') as mkstemp: mkstemp.return_value = (os.open(self.parameter_defaults_env_file, os.O_RDWR), self.parameter_defaults_env_file) self.cmd.take_action(parsed_args) args, kwargs = orchestration_client.stacks.update.call_args self.assertEqual(args, (orchestration_client.stacks.get().id, )) self.assertEqual(kwargs['files'], {}) self.assertEqual(kwargs['template'], 'template') self.assertEqual(kwargs['environment'], mock_env) self.assertEqual(kwargs['stack_name'], 'overcloud') self.assertEqual(kwargs['clear_parameters'], mock_env['parameter_defaults'].keys()) mock_get_templte_contents.assert_called_with( '/home/stack/tripleo-heat-templates/' + constants.OVERCLOUD_YAML_NAMES[0]) mock_create_tempest_deployer_input.assert_called_with() mock_process_multiple_env.assert_called_with( [self.parameter_defaults_env_file])
def test_rebuild_quotas_calls_quotas_script(self): with mock.patch('kinto.core.scripts.quotas.rebuild_quotas') as mocked: code = scripts.rebuild_quotas({'registry': self.registry}) assert code == 0 mocked.assert_called_with(self.registry.storage, dry_run=False)
def test_handle_exception(self): raise SkipTest('For unknown reasons this test hangs by consuming tons of CPU and memory.') with patch('w3af.core.ui.gui.exception_handling.unhandled.sys') as mock_sys: handle_crash(self.w3af_core, KeyboardInterrupt, Mock(), Mock()) mock_sys.exit.called_once_with(0)
def test_cli_status(self): mock_tool = MagicMock() with patch('ooni.report.cli.tool', mock_tool): from ooni.report import cli cli.run(["status"]) self.assertTrue(mock_tool.status.called)
def test_cx_state_psutil(aggregator, check): sconn = namedtuple( 'sconn', ['fd', 'family', 'type', 'laddr', 'raddr', 'status', 'pid']) conn = [ sconn( fd=-1, family=socket.AF_INET, type=socket.SOCK_STREAM, laddr=('127.0.0.1', 50482), raddr=('127.0.0.1', 2638), status='ESTABLISHED', pid=1416, ), sconn( fd=-1, family=socket.AF_INET6, type=socket.SOCK_STREAM, laddr=('::', 50482), raddr=('::', 2638), status='ESTABLISHED', pid=42, ), sconn( fd=-1, family=socket.AF_INET6, type=socket.SOCK_STREAM, laddr=('::', 49163), raddr=(), status='LISTEN', pid=1416, ), sconn( fd=-1, family=socket.AF_INET, type=socket.SOCK_STREAM, laddr=('0.0.0.0', 445), raddr=(), status='LISTEN', pid=4, ), sconn( fd=-1, family=socket.AF_INET6, type=socket.SOCK_STREAM, laddr=('::1', 56521), raddr=('::1', 17123), status='TIME_WAIT', pid=0, ), sconn(fd=-1, family=socket.AF_INET6, type=socket.SOCK_DGRAM, laddr=('::', 500), raddr=(), status='NONE', pid=892), sconn( fd=-1, family=socket.AF_INET6, type=socket.SOCK_STREAM, laddr=('::1', 56493), raddr=('::1', 17123), status='TIME_WAIT', pid=0, ), sconn( fd=-1, family=socket.AF_INET, type=socket.SOCK_STREAM, laddr=('127.0.0.1', 54541), raddr=('127.0.0.1', 54542), status='ESTABLISHED', pid=20500, ), ] results = { 'system.net.tcp6.time_wait': 2, 'system.net.tcp4.listening': 1, 'system.net.tcp6.closing': 0, 'system.net.tcp4.closing': 0, 'system.net.tcp4.time_wait': 0, 'system.net.tcp6.established': 1, 'system.net.tcp4.established': 2, 'system.net.tcp6.listening': 1, 'system.net.tcp4.opening': 0, 'system.net.udp4.connections': 0, 'system.net.udp6.connections': 1, 'system.net.tcp6.opening': 0, } with mock.patch('datadog_checks.network.network.psutil') as mock_psutil: mock_psutil.net_connections.return_value = conn check._setup_metrics({}) check._cx_state_psutil() for _, m in iteritems(aggregator._metrics): assert results[m[0].name] == m[0].value
def test_main(self): with patch('celery.__main__.maybe_patch_concurrency') as mpc: with patch('celery.bin.celery.main') as main: __main__.main() mpc.assert_called_with() main.assert_called_with()
def test_cli_upload_all(self): mock_tool = MagicMock() with patch('ooni.report.cli.tool', mock_tool): from ooni.report import cli cli.run(["upload"]) self.assertTrue(mock_tool.upload_all.called)
def setUp(self): patch("acs_test_scripts.Utilities.HttpDownloaderUtil.hashlib.md5").start() patch("acs_test_scripts.Utilities.HttpDownloaderUtil.shutil.move").start() patch("acs_test_scripts.Utilities.HttpDownloaderUtil.os.remove").start() patch("acs_test_scripts.Utilities.HttpDownloaderUtil.tempfile.NamedTemporaryFile").start()
def test_compat_command_decorator(self): with patch('celery.bin.celery.CeleryCommand') as CC: self.assertEqual(command(), CC.register_command) fun = Mock(name='fun') command(fun) CC.register_command.assert_called_with(fun)
import unittest from mock import MagicMock, patch with patch('meniscus.data.datastore.datasource_handler', MagicMock()): from meniscus.storage.short_term_store import persist_message class WhenTestingStoragePersistence(unittest.TestCase): def setUp(self): self.message = { "processid": "3071", "appname": "dhcpcd", "timestamp": "2013-04-05T15:51:18.607457-05:00", "hostname": "tohru", "priority": "30", "version": "1", "messageid": "-", "message": "wlan0: leased 10.6.173.172 for 3600 seconds\n", "sd": { "origin": { "software": "rsyslogd", "swVersion": "7.2.5", "x-pid": "24592", "x-info": "http://www.rsyslog.com" } } } self.db_handler = MagicMock() def test_persist_message_calls_db_put(self):
def test_load_extensions_no_commands(self): with patch('celery.bin.celery.Extensions') as Ext: ext = Ext.return_value = Mock(name='Extension') ext.load.return_value = None x = CeleryCommand(app=self.app) x.load_extension_commands()
def setUp(self): super(MyTestCase, self).setUp() self.patcher2 = patch( 'pyexcel_handsontable.handsontable._dump_dict') self.dump_dict = self.patcher2.start()
def test_persist_message_calls_db_put(self): with patch('meniscus.storage.short_term_store._db_handler', self.db_handler): persist_message(self.message) self.db_handler.put.assert_called_once_with('logs', self.message)