desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Check the documents length matches the iterator details'
def test_cloudsearch_results_internal_consistancy(self):
search = SearchConnection(endpoint=HOSTNAME) results = search.search(q='Test') self.assertEqual(len(results), len(results.docs))
'Check next page query is correct'
def test_cloudsearch_search_nextpage(self):
search = SearchConnection(endpoint=HOSTNAME) query1 = search.build_query(q='Test') query2 = search.build_query(q='Test') results = search(query2) self.assertEqual(results.next_page().query.start, (query1.start + query1.size)) self.assertEqual(query1.q, query2.q)
'Check that endpoints & ARNs are correctly returned from AWS'
def test_cloudsearch_connect_result_endpoints(self):
self.set_http_response(status_code=200) api_response = self.service_connection.create_domain('demo') domain = Domain(self, api_response['CreateDomainResponse']['CreateDomainResult']['DomainStatus']) self.assertEqual(domain.doc_service_endpoint, 'doc-demo.us-east-1.cloudsearch.amazonaws.com') self.as...
'Check that domain statuses are correctly returned from AWS'
def test_cloudsearch_connect_result_statuses(self):
self.set_http_response(status_code=200) api_response = self.service_connection.create_domain('demo') domain = Domain(self, api_response['CreateDomainResponse']['CreateDomainResult']['DomainStatus']) self.assertEqual(domain.created, True) self.assertEqual(domain.processing, False) self.assertEqua...
'Check that the domain information is correctly returned from AWS'
def test_cloudsearch_connect_result_details(self):
self.set_http_response(status_code=200) api_response = self.service_connection.create_domain('demo') domain = Domain(self, api_response['CreateDomainResponse']['CreateDomainResult']['DomainStatus']) self.assertEqual(domain.id, '1234567890/demo') self.assertEqual(domain.name, 'demo')
'Check that the correct arguments are sent to AWS when creating a cloudsearch connection.'
def test_cloudsearch_deletion(self):
self.set_http_response(status_code=200) self.service_connection.delete_domain('demo') self.assert_request_parameters({'Action': 'DeleteDomain', 'ContentType': 'JSON', 'DomainName': 'demo', 'Version': '2013-01-01'})
'Check that the correct arguments are sent to AWS when indexing a domain.'
def test_cloudsearch_index_documents(self):
self.set_http_response(status_code=200) self.service_connection.index_documents('demo') self.assert_request_parameters({'Action': 'IndexDocuments', 'ContentType': 'JSON', 'DomainName': 'demo', 'Version': '2013-01-01'})
'Check that the AWS response is being parsed correctly when indexing a domain.'
def test_cloudsearch_index_documents_resp(self):
self.set_http_response(status_code=200) api_response = self.service_connection.index_documents('demo') fields = api_response['IndexDocumentsResponse']['IndexDocumentsResult']['FieldNames'] self.assertEqual(fields, ['average_score', 'brand_id', 'colors', 'context', 'context_owner', 'created_at', 'creator...
'Check that a simple add document actually sends an add document request to AWS.'
def test_cloudsearch_add_basics(self):
document = DocumentServiceConnection(endpoint='doc-demo-userdomain.us-east-1.cloudsearch.amazonaws.com') document.add('1234', {'id': '1234', 'title': 'Title 1', 'category': ['cat_a', 'cat_b', 'cat_c']}) document.commit() args = json.loads(HTTPretty.last_request.body.decode('utf-8'))[0] self.asser...
'Check that a simple add document sends correct document metadata to AWS.'
def test_cloudsearch_add_single_basic(self):
document = DocumentServiceConnection(endpoint='doc-demo-userdomain.us-east-1.cloudsearch.amazonaws.com') document.add('1234', {'id': '1234', 'title': 'Title 1', 'category': ['cat_a', 'cat_b', 'cat_c']}) document.commit() args = json.loads(HTTPretty.last_request.body.decode('utf-8'))[0] self.asser...
'Check that a simple add document sends the actual document to AWS.'
def test_cloudsearch_add_single_fields(self):
document = DocumentServiceConnection(endpoint='doc-demo-userdomain.us-east-1.cloudsearch.amazonaws.com') document.add('1234', {'id': '1234', 'title': 'Title 1', 'category': ['cat_a', 'cat_b', 'cat_c']}) document.commit() args = json.loads(HTTPretty.last_request.body.decode('utf-8'))[0] self.asser...
'Check that the reply from adding a single document is correctly parsed.'
def test_cloudsearch_add_single_result(self):
document = DocumentServiceConnection(endpoint='doc-demo-userdomain.us-east-1.cloudsearch.amazonaws.com') document.add('1234', {'id': '1234', 'title': 'Title 1', 'category': ['cat_a', 'cat_b', 'cat_c']}) doc = document.commit() self.assertEqual(doc.status, 'success') self.assertEqual(doc.adds, 1) ...
'Check that multiple documents are added correctly to AWS'
def test_cloudsearch_add_basics(self):
document = DocumentServiceConnection(endpoint='doc-demo-userdomain.us-east-1.cloudsearch.amazonaws.com') for (key, obj) in self.objs.items(): document.add(key, obj['fields']) document.commit() args = json.loads(HTTPretty.last_request.body.decode('utf-8')) for arg in args: self.assert...
'Check that the result from adding multiple documents is parsed correctly.'
def test_cloudsearch_add_results(self):
document = DocumentServiceConnection(endpoint='doc-demo-userdomain.us-east-1.cloudsearch.amazonaws.com') for (key, obj) in self.objs.items(): document.add(key, obj['fields']) doc = document.commit() self.assertEqual(doc.status, 'success') self.assertEqual(doc.adds, len(self.objs)) self.a...
'Test that the request for a single document deletion is done properly.'
def test_cloudsearch_delete(self):
document = DocumentServiceConnection(endpoint='doc-demo-userdomain.us-east-1.cloudsearch.amazonaws.com') document.delete('5') document.commit() args = json.loads(HTTPretty.last_request.body.decode('utf-8'))[0] self.assertEqual(args['type'], 'delete') self.assertEqual(args['id'], '5')
'Check that the result of a single document deletion is parsed properly.'
def test_cloudsearch_delete_results(self):
document = DocumentServiceConnection(endpoint='doc-demo-userdomain.us-east-1.cloudsearch.amazonaws.com') document.delete('5') doc = document.commit() self.assertEqual(doc.status, 'success') self.assertEqual(doc.adds, 0) self.assertEqual(doc.deletes, 1)
'Sets up a mock elb request. Returns: response, elb connection and LoadBalancer'
def _setup_mock(self):
mock_response = mock.Mock() mock_response.status = 200 elb = ELBConnection(aws_access_key_id='aws_access_key_id', aws_secret_access_key='aws_secret_access_key') elb.make_request = mock.Mock(return_value=mock_response) return (mock_response, elb, LoadBalancer(elb, 'test_elb'))
'Verifies an LbAttributes object.'
def _verify_attributes(self, attributes, attr_tests):
for (attr, result) in attr_tests: attr_result = attributes for sub_attr in attr.split('.'): attr_result = getattr(attr_result, sub_attr, None) self.assertEqual(attr_result, result)
'Tests getting the LbAttributes from the elb.connection.'
def test_get_all_lb_attributes(self):
(mock_response, elb, _) = self._setup_mock() for (response, attr_tests) in ATTRIBUTE_TESTS: mock_response.read.return_value = response attributes = elb.get_all_lb_attributes('test_elb') self.assertTrue(isinstance(attributes, LbAttributes)) self._verify_attributes(attributes, attr...
'Tests getting a single attribute from elb.connection.'
def test_get_lb_attribute(self):
(mock_response, elb, _) = self._setup_mock() tests = [('crossZoneLoadBalancing', True, ATTRIBUTE_GET_TRUE_CZL_RESPONSE), ('crossZoneLoadBalancing', False, ATTRIBUTE_GET_FALSE_CZL_RESPONSE)] for (attr, value, response) in tests: mock_response.read.return_value = response status = elb.get_lb_a...
'Tests setting the attributes from elb.connection.'
def test_modify_lb_attribute(self):
(mock_response, elb, _) = self._setup_mock() tests = [('crossZoneLoadBalancing', True, ATTRIBUTE_SET_CZL_TRUE_REQUEST), ('crossZoneLoadBalancing', False, ATTRIBUTE_SET_CZL_FALSE_REQUEST)] for (attr, value, args) in tests: mock_response.read.return_value = ATTRIBUTE_SET_RESPONSE result = elb....
'Tests the LbAttributes from the ELB object.'
def test_lb_get_attributes(self):
(mock_response, _, lb) = self._setup_mock() for (response, attr_tests) in ATTRIBUTE_TESTS: mock_response.read.return_value = response attributes = lb.get_attributes(force=True) self.assertTrue(isinstance(attributes, LbAttributes)) self._verify_attributes(attributes, attr_tests)
'Tests checking is_cross_zone_load_balancing.'
def test_lb_is_cross_zone_load_balancing(self):
(mock_response, _, lb) = self._setup_mock() tests = [(lb.is_cross_zone_load_balancing, [], True, ATTRIBUTE_GET_TRUE_CZL_RESPONSE), (lb.is_cross_zone_load_balancing, [], True, ATTRIBUTE_GET_FALSE_CZL_RESPONSE), (lb.is_cross_zone_load_balancing, [True], False, ATTRIBUTE_GET_FALSE_CZL_RESPONSE)] for (method, a...
'Tests enabling cross zone balancing from LoadBalancer.'
def test_lb_enable_cross_zone_load_balancing(self):
(mock_response, elb, lb) = self._setup_mock() mock_response.read.return_value = ATTRIBUTE_SET_RESPONSE self.assertTrue(lb.enable_cross_zone_load_balancing()) elb.make_request.assert_called_with(*ATTRIBUTE_SET_CZL_TRUE_REQUEST)
'Tests disabling cross zone balancing from LoadBalancer.'
def test_lb_disable_cross_zone_load_balancing(self):
(mock_response, elb, lb) = self._setup_mock() mock_response.read.return_value = ATTRIBUTE_SET_RESPONSE self.assertTrue(lb.disable_cross_zone_load_balancing()) elb.make_request.assert_called_with(*ATTRIBUTE_SET_CZL_FALSE_REQUEST)
'Tests checking connectionSettings attribute'
def test_lb_get_connection_settings(self):
(mock_response, elb, _) = self._setup_mock() attrs = [('idle_timeout', 30)] mock_response.read.return_value = ATTRIBUTE_GET_CS_RESPONSE attributes = elb.get_all_lb_attributes('test_elb') self.assertTrue(isinstance(attributes, LbAttributes)) for (attr, value) in attrs: self.assertEqual(ge...
'Generate a list of fake snapshots with names and dates.'
def _get_snapshots(self):
snaps = [] now = datetime.now() dates = [now, (now - timedelta(days=1)), (now - timedelta(days=2)), (now - timedelta(days=7)), (now - timedelta(days=14)), (datetime(now.year, now.month, 1) - timedelta(days=28)), (datetime(now.year, now.month, 1) - timedelta(days=58)), (datetime(now.year, now.month, 1) - tim...
'Test trimming snapshots with the default arguments, which should keep all monthly backups forever. The result of this test should be that nothing is deleted.'
def test_trim_defaults(self):
orig = {'get_all_snapshots': self.ec2.get_all_snapshots, 'delete_snapshot': self.ec2.delete_snapshot} snaps = self._get_snapshots() self.ec2.get_all_snapshots = MagicMock(return_value=snaps) self.ec2.delete_snapshot = MagicMock() self.ec2.trim_snapshots() self.assertEqual(True, self.ec2.get_all_...
'Test trimming monthly snapshots and ensure that older months get deleted properly. The result of this test should be that the two oldest snapshots get deleted.'
def test_trim_months(self):
orig = {'get_all_snapshots': self.ec2.get_all_snapshots, 'delete_snapshot': self.ec2.delete_snapshot} snaps = self._get_snapshots() self.ec2.get_all_snapshots = MagicMock(return_value=snaps) self.ec2.delete_snapshot = MagicMock() self.ec2.trim_snapshots(monthly_backups=1) self.assertEqual(True, ...
'Ensures that if the token is set to None, nothing is serialized.'
def test_none_token(self):
self.set_http_response(status_code=200) response = self.ec2.modify_reserved_instances(None, reserved_instance_ids=['2567o137-8a55-48d6-82fb-7258506bb497'], target_configurations=[ReservedInstancesConfiguration(availability_zone='us-west-2c', platform='EC2-VPC', instance_count=3, instance_type='c3.large')]) ...
'This test ensures that binary is base64 encoded when it is sent to the service.'
def test_binary_input(self):
self.set_http_response(status_code=200) data = '\x00\x01\x02\x03\x04\x05' self.service_connection.encrypt(key_id='foo', plaintext=data) body = json.loads(self.actual_request.body.decode('utf-8')) self.assertEqual(body['Plaintext'], 'AAECAwQF')
'This test ensures that only binary is used for blob type parameters.'
def test_non_binary_input_for_blobs_fails(self):
self.set_http_response(status_code=200) data = u'\xe9' with self.assertRaises(TypeError): self.service_connection.encrypt(key_id='foo', plaintext=data)
'This test ensures that the output is base64 decoded before it is returned to the user.'
def test_binary_ouput(self):
content = {'Plaintext': 'AAECAwQF'} self.set_http_response(status_code=200, body=json.dumps(content).encode('utf-8')) response = self.service_connection.decrypt('some arbitrary value') self.assertEqual(response['Plaintext'], '\x00\x01\x02\x03\x04\x05')
'Check connection re-use'
def test_multi_commands(self):
HTTPretty.register_uri(HTTPretty.POST, ('https://%s/' % self.region.endpoint), json.dumps({'test': 'secure'}), content_type='application/json') conn = self.region.connect(aws_access_key_id='access_key', aws_secret_access_key='secret') resp1 = conn.make_request('myCmd1', {'par1': 'foo', 'par2': 'baz'}, '/', ...
'Check connection re-use after close header is received'
def test_connection_close(self):
HTTPretty.register_uri(HTTPretty.POST, ('https://%s/' % self.region.endpoint), json.dumps({'test': 'secure'}), content_type='application/json', connection='close') conn = self.region.connect(aws_access_key_id='access_key', aws_secret_access_key='secret') def mock_put_conn(*args, **kwargs): raise Exc...
'Make sure only the AWS required params are required by boto'
def test_required_launch_params(self):
name = 'test_cache_cluster' self.set_http_response(status_code=200, body='{}') self.service_connection.create_cache_cluster(name) self.assert_request_parameters({'Action': 'CreateCacheCluster', 'CacheClusterId': name}, ignore_params_values=['Version', 'ContentType'])
'Test that wildcards are retained as literals See: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html#invalidation-specifying-objects-paths'
def test_wildcard_escape(self):
batch = cf.invalidation.InvalidationBatch() self.assertEqual(batch.escape('/*'), '/*') self.assertEqual(batch.escape('/foo*'), '/foo*') self.assertEqual(batch.escape('/foo/bar/*'), '/foo/bar/*') self.assertEqual(batch.escape('/nowildcard'), '/nowildcard') self.assertEqual(batch.escape('/other ...
'Test that paginating manually works properly'
def test_manual_pagination(self, num_invals=30, max_items=4):
self.assertGreater(num_invals, max_items) responses = self._get_mock_responses(num=num_invals, max_items=max_items) self.cf.make_request = mock.Mock(side_effect=responses) ir = self.cf.get_invalidation_requests('dist-id-here', max_items=max_items) all_invals = list(ir) self.assertEqual(len(all_i...
'Test that auto-pagination works properly'
def test_auto_pagination(self, num_invals=1024):
max_items = 100 self.assertGreaterEqual(num_invals, max_items) responses = self._get_mock_responses(num=num_invals, max_items=max_items) self.cf.make_request = mock.Mock(side_effect=responses) ir = self.cf.get_invalidation_requests('dist-id-here') self.assertEqual(len(ir._inval_cache), max_items...
'Test base64 encoding custom policy 1 from Amazon\'s documentation.'
def test_encode_custom_policy_1(self):
expected = 'eyAKICAgIlN0YXRlbWVudCI6IFt7IAogICAgICAiUmVzb3VyY2UiOiJodHRwOi8vZDYwNDcyMWZ4YWFxeTkuY2xvdWRmcm9udC5uZXQvdHJhaW5pbmcvKiIsIAogICAgICAiQ29uZGl0aW9uIjp7IAogICAgICAgICAiSXBBZGRyZXNzIjp7IkFXUzpTb3VyY2VJcCI6IjE0NS4xNjguMTQzLjAvMjQifSwgCiAgICAgICAgICJEYXRlTGVzc1RoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTI1ODIzNzIwMH0gICAg...
'Test base64 encoding custom policy 2 from Amazon\'s documentation.'
def test_encode_custom_policy_2(self):
expected = 'eyAKICAgIlN0YXRlbWVudCI6IFt7IAogICAgICAiUmVzb3VyY2UiOiJodHRwOi8vKiIsIAogICAgICAiQ29uZGl0aW9uIjp7IAogICAgICAgICAiSXBBZGRyZXNzIjp7IkFXUzpTb3VyY2VJcCI6IjIxNi45OC4zNS4xLzMyIn0sCiAgICAgICAgICJEYXRlR3JlYXRlclRoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTI0MTA3Mzc5MH0sCiAgICAgICAgICJEYXRlTGVzc1RoYW4iOnsiQVdTOkVwb2NoVGltZSI6...
'Test signing the canned policy from amazon\'s cloudfront documentation.'
def test_sign_canned_policy(self):
expected = 'Nql641NHEUkUaXQHZINK1FZ~SYeUSoBJMxjdgqrzIdzV2gyEXPDNv0pYdWJkflDKJ3xIu7lbwRpSkG98NBlgPi4ZJpRRnVX4kXAJK6tdNx6FucDB7OVqzcxkxHsGFd8VCG1BkC-Afh9~lOCMIYHIaiOB6~5jt9w2EOwi6sIIqrg_' sig = self.dist._sign_string(self.canned_policy, private_key_string=self.pk_str) encoded_sig = self.dist._url_base64_encod...
'Test signing the canned policy from amazon\'s cloudfront documentation with a file object.'
def test_sign_canned_policy_pk_file(self):
expected = 'Nql641NHEUkUaXQHZINK1FZ~SYeUSoBJMxjdgqrzIdzV2gyEXPDNv0pYdWJkflDKJ3xIu7lbwRpSkG98NBlgPi4ZJpRRnVX4kXAJK6tdNx6FucDB7OVqzcxkxHsGFd8VCG1BkC-Afh9~lOCMIYHIaiOB6~5jt9w2EOwi6sIIqrg_' pk_file = tempfile.TemporaryFile() pk_file.write(self.pk_str) pk_file.seek(0) sig = self.dist._sign_string(self.ca...
'Test signing the canned policy from amazon\'s cloudfront documentation with a file name.'
def test_sign_canned_policy_pk_file_name(self):
expected = 'Nql641NHEUkUaXQHZINK1FZ~SYeUSoBJMxjdgqrzIdzV2gyEXPDNv0pYdWJkflDKJ3xIu7lbwRpSkG98NBlgPi4ZJpRRnVX4kXAJK6tdNx6FucDB7OVqzcxkxHsGFd8VCG1BkC-Afh9~lOCMIYHIaiOB6~5jt9w2EOwi6sIIqrg_' pk_file = tempfile.NamedTemporaryFile() pk_file.write(self.pk_str) pk_file.flush() sig = self.dist._sign_string(se...
'Test signing the canned policy from amazon\'s cloudfront documentation with a file-like object (not a subclass of \'file\' type)'
def test_sign_canned_policy_pk_file_like(self):
expected = 'Nql641NHEUkUaXQHZINK1FZ~SYeUSoBJMxjdgqrzIdzV2gyEXPDNv0pYdWJkflDKJ3xIu7lbwRpSkG98NBlgPi4ZJpRRnVX4kXAJK6tdNx6FucDB7OVqzcxkxHsGFd8VCG1BkC-Afh9~lOCMIYHIaiOB6~5jt9w2EOwi6sIIqrg_' pk_file = StringIO() pk_file.write(self.pk_str) pk_file.seek(0) sig = self.dist._sign_string(self.canned_policy, p...
'Test signing the canned policy from amazon\'s cloudfront documentation.'
def test_sign_canned_policy_unicode(self):
expected = 'Nql641NHEUkUaXQHZINK1FZ~SYeUSoBJMxjdgqrzIdzV2gyEXPDNv0pYdWJkflDKJ3xIu7lbwRpSkG98NBlgPi4ZJpRRnVX4kXAJK6tdNx6FucDB7OVqzcxkxHsGFd8VCG1BkC-Afh9~lOCMIYHIaiOB6~5jt9w2EOwi6sIIqrg_' unicode_policy = six.text_type(self.canned_policy) sig = self.dist._sign_string(unicode_policy, private_key_string=self.pk...
'Test signing custom policy 1 from amazon\'s cloudfront documentation.'
def test_sign_custom_policy_1(self):
expected = 'cPFtRKvUfYNYmxek6ZNs6vgKEZP6G3Cb4cyVt~FjqbHOnMdxdT7eT6pYmhHYzuDsFH4Jpsctke2Ux6PCXcKxUcTIm8SO4b29~1QvhMl-CIojki3Hd3~Unxjw7Cpo1qRjtvrimW0DPZBZYHFZtiZXsaPt87yBP9GWnTQoaVysMxQ_' sig = self.dist._sign_string(self.custom_policy_1, private_key_string=self.pk_str) encoded_sig = self.dist._url_base64_enc...
'Test signing custom policy 2 from amazon\'s cloudfront documentation.'
def test_sign_custom_policy_2(self):
expected = 'rc~5Qbbm8EJXjUTQ6Cn0LAxR72g1DOPrTmdtfbWVVgQNw0q~KHUAmBa2Zv1Wjj8dDET4XSL~Myh44CLQdu4dOH~N9huH7QfPSR~O4tIOS1WWcP~2JmtVPoQyLlEc8YHRCuN3nVNZJ0m4EZcXXNAS-0x6Zco2SYx~hywTRxWR~5Q_' sig = self.dist._sign_string(self.custom_policy_2, private_key_string=self.pk_str) encoded_sig = self.dist._url_base64_enc...
'Test that a canned policy is generated correctly.'
def test_create_canned_policy(self):
url = 'http://1234567.cloudfront.com/test_resource.mp3?dog=true' expires = 999999 policy = self.dist._canned_policy(url, expires) policy = json.loads(policy) self.assertEqual(1, len(policy.keys())) statements = policy['Statement'] self.assertEqual(1, len(statements)) statement = statemen...
'Test that a custom policy can be created with an expire time and an arbitrary URL.'
def test_custom_policy_expires_and_policy_url(self):
url = 'http://1234567.cloudfront.com/*' expires = 999999 policy = self.dist._custom_policy(url, expires=expires) policy = json.loads(policy) self.assertEqual(1, len(policy.keys())) statements = policy['Statement'] self.assertEqual(1, len(statements)) statement = statements[0] resourc...
'Test that a custom policy can be created with a valid-after time and an arbitrary URL.'
def test_custom_policy_valid_after(self):
url = 'http://1234567.cloudfront.com/*' valid_after = 999999 policy = self.dist._custom_policy(url, valid_after=valid_after) policy = json.loads(policy) self.assertEqual(1, len(policy.keys())) statements = policy['Statement'] self.assertEqual(1, len(statements)) statement = statements[0]...
'Test that a custom policy can be created with an IP address and an arbitrary URL.'
def test_custom_policy_ip_address(self):
url = 'http://1234567.cloudfront.com/*' ip_range = '192.168.0.1' policy = self.dist._custom_policy(url, ip_address=ip_range) policy = json.loads(policy) self.assertEqual(1, len(policy.keys())) statements = policy['Statement'] self.assertEqual(1, len(statements)) statement = statements[0]...
'Test that a custom policy can be created with an IP address and an arbitrary URL.'
def test_custom_policy_ip_range(self):
url = 'http://1234567.cloudfront.com/*' ip_range = '192.168.0.0/24' policy = self.dist._custom_policy(url, ip_address=ip_range) policy = json.loads(policy) self.assertEqual(1, len(policy.keys())) statements = policy['Statement'] self.assertEqual(1, len(statements)) statement = statements...
'Test that a custom policy can be created with an IP address and an arbitrary URL.'
def test_custom_policy_all(self):
url = 'http://1234567.cloudfront.com/test.txt' expires = 999999 valid_after = 111111 ip_range = '192.168.0.0/24' policy = self.dist._custom_policy(url, expires=expires, valid_after=valid_after, ip_address=ip_range) policy = json.loads(policy) self.assertEqual(1, len(policy.keys())) state...
'Test the correct params are generated for a canned policy.'
def test_params_canned_policy(self):
url = 'http://d604721fxaaqy9.cloudfront.net/horizon.jpg?large=yes&license=yes' expire_time = 1258237200 expected_sig = 'Nql641NHEUkUaXQHZINK1FZ~SYeUSoBJMxjdgqrzIdzV2gyEXPDNv0pYdWJkflDKJ3xIu7lbwRpSkG98NBlgPi4ZJpRRnVX4kXAJK6tdNx6FucDB7OVqzcxkxHsGFd8VCG1BkC-Afh9~lOCMIYHIaiOB6~5jt9w2EOwi6sIIqrg_' signed_url...
'Generate signed url from the Example Canned Policy in Amazon\'s documentation.'
def test_canned_policy(self):
url = 'http://d604721fxaaqy9.cloudfront.net/horizon.jpg?large=yes&license=yes' expire_time = 1258237200 expected_url = 'http://d604721fxaaqy9.cloudfront.net/horizon.jpg?large=yes&license=yes&Expires=1258237200&Signature=Nql641NHEUkUaXQHZINK1FZ~SYeUSoBJMxjdgqrzIdzV2gyEXPDNv0pYdWJkflDKJ3xIu7lbwRpSkG98NBlgPi4Z...
'Test InstanceGroup init raises ValueError when market==spot and bidprice is not specified.'
def test_bidprice_missing_spot(self):
with self.assertRaisesRegexp(ValueError, 'bidprice must be specified'): InstanceGroup(1, 'MASTER', 'm1.small', 'SPOT', 'master')
'Test InstanceGroup init accepts a missing bidprice arg, when market is ON_DEMAND.'
def test_bidprice_missing_ondemand(self):
instance_group = InstanceGroup(1, 'MASTER', 'm1.small', 'ON_DEMAND', 'master')
'Test InstanceGroup init works with bidprice type = Decimal.'
def test_bidprice_Decimal(self):
instance_group = InstanceGroup(1, 'MASTER', 'm1.small', 'SPOT', 'master', bidprice=Decimal(1.1)) self.assertEquals('1.10', instance_group.bidprice[:4])
'Test InstanceGroup init works with bidprice type = float.'
def test_bidprice_float(self):
instance_group = InstanceGroup(1, 'MASTER', 'm1.small', 'SPOT', 'master', bidprice=1.1) self.assertEquals('1.1', instance_group.bidprice)
'Test InstanceGroup init works with bidprice type = string.'
def test_bidprice_string(self):
instance_group = InstanceGroup(1, 'MASTER', 'm1.small', 'SPOT', 'master', bidprice='1.1') self.assertEquals('1.1', instance_group.bidprice)
'Check returned metadata is parsed correctly'
def test_cloudsearch_results_meta(self):
search = SearchConnection(endpoint=HOSTNAME) results = search.search(q='Test') self.assertEqual(results.rank, '-text_relevance') self.assertEqual(results.match_expression, 'Test')
'Check num_pages_needed is calculated correctly'
def test_cloudsearch_results_info(self):
search = SearchConnection(endpoint=HOSTNAME) results = search.search(q='Test') self.assertEqual(results.num_pages_needed, 3.0)
'Check that information objects are passed back through the API correctly.'
def test_cloudsearch_results_matched(self):
search = SearchConnection(endpoint=HOSTNAME) query = search.build_query(q='Test') results = search(query) self.assertEqual(results.search_service, search) self.assertEqual(results.query, query)
'Check that documents are parsed properly from AWS'
def test_cloudsearch_results_hits(self):
search = SearchConnection(endpoint=HOSTNAME) results = search.search(q='Test') hits = list(map((lambda x: x['id']), results.docs)) self.assertEqual(hits, ['12341', '12342', '12343', '12344', '12345', '12346', '12347'])
'Check the results iterator'
def test_cloudsearch_results_iterator(self):
search = SearchConnection(endpoint=HOSTNAME) results = search.search(q='Test') results_correct = iter(['12341', '12342', '12343', '12344', '12345', '12346', '12347']) for x in results: self.assertEqual(x['id'], next(results_correct))
'Check the documents length matches the iterator details'
def test_cloudsearch_results_internal_consistancy(self):
search = SearchConnection(endpoint=HOSTNAME) results = search.search(q='Test') self.assertEqual(len(results), len(results.docs))
'Check next page query is correct'
def test_cloudsearch_search_nextpage(self):
search = SearchConnection(endpoint=HOSTNAME) query1 = search.build_query(q='Test') query2 = search.build_query(q='Test') results = search(query2) self.assertEqual(results.next_page().query.start, (query1.start + query1.size)) self.assertEqual(query1.q, query2.q)
'Check that endpoints & ARNs are correctly returned from AWS'
def test_cloudsearch_connect_result_endpoints(self):
self.set_http_response(status_code=200) api_response = self.service_connection.create_domain('demo') domain = Domain(self, api_response) self.assertEqual(domain.doc_service_arn, 'arn:aws:cs:us-east-1:1234567890:doc/demo') self.assertEqual(domain.doc_service_endpoint, 'doc-demo-userdomain.us-east-1.c...
'Check that domain statuses are correctly returned from AWS'
def test_cloudsearch_connect_result_statuses(self):
self.set_http_response(status_code=200) api_response = self.service_connection.create_domain('demo') domain = Domain(self, api_response) self.assertEqual(domain.created, True) self.assertEqual(domain.processing, False) self.assertEqual(domain.requires_index_documents, False) self.assertEqual...
'Check that the domain information is correctly returned from AWS'
def test_cloudsearch_connect_result_details(self):
self.set_http_response(status_code=200) api_response = self.service_connection.create_domain('demo') domain = Domain(self, api_response) self.assertEqual(domain.id, '1234567890/demo') self.assertEqual(domain.name, 'demo')
'Check that the correct arguments are sent to AWS when creating a cloudsearch connection.'
def test_cloudsearch_deletion(self):
self.set_http_response(status_code=200) api_response = self.service_connection.delete_domain('demo') self.assert_request_parameters({'Action': 'DeleteDomain', 'DomainName': 'demo', 'Version': '2011-02-01'})
'Check that the correct arguments are sent to AWS when indexing a domain.'
def test_cloudsearch_index_documents(self):
self.set_http_response(status_code=200) api_response = self.service_connection.index_documents('demo') self.assert_request_parameters({'Action': 'IndexDocuments', 'DomainName': 'demo', 'Version': '2011-02-01'})
'Check that the AWS response is being parsed correctly when indexing a domain.'
def test_cloudsearch_index_documents_resp(self):
self.set_http_response(status_code=200) api_response = self.service_connection.index_documents('demo') self.assertEqual(api_response, ['average_score', 'brand_id', 'colors', 'context', 'context_owner', 'created_at', 'creator_id', 'description', 'file_size', 'format', 'has_logo', 'has_messaging', 'height', '...
'Check that a simple add document actually sends an add document request to AWS.'
def test_cloudsearch_add_basics(self):
document = DocumentServiceConnection(endpoint='doc-demo-userdomain.us-east-1.cloudsearch.amazonaws.com') document.add('1234', 10, {'id': '1234', 'title': 'Title 1', 'category': ['cat_a', 'cat_b', 'cat_c']}) document.commit() args = json.loads(HTTPretty.last_request.body.decode('utf-8'))[0] self.a...
'Check that a simple add document sends correct document metadata to AWS.'
def test_cloudsearch_add_single_basic(self):
document = DocumentServiceConnection(endpoint='doc-demo-userdomain.us-east-1.cloudsearch.amazonaws.com') document.add('1234', 10, {'id': '1234', 'title': 'Title 1', 'category': ['cat_a', 'cat_b', 'cat_c']}) document.commit() args = json.loads(HTTPretty.last_request.body.decode('utf-8'))[0] self.a...
'Check that a simple add document sends the actual document to AWS.'
def test_cloudsearch_add_single_fields(self):
document = DocumentServiceConnection(endpoint='doc-demo-userdomain.us-east-1.cloudsearch.amazonaws.com') document.add('1234', 10, {'id': '1234', 'title': 'Title 1', 'category': ['cat_a', 'cat_b', 'cat_c']}) document.commit() args = json.loads(HTTPretty.last_request.body.decode('utf-8'))[0] self.a...
'Check that the reply from adding a single document is correctly parsed.'
def test_cloudsearch_add_single_result(self):
document = DocumentServiceConnection(endpoint='doc-demo-userdomain.us-east-1.cloudsearch.amazonaws.com') document.add('1234', 10, {'id': '1234', 'title': 'Title 1', 'category': ['cat_a', 'cat_b', 'cat_c']}) doc = document.commit() self.assertEqual(doc.status, 'success') self.assertEqual(doc.adds,...
'Check that multiple documents are added correctly to AWS'
def test_cloudsearch_add_basics(self):
document = DocumentServiceConnection(endpoint='doc-demo-userdomain.us-east-1.cloudsearch.amazonaws.com') for (key, obj) in self.objs.items(): document.add(key, obj['version'], obj['fields']) document.commit() args = json.loads(HTTPretty.last_request.body.decode('utf-8')) for arg in args: ...
'Check that the result from adding multiple documents is parsed correctly.'
def test_cloudsearch_add_results(self):
document = DocumentServiceConnection(endpoint='doc-demo-userdomain.us-east-1.cloudsearch.amazonaws.com') for (key, obj) in self.objs.items(): document.add(key, obj['version'], obj['fields']) doc = document.commit() self.assertEqual(doc.status, 'success') self.assertEqual(doc.adds, len(self.o...
'Test that the request for a single document deletion is done properly.'
def test_cloudsearch_delete(self):
document = DocumentServiceConnection(endpoint='doc-demo-userdomain.us-east-1.cloudsearch.amazonaws.com') document.delete('5', '10') document.commit() args = json.loads(HTTPretty.last_request.body.decode('utf-8'))[0] self.assertEqual(args['version'], '10') self.assertEqual(args['type'], 'delete')...
'Check that the result of a single document deletion is parsed properly.'
def test_cloudsearch_delete_results(self):
document = DocumentServiceConnection(endpoint='doc-demo-userdomain.us-east-1.cloudsearch.amazonaws.com') document.delete('5', '10') doc = document.commit() self.assertEqual(doc.status, 'success') self.assertEqual(doc.adds, 0) self.assertEqual(doc.deletes, 1)
'Insure that password.__eq__ hashes test value before compare.'
def clstest(self, cls):
password = cls('foo') self.assertNotEquals(password, 'foo') password.set('foo') hashed = str(password) self.assertEquals(password, 'foo') self.assertEquals(password.str, hashed) password = cls(hashed) self.assertNotEquals(password.str, 'foo') self.assertEquals(password, 'foo') se...
'Simple List decoding that had caused some errors'
def test_decoding_full_doc(self):
dynamizer = types.Dynamizer() doc = '{"__type__":{"S":"Story"},"company_tickers":{"SS":["NASDAQ-TSLA","NYSE-F","NYSE-GM"]},"modified_at":{"N":"1452525162"},"created_at":{"N":"1452525162"},"version":{"N":"1"},"categories":{"SS":["AUTOMTVE","LTRTR","MANUFCTU","PN","PRHYPE","TAXE","TJ","TL"]},"provider_categories"...
'It seems the technique used to store and reload the object must result in an equivalent object, or subsequent pickles may fail. This tests a double-pickle to elicit that error.'
def test_pickle_deserialized_version(self):
result = self.create_hit_result() new_result = pickle.loads(pickle.dumps(result)) pickle.dumps(new_result)
'update(arg)'
def update(self, arg):
RMD160Update(self.ctx, arg, len(arg)) self.dig = None
'digest()'
def digest(self):
if self.dig: return self.dig ctx = self.ctx.copy() self.dig = RMD160Final(self.ctx) self.ctx = ctx return self.dig
'hexdigest()'
def hexdigest(self):
dig = self.digest() hex_digest = '' for d in dig: if is_python2: hex_digest += ('%02x' % ord(d)) else: hex_digest += ('%02x' % d) return hex_digest
'copy()'
def copy(self):
import copy return copy.deepcopy(self)
'Normalize and hash a message ID for the metadata index'
def _encode_msg_id(self, msg_id):
if ('<' in msg_id): new_msg_id = ('<%s>' % msg_id.split('<')[1].split('>')[0]) if (len(new_msg_id) > 2): msg_id = new_msg_id return b64c(sha1b64(msg_id.strip()))
'Create the generator for message flattening. outfp is the output file-like object for writing the message to. It must have a write() method. Optional mangle_from_ is a flag that, when True (the default), escapes From_ lines in the body of the message by putting a `>\' in front of them. Optional maxheaderlen specifies...
def __init__(self, outfp, mangle_from_=True, maxheaderlen=78, linesep=None):
self._fp = outfp self._mangle_from_ = mangle_from_ self._maxheaderlen = maxheaderlen self._NL = (linesep or NL)
'Print the message object tree rooted at msg to the output file specified when the Generator instance was created. unixfrom is a flag that forces the printing of a Unix From_ delimiter before the first object in the message tree. If the original message has no From_ delimiter, a `standard\' one is crafted. By default...
def flatten(self, msg, unixfrom=False, linesep=None):
if linesep: self._NL = linesep if unixfrom: ufrom = msg.get_unixfrom() if (not ufrom): ufrom = ('From nobody ' + time.ctime(time.time())) print >>self._fp, (ufrom + self._NL), self._write(msg)
'Clone this generator with the exact same options.'
def clone(self, fp):
return self.__class__(fp, self._mangle_from_, self._maxheaderlen)
'Like Generator.__init__() except that an additional optional argument is allowed. Walks through all subparts of a message. If the subpart is of main type `text\', then it prints the decoded payload of the subpart. Otherwise, fmt is a format string that is used instead of the message payload. fmt is expanded with the...
def __init__(self, outfp, mangle_from_=True, maxheaderlen=78, fmt=None, linesep=None):
Generator.__init__(self, outfp, mangle_from_, maxheaderlen, linesep) if (fmt is None): self._fmt = _FMT else: self._fmt = fmt
'Extract a date, sanity checking against the Received: headers.'
def _extract_date_ts(self, session, msg_mid, msg_id, msg, default):
return (safe_message_ts(msg, default=default, msg_mid=msg_mid, msg_id=msg_id, session=session) or int((time.time() - 1)))
'This method will calculate/update the thread-ID and parent-ID of a given message. Mailpile will group all messages in a thread together as "replies" to the root message; but it will also keep track of what is the immediate parent of any given mail. Note that the "root" message may not be the actual root of the thread;...
def set_conversation_ids(self, msg_mid, msg, subject_threading=True):
parent_mid = None parent_idx_pos = None msg_thr_mid = None in_reply_to = safe_decode_hdr(msg, 'in-reply-to') refs = safe_decode_hdr(msg, 'references').replace(',', ' ').strip().split() if in_reply_to: if ('<' in in_reply_to): irt_ref = ('<%s>' % in_reply_to.split('<')[1].s...
'Extracts IDs and such from <...> in list-headers.'
def _list_header_keywords(self, hdr, val_lower, body_info):
words = [] for word in val_lower.replace(',', ' ').split(): if (not word): continue elif (word[:5] == '<http'): continue elif ((len(word) > 65) and ('+' in word) and ('@' in word)): continue elif (word[(-1):] == '>'): if (word[:8...
'Wraps method with a screenshot on exception aspect.'
@classmethod def wrap_method(mcs, method):
def test_call_wrapper_method(*args, **kw): "The wrapper method\n\n Notes:\n The method name has to start with *test*, otherwise the\n ...
'Note that we are about to perform an action.'
def mark(self, action=None, percent=None):
if (not action): try: action = self.times[(-1)][1] except IndexError: action = 'mark' self.progress(action) self.times.append((time.time(), action))
'This sequence of actions is complete.'
def reset_marks(self, mark=True, quiet=False, details=False):
if (self.times and mark): self.mark() elapsed = self.report_marks(quiet=quiet, details=details) self.times[:] = [] return elapsed