def test_multi(self): now = 1379406823.9 fo = MockStdout() with mock.patch('dnf.cli.progress._term_width', return_value=60), \ mock.patch('dnf.cli.progress.time', lambda: now): p = dnf.cli.progress.MultiFileProgressMeter(fo) p.start(2, 30) for i in range(11): p.progress('foo', 10.0, float(i)) self.assertEquals(len(fo.out), i*2 + 1) if i == 10: p.end('foo', 10, None) now += 0.5 p.progress('bar', 20.0, float(i*2)) self.assertEquals(len(fo.out), i*2 + 2 + (i == 10 and 2)) if i == 10: p.end('bar', 20, 'some error') now += 0.5 # check "end" events self.assertEquals([o for o in fo.out if o.endswith('\n')], [ '(1/2): foo 1.0 B/s | 10 B 00:10 \n', '[FAILED] bar: some error \n']) # verify we estimated a sane rate (should be around 3 B/s) self.assertTrue(2.0 < p.rate < 4.0)
def download(self, errors=None, err={}): # utility function, calls Base.download_packages() # and returns the list of relative URLs it used. urls = [] def dlp(targets, failfast): target, = targets self.assertEqual(target.__class__.__name__, 'PackageTarget') self.assertTrue(failfast) urls.append(target.relative_url) err = errors and errors.pop(0) if err: # PackageTarget.err is not writable targets[0] = Bunch(cbdata=target.cbdata, err=err) def lock_dir(_dir): return os.path.join(support.USER_RUNDIR, dnf.const.PROGRAM_NAME) with mock.patch('librepo.download_packages', dlp),\ mock.patch('dnf.lock._fit_lock_dir', lock_dir): try: self.base.download_packages([self.pkg]) except dnf.exceptions.DownloadError as e: pass return urls
def _verify_expected_endpoint_url(region, bucket, key, s3_config, is_secure=True, customer_provided_endpoint=None, expected_url=None): http_response = mock.Mock() http_response.status_code = 200 http_response.headers = {} http_response.content = b'' environ = {} with mock.patch('os.environ', environ): environ['AWS_ACCESS_KEY_ID'] = 'access_key' environ['AWS_SECRET_ACCESS_KEY'] = 'secret_key' environ['AWS_CONFIG_FILE'] = 'no-exist-foo' session = create_session() session.config_filename = 'no-exist-foo' config = None if s3_config is not None: config = Config(s3=s3_config) s3 = session.create_client('s3', region_name=region, use_ssl=is_secure, config=config, endpoint_url=customer_provided_endpoint) with mock.patch('botocore.endpoint.Session.send') as mock_send: mock_send.return_value = http_response s3.put_object(Bucket=bucket, Key=key, Body=b'bar') request_sent = mock_send.call_args[0][0] assert_equal(request_sent.url, expected_url)
def test_content_sha256_set_if_md5_is_unavailable(self): with mock.patch('botocore.auth.MD5_AVAILABLE', False): with mock.patch('botocore.handlers.MD5_AVAILABLE', False): self.client.put_object(Bucket='foo', Key='bar', Body='baz') sent_headers = self.get_sent_headers() unsigned = 'UNSIGNED-PAYLOAD' self.assertNotEqual(sent_headers['x-amz-content-sha256'], unsigned) self.assertNotIn('content-md5', sent_headers)
def test_drpm_download(self): # the testing drpm is about 150% of the target.. self.pkg.repo.deltarpm = 1 dnf.drpm.APPLYDELTA = '/bin/true' with mock.patch('dnf.drpm.MAX_PERCENTAGE', 50): self.assertEquals(self.download(), ['tour-5-1.noarch.rpm']) with mock.patch('dnf.drpm.MAX_PERCENTAGE', 200): self.assertEquals(self.download(), ['drpms/tour-5-1.noarch.drpm'])
def test_print_versions(self): yumbase = support.MockYumBase() with mock.patch('sys.stdout') as stdout,\ mock.patch('dnf.sack.rpmdb_sack', return_value=yumbase.sack): dnf.cli.cli.print_versions(['pepper', 'tour'], yumbase) written = ''.join([mc[1][0] for mc in stdout.method_calls if mc[0] == 'write']) self.assertEqual(written, VERSIONS_OUTPUT)
def test_incompatible_openssl_version(self): with mock.patch('ssl.OPENSSL_VERSION_INFO', new=(0, 9, 8, 11, 15)): with mock.patch('warnings.warn') as mock_warn: self.session.create_client('iot-data', 'us-east-1') call_args = mock_warn.call_args[0] warning_message = call_args[0] warning_type = call_args[1] # We should say something specific about the service. self.assertIn('iot-data', warning_message) self.assertEqual(warning_type, UnsupportedTLSVersionWarning)
def setUp(self): self.url = URL self.redmine = Redmine(self.url) self.response = mock.Mock(status_code=200, json=json_response(response)) patcher_get = mock.patch('requests.get', return_value=self.response) patcher_put = mock.patch('requests.put', return_value=self.response) patcher_delete = mock.patch('requests.delete', return_value=self.response) patcher_get.start() patcher_put.start() patcher_delete.start() self.addCleanup(patcher_get.stop) self.addCleanup(patcher_put.stop) self.addCleanup(patcher_delete.stop)
def setUp(self): self.url = URL self.redmine = Redmine(self.url) self.response = mock.Mock() patcher_get = mock.patch("requests.get", return_value=self.response) patcher_post = mock.patch("requests.post", return_value=self.response) patcher_put = mock.patch("requests.put", return_value=self.response) patcher_get.start() patcher_post.start() patcher_put.start() self.addCleanup(patcher_get.stop) self.addCleanup(patcher_post.stop) self.addCleanup(patcher_put.stop)
def setUp(self): self.patch_urlparse = mock.patch('freight_forwarder.container_ship.urlparse') self.patch_utils = mock.patch('freight_forwarder.container_ship.utils') self.patch_urllib = mock.patch('freight_forwarder.container_ship.urllib3') self.patch_docker_client = mock.patch('freight_forwarder.container_ship.docker.Client') self.patch_image = mock.patch('freight_forwarder.container_ship.Image') self.injector = InjectorFactory() self.mock_urlparse = self.patch_urlparse.start() self.mock_utils = self.patch_utils.start() self.mock_urllib = self.patch_urllib.start() self.mock_docker_client = self.patch_docker_client.start() self.mock_image = self.patch_image.start()
def test_setup_stdout(self): # No stdout output can be seen when sys.stdout is patched, debug msgs, # etc. included. with mock.patch('sys.stdout') as mock_stdout: mock_stdout.encoding = None retval = dnf.i18n.setup_stdout() self.assertFalse(retval) with mock.patch('sys.stdout') as mock_stdout: mock_stdout.encoding = 'UTF-8' retval = dnf.i18n.setup_stdout() self.assertTrue(retval) with mock.patch('sys.stdout') as mock_stdout: mock_stdout.encoding = 'ISO-8859-2' retval = dnf.i18n.setup_stdout() self.assertFalse(retval)
def test_with_http_host(self): with mock.patch('subprocess.call') as fake_call: call_docker(['ps'], {'--host': 'http://mydocker.net:2333'}) assert fake_call.call_args[0][0] == [ 'docker', '--host', 'tcp://mydocker.net:2333', 'ps', ]
def setUp(self): self.url = URL self.redmine = Redmine(self.url) self.response = mock.Mock(**{'status_code': 200, 'json.return_value': response}) patcher = mock.patch('requests.get', return_value=self.response) patcher.start() self.addCleanup(patcher.stop)
def test_instantiation(self): # Instantiate the class. dynamodb_class = type( 'dynamodb', (DynamoDBHighLevelResource, ServiceResource), {'meta': self.meta}) with mock.patch('boto3.dynamodb.transform.TransformationInjector') \ as mock_injector: dynamodb_class(client=self.client) # It should have fired the following events upon instantiation. event_call_args = self.events.register.call_args_list self.assertEqual( event_call_args, [mock.call( 'provide-client-params.dynamodb', copy_dynamodb_params, unique_id='dynamodb-create-params-copy'), mock.call( 'before-parameter-build.dynamodb', mock_injector.return_value.inject_condition_expressions, unique_id='dynamodb-condition-expression'), mock.call( 'before-parameter-build.dynamodb', mock_injector.return_value.inject_attribute_value_input, unique_id='dynamodb-attr-value-input'), mock.call( 'after-call.dynamodb', mock_injector.return_value.inject_attribute_value_output, unique_id='dynamodb-attr-value-output')] )
def setUp(self): super(BaseS3OperationTest, self).setUp() self.region = 'us-west-2' self.client = self.session.create_client( 's3', self.region) self.session_send_patch = mock.patch('botocore.endpoint.Session.send') self.http_session_send_mock = self.session_send_patch.start()
def test_use_correct_docstring_writer(self): with mock.patch( 'botocore.docs.docstring' '.document_wait_method') as mock_writer: docstring = WaiterDocstring() str(docstring) self.assertTrue(mock_writer.called)
def assert_func(self, func, args, expected_ret): m = mock.mock_open() m.return_value = self.data with mock.patch('builtins.open', m, create=True): ret = func('/foo/bar', **args) m.assert_called_once_with('/foo/bar', 'rb') self.assertEqual(expected_ret, ret, str(func))
def test_with_host_option_shorthand_equal(self): with mock.patch('subprocess.call') as fake_call: call_docker(['ps'], {'--host': '=tcp://mydocker.net:2333'}) assert fake_call.call_args[0][0] == [ 'docker', '--host', 'tcp://mydocker.net:2333', 'ps' ]
def test_warning_in_swarm_mode(self): mock_client = mock.create_autospec(docker.APIClient) mock_client.info.return_value = {'Swarm': {'LocalNodeState': 'active'}} with mock.patch('compose.cli.main.log') as fake_log: warn_for_swarm_mode(mock_client) assert fake_log.warning.call_count == 1
def test_emit_response_received(self): recording_handler = RecordingHandler() self.client.meta.events.register( 'response-received.ec2.DescribeRegions', recording_handler.record) with mock.patch( 'botocore.httpsession.URLLib3Session.send') as mock_send: response_body = ( b'<?xml version="1.0" ?>' b'<DescribeRegionsResponse xmlns="">' b'</DescribeRegionsResponse>' ) mock_send.return_value = mock.Mock( status_code=200, headers={}, content=response_body) self.client.describe_regions() self.assertEqual( recording_handler.recorded_events, [ ('response-received.ec2.DescribeRegions', { 'exception': None, 'response_dict': { 'body': response_body, 'headers': {}, 'context': mock.ANY, 'status_code': 200 }, 'parsed_response': { 'ResponseMetadata': mock.ANY}, 'context': mock.ANY }) ] )
def test_retry_dns_error(self): with mock.patch('socket.gethostbyname', side_effect=socket.gaierror(-5, 'No address associated with hostname')): crawler = get_crawler(SimpleSpider) with LogCapture() as l: yield crawler.crawl("http://example.com/") self._assert_retried(l)
def test_use_correct_docstring_writer(self): with mock.patch( 'botocore.docs.docstring' '.document_model_driven_method') as mock_writer: docstring = ClientMethodDocstring() str(docstring) self.assertTrue(mock_writer.called)
def setUp(self): super(TestS3GetBucketLifecycle, self).setUp() self.region = 'us-west-2' self.client = self.session.create_client( 's3', self.region) self.session_send_patch = mock.patch('botocore.endpoint.Session.send') self.http_session_send_mock = self.session_send_patch.start()
def test_provided_endpoint_url_is_not_mutated(self): s3 = self.session.create_client('s3', endpoint_url='https://foo.com') with mock.patch('botocore.endpoint.Session.send') as mock_send: mock_send.return_value = self.http_response s3.put_object(Bucket='mybucket', Key='mykey', Body='mybody') request_sent = mock_send.call_args[0][0] self.assertEqual( 'https://foo.com/mybucket/mykey', request_sent.url)
def assert_will_retry_n_times(self, method, num_retries): num_responses = num_retries + 1 with mock.patch('botocore.endpoint.Session.send') as mock_send: self.add_n_retryable_responses(mock_send, num_responses) with self.assertRaisesRegexp( ClientError, 'reached max retries: %s' % num_retries): method() self.assertEqual(mock_send.call_count, num_responses)
def test_inspect_stack(self): with mock.patch('inspect.stack', side_effect=IndexError): with warnings.catch_warnings(record=True) as w: DeprecatedName = create_deprecated_class('DeprecatedName', NewName) class SubClass(DeprecatedName): pass self.assertIn("Error detecting parent module", str(w[0].message))
def test_handle(self): os.path.getsize = lambda p: self.data["size"] os.path.getmtime = lambda p: 123412341234 m = mock.mock_open() m.return_value = io.BytesIO() with mock.patch("builtins.open", m, create=True): self.task.handle() self.assertEqual(1, len(self.task.items_store.get_items_by_id(item_id=self.item.id)))
def test_throttle(self): self.repo.throttle = '50%' self.repo.bandwidth = '10M' self.assertEquals(self.repo.throttle, 0.5) self.assertEquals(self.repo.bandwidth, 10 << 20) opts = {} with mock.patch('librepo.Handle.setopt', opts.__setitem__): self.repo.get_handle() self.assertEquals(opts[librepo.LRO_MAXSPEED], 5 << 20)
def test_dispatch_generic_connection_error(self): with pytest.raises(errors.ConnectionErrorGeneric): with mock.patch( 'compose.cli.command.call_silently', autospec=True, side_effect=[0, 1] ): with friendly_error_message(): raise ConnectionError()
def test_default_endpoint_for_path_addressing(self): s3 = self.session.create_client( 's3', config=Config(s3={'addressing_style': 'path'})) with mock.patch('botocore.endpoint.Session.send') \ as mock_send: mock_send.return_value = self.http_response s3.put_object(Bucket='mybucket', Key='mykey', Body='mybody') request_sent = mock_send.call_args[0][0] self.assertEqual( 'https://s3.amazonaws.com/mybucket/mykey', request_sent.url)