def test_delete_retain(self): # first run, with retain policy swiftclient.Connection.put_container(mox.Regex(self.container_pattern), { 'X-Container-Write': None, 'X-Container-Read': None }).AndReturn(None) # This should not be called swiftclient.Connection.delete_container( mox.Regex(self.container_pattern)).AndReturn(None) self.m.ReplayAll() t = self.load_template() properties = t['Resources']['SwiftContainer']['Properties'] properties['DeletionPolicy'] = 'Retain' stack = self.parse_stack(t) resource = self.create_resource(t, stack, 'SwiftContainer') # if delete_container is called, mox verify will succeed resource.delete() try: self.m.VerifyAll() except mox.ExpectedMethodCallsError: return raise Exception('delete_container was called despite Retain policy')
def test_attributes(self): swiftclient.Connection.put_container( mox.Regex(self.container_pattern), { 'X-Container-Write': 'test_tenant:test_username', 'X-Container-Read': 'test_tenant:test_username' }).AndReturn(None) swiftclient.Connection.get_auth().MultipleTimes().AndReturn( ('http://localhost:8080/v_2', None)) swiftclient.Connection.delete_container( mox.Regex(self.container_pattern)).AndReturn(None) self.m.ReplayAll() t = self.load_template() stack = self.parse_stack(t) resource = self.create_resource(t, stack, 'S3Bucket') ref_id = resource.FnGetRefId() self.assertTrue(re.match(self.container_pattern, ref_id)) self.assertEqual('localhost', resource.FnGetAtt('DomainName')) url = 'http://localhost:8080/v_2/%s' % ref_id self.assertEqual(url, resource.FnGetAtt('WebsiteURL')) try: resource.FnGetAtt('Foo') raise Exception('Expected InvalidTemplateAttribute') except s3.exception.InvalidTemplateAttribute: pass self.assertEqual(s3.S3Bucket.UPDATE_REPLACE, resource.handle_update({})) resource.delete() self.m.VerifyAll()
def test_get_entity_zero_props(self): request = webapp2.Request.blank( '/datastore/edit/%s?next=http://next/' % self.entity5.key()) response = webapp2.Response() handler = datastore_viewer.DatastoreEditRequestHandler(request, response) admin_request_handler.AdminRequestHandler(handler).get( str(self.entity5.key())) handler.render( 'datastore_edit.html', {'fields': [('boolprop', 'bool', mox.Regex('^<select class="bool"(.|\n)*$')), ('floatprop', 'float', mox.Regex('^<input class="float".*value="0\.0".*$')), ('intprop', 'int', mox.Regex('^<input class="int".*value="0".*$')), ('stringprop', 'string', mox.Regex('^<input class="string".*value="".*$'))], 'key': str(self.entity5.key()), 'key_id': 127, 'key_name': None, 'kind': 'Kind1', 'namespace': '', 'next': 'http://next/', 'parent_key': None, 'parent_key_string': None}) self.mox.ReplayAll() handler.get(str(self.entity5.key())) self.mox.VerifyAll()
def test_get_entity_string(self): request = webapp2.Request.blank( '/datastore/edit/%s?next=http://next/' % self.entity1.key()) response = webapp2.Response() handler = datastore_viewer.DatastoreEditRequestHandler(request, response) admin_request_handler.AdminRequestHandler(handler).get( str(self.entity1.key())) handler.render( 'datastore_edit.html', {'fields': [('dateprop', 'overflowdatetime', mox.Regex('^<input class="overflowdatetime".*' 'value="1152921504606846976".*$')), ('intprop', 'int', mox.Regex('^<input class="int".*value="1".*$')), ('listprop', 'list', mox.Regex(r'\[7L?, 8L?, 9L?\]'))], 'key': str(self.entity1.key()), 'key_id': 123, 'key_name': None, 'kind': 'Kind1', 'namespace': '', 'next': 'http://next/', 'parent_key': None, 'parent_key_string': None}) self.mox.ReplayAll() handler.get(str(self.entity1.key())) self.mox.VerifyAll()
def test_get_no_entity_key_string(self): request = webapp2.Request.blank( '/datastore/edit?kind=Kind1&next=http://next/') response = webapp2.Response() handler = datastore_viewer.DatastoreEditRequestHandler(request, response) handler.render( 'datastore_edit.html', {'fields': [('intprop', 'int', mox.Regex('^<input class="int".*value="".*$')), ('listprop', 'list', ''), ('stringprop', 'string', mox.Regex('^<input class="string".*$'))], 'key': None, 'key_id': None, 'key_name': None, 'kind': 'Kind1', 'namespace': '', 'next': 'http://next/', 'parent_key': None, 'parent_key_string': None}) self.mox.ReplayAll() handler.get() self.mox.VerifyAll()
def test_delete_retain(self): # first run, with retain policy swiftclient.Connection.put_container( mox.Regex(self.container_pattern), {'X-Container-Write': 'test_tenant:test_username', 'X-Container-Read': 'test_tenant:test_username'}).AndReturn(None) # This should not be called swiftclient.Connection.delete_container( mox.Regex(self.container_pattern)).AndReturn(None) self.m.ReplayAll() t = template_format.parse(swift_template) bucket = t['Resources']['S3Bucket'] bucket['DeletionPolicy'] = 'Retain' stack = parse_stack(t) resource = self.create_resource(t, stack, 'S3Bucket') # if delete_container is called, mox verify will succeed resource.delete() self.assertEqual(resource.DELETE_COMPLETE, resource.state) try: self.m.VerifyAll() except mox.ExpectedMethodCallsError: return raise Exception('delete_container was called despite Retain policy')
def test_attributes(self): headers = { "content-length": "0", "x-container-object-count": "82", "x-container-write": "None", "accept-ranges": "bytes", "x-trans-id": "tx08ea48ef2fa24e6da3d2f5c188fd938b", "date": "Wed, 23 Jan 2013 22:48:05 GMT", "x-timestamp": "1358980499.84298", "x-container-read": ".r:*", "x-container-bytes-used": "17680980", "content-type": "text/plain; charset=utf-8" } swiftclient.Connection.put_container(mox.Regex(self.container_pattern), { 'X-Container-Write': None, 'X-Container-Read': None }).AndReturn(None) swiftclient.Connection.get_auth().MultipleTimes().AndReturn( ('http://localhost:8080/v_2', None)) swiftclient.Connection.head_container( mox.IgnoreArg()).MultipleTimes().AndReturn(headers) swiftclient.Connection.delete_container( mox.Regex(self.container_pattern)).AndReturn(None) self.m.ReplayAll() t = self.load_template() stack = self.parse_stack(t) resource = self.create_resource(t, stack, 'SwiftContainer') ref_id = resource.FnGetRefId() self.assertTrue(re.match(self.container_pattern, ref_id)) self.assertEqual('localhost', resource.FnGetAtt('DomainName')) url = 'http://localhost:8080/v_2/%s' % ref_id self.assertEqual(url, resource.FnGetAtt('WebsiteURL')) self.assertEqual('82', resource.FnGetAtt('ObjectCount')) self.assertEqual('17680980', resource.FnGetAtt('BytesUsed')) self.assertEqual(headers, resource.FnGetAtt('HeadContainer')) try: resource.FnGetAtt('Foo') raise Exception('Expected InvalidTemplateAttribute') except swift.exception.InvalidTemplateAttribute: pass self.assertEqual(swift.SwiftContainer.UPDATE_REPLACE, resource.handle_update({})) resource.delete() self.m.VerifyAll()
def testLuksAsOwnerBarcodeTooLong(self): self.mox.StubOutWithMock(self.c, 'VerifyXsrfToken') self.c.VerifyXsrfToken('RetrieveSecret') mock_user = self.mox.CreateMockAnything() mock_user.email = '*****@*****.**' mock_user.__getitem__('email').AndReturn(mock_user.email) self.mox.StubOutWithMock(models, 'GetCurrentUser') models.GetCurrentUser().AndReturn(mock_user) models.GetCurrentUser().AndReturn(mock_user) self.mox.StubOutWithMock(self.c, 'VerifyPermissions') self.c.VerifyPermissions( permissions.RETRIEVE, user=mock_user).AndRaise( models.AccessDeniedError('user is not an admin')) self.c.VerifyPermissions(permissions.RETRIEVE_OWN, user=mock_user) volume_uuid = 'foovolumeuuid' passphrase = '676ffb71232f71ee0ddf643876907f17' * 20 self.c.request = {'json': '0'} self.c.response = self.mox.CreateMockAnything() self.c.response.out = self.mox.CreateMockAnything() self.c.response.out.write( mox.And(mox.Not(mox.Regex(r'<img class="qr_code" ')), mox.Regex(passphrase))) mock_entity = self.mox.CreateMockAnything() mock_entity.passphrase = passphrase mock_entity.owner = '*****@*****.**' self.mox.StubOutWithMock(models.LuksVolume, 'get_by_key_name') models.LuksVolume.get_by_key_name(volume_uuid).AndReturn(mock_entity) mock_user.user = self.mox.CreateMockAnything() self.mox.StubOutWithMock(mock_user.user, 'nickname') mock_user.user.nickname().AndReturn('mock_user_foo') self.mox.StubOutWithMock(models.LuksAccessLog, 'Log') models.LuksAccessLog.Log(message='GET', entity=mock_entity, request=self.c.request) self.mox.StubOutWithMock(self.c, 'SendRetrievalEmail') self.c.SendRetrievalEmail(mock_entity, mock_user).AndReturn(None) self.mox.ReplayAll() self.c.RetrieveSecret(volume_uuid) self.mox.VerifyAll()
def test(self): headers, entities, total_entities = ( datastore_viewer.DatastoreRequestHandler._get_entity_template_data( request_uri='http://next/', kind='Kind1', namespace='', order='intprop', start=1)) self.assertEqual( [{'name': 'intprop'}, {'name': 'listprop'}, {'name': 'stringprop'}], headers) self.assertEqual( [{'attributes': [{'name': u'intprop', 'short_value': '3', 'value': '3'}, {'name': u'listprop', 'short_value': mox.Regex(r'\[1L?, 2L?, 3L?\]'), 'value': mox.Regex(r'\[1L?, 2L?, 3L?\]')}, {'name': u'stringprop', 'short_value': '', 'value': ''}], 'edit_uri': '/datastore/edit/{0}?next=http%3A//next/'.format( self.entity3.key()), 'key': datastore_types.Key.from_path(u'Kind1', 125, _app=u'myapp'), 'key_id': 125, 'key_name': None, 'shortened_key': 'agVteWFw...', 'write_ops': 10}, {'attributes': [{'name': u'intprop', 'short_value': '4', 'value': '4'}, {'name': u'listprop', 'short_value': mox.Regex(r'\[10L?, 11L?\]'), 'value': mox.Regex(r'\[10L?, 11L?\]')}, {'name': u'stringprop', 'short_value': u'value4', 'value': u'value4'}], 'edit_uri': '/datastore/edit/{0}?next=http%3A//next/'.format( self.entity4.key()), 'key': datastore_types.Key.from_path(u'Kind1', 126, _app=u'myapp'), 'key_id': 126, 'key_name': None, 'shortened_key': 'agVteWFw...', 'write_ops': 10}], entities) self.assertEqual(3, total_entities)
def _mock_exists(self, mock_number, fn): # mock os.path.exists() self.mox.StubOutWithMock(os.path, 'exists') mox_ = self.mox def exists(path): # Always reset return values (0=GitJenkinsSync(), 1=sync(), 2=exists()) for method in mox_._mock_objects[ mock_number]._expected_calls_queue[0]._methods: method._return_value = None # print "exists(%s)" % path if not re.match("^/path.*$", path): # print " not /path..." orig_exists = filter(lambda x: x[2] == "exists", mox_.stubs.cache)[0][1] # print " " + str(orig_exists) ret = orig_exists(path) # print " ret=" + str(ret) return ret else: # print " is /path..." return fn(path) os.path.exists( mox.Regex("^.*$")).MultipleTimes().WithSideEffects(exists)
def _test_create_consumer(self, fanout): self.mock_connection = self.mox.CreateMock(self.orig_connection) self.mock_session = self.mox.CreateMock(self.orig_session) self.mock_receiver = self.mox.CreateMock(self.orig_receiver) self.mock_connection.opened().AndReturn(False) self.mock_connection.open() self.mock_connection.session().AndReturn(self.mock_session) if fanout: # The link name includes a UUID, so match it with a regex. expected_address = mox.Regex( r'^impl_qpid_test_fanout ; ' '{"node": {"x-declare": {"auto-delete": true, "durable": ' 'false, "type": "fanout"}, "type": "topic"}, "create": ' '"always", "link": {"x-declare": {"auto-delete": true, ' '"exclusive": true, "durable": false}, "durable": true, ' '"name": "impl_qpid_test_fanout_.*"}}$') else: expected_address = ( 'nova/impl_qpid_test ; {"node": {"x-declare": ' '{"auto-delete": true, "durable": true}, "type": "topic"}, ' '"create": "always", "link": {"x-declare": {"auto-delete": ' 'true, "exclusive": false, "durable": false}, "durable": ' 'true, "name": "impl_qpid_test"}}') self.mock_session.receiver(expected_address).AndReturn( self.mock_receiver) self.mock_receiver.capacity = 1 self.mock_connection.close() self.mox.ReplayAll() connection = impl_qpid.create_connection(FLAGS) connection.create_consumer("impl_qpid_test", lambda *_x, **_y: None, fanout) connection.close()
def test_authenticated_read(self): swiftclient.Connection.put_container( mox.Regex(self.container_pattern), {'X-Container-Write': 'test_tenant:test_username', 'X-Container-Read': 'test_tenant'}).AndReturn(None) swiftclient.Connection.delete_container( mox.Regex(self.container_pattern)).AndReturn(None) self.m.ReplayAll() t = template_format.parse(swift_template) properties = t['Resources']['S3Bucket']['Properties'] properties['AccessControl'] = 'AuthenticatedRead' stack = parse_stack(t) resource = self.create_resource(t, stack, 'S3Bucket') resource.delete() self.m.VerifyAll()
def test_public_read_write(self): swiftclient.Connection.put_container( mox.Regex(self.container_pattern), {'X-Container-Write': '.r:*', 'X-Container-Read': '.r:*'}).AndReturn(None) swiftclient.Connection.delete_container( mox.Regex(self.container_pattern)).AndReturn(None) self.m.ReplayAll() t = self.load_template() properties = t['Resources']['S3Bucket']['Properties'] properties['AccessControl'] = 'PublicReadWrite' stack = self.parse_stack(t) resource = self.create_resource(t, stack, 'S3Bucket') resource.delete() self.m.VerifyAll()
def _test_call_mock_common(self): self.stubs.Set(time, 'sleep', self.my_time_sleep) self.mock_connection = self.mox.CreateMock(self.orig_connection) self.mock_session = self.mox.CreateMock(self.orig_session) self.mock_sender = self.mox.CreateMock(self.orig_sender) self.mock_receiver = self.mox.CreateMock(self.orig_receiver) self.mock_connection.opened().AndReturn(False) self.mock_connection.open() self.mock_connection.session().AndReturn(self.mock_session) rcv_addr = mox.Regex( r'^.*/.* ; {"node": {"x-declare": {"auto-delete":' ' true, "durable": true, "type": "direct"}, "type": ' '"topic"}, "create": "always", "link": {"x-declare": ' #'{"auto-delete": true, "exclusive": true, "durable": ' '{"exclusive": true, "auto-delete": false, "durable": ' 'false}, "durable": true, "name": ".*"}}') self.mock_session.receiver(rcv_addr).AndReturn(self.mock_receiver) self.mock_receiver.capacity = 1 self.mock_connection.opened().AndReturn(False) self.mock_connection.open() self.mock_connection.session().AndReturn(self.mock_session) send_addr = ( 'openstack/impl_qpid_test ; {"node": {"x-declare": ' '{"auto-delete": true, "durable": false}, "type": "topic"}, ' '"create": "always"}') self.mock_session.sender(send_addr).AndReturn(self.mock_sender) self.mock_sender.send(mox.IgnoreArg()) self.mock_session.close() self.mock_connection.session().AndReturn(self.mock_session)
def test_public_read(self): swiftclient.Connection.put_container(mox.Regex(self.container_pattern), { 'X-Container-Write': None, 'X-Container-Read': '.r:*' }).AndReturn(None) swiftclient.Connection.delete_container( mox.Regex(self.container_pattern)).AndReturn(None) self.m.ReplayAll() t = template_format.parse(swift_template) properties = t['Resources']['SwiftContainer']['Properties'] properties['X-Container-Read'] = '.r:*' stack = parse_stack(t) rsrc = self.create_resource(t, stack, 'SwiftContainer') rsrc.delete() self.m.VerifyAll()
def test_delete_exception(self): swiftclient.Connection.put_container( mox.Regex(self.container_pattern), {'X-Container-Write': 'test_tenant:test_username', 'X-Container-Read': 'test_tenant:test_username'}).AndReturn(None) swiftclient.Connection.delete_container( mox.Regex(self.container_pattern)).AndRaise( swiftclient.ClientException('Test delete failure')) self.m.ReplayAll() t = template_format.parse(swift_template) stack = parse_stack(t) resource = self.create_resource(t, stack, 'S3Bucket') resource.delete() self.m.VerifyAll()
def test_website(self): swiftclient.Connection.put_container( mox.Regex(self.container_pattern), {'X-Container-Meta-Web-Error': 'error.html', 'X-Container-Meta-Web-Index': 'index.html', 'X-Container-Write': 'test_tenant:test_username', 'X-Container-Read': '.r:*'}).AndReturn(None) swiftclient.Connection.delete_container( mox.Regex(self.container_pattern)).AndReturn(None) self.m.ReplayAll() t = template_format.parse(swift_template) stack = parse_stack(t) resource = self.create_resource(t, stack, 'S3BucketWebsite') resource.delete() self.m.VerifyAll()
def test_delete_exception(self): swiftclient.Connection.put_container(mox.Regex(self.container_pattern), { 'X-Container-Write': None, 'X-Container-Read': None }).AndReturn(None) swiftclient.Connection.delete_container( mox.Regex(self.container_pattern)).AndRaise( swiftclient.ClientException('Test delete failure')) self.m.ReplayAll() t = self.load_template() stack = self.parse_stack(t) resource = self.create_resource(t, stack, 'SwiftContainer') resource.delete() self.m.VerifyAll()
def test_website(self): swiftclient.Connection.put_container( mox.Regex(self.container_pattern), { 'X-Container-Meta-Web-Error': 'error.html', 'X-Container-Meta-Web-Index': 'index.html', 'X-Container-Write': None, 'X-Container-Read': '.r:*' }).AndReturn(None) swiftclient.Connection.delete_container( mox.Regex(self.container_pattern)).AndReturn(None) self.m.ReplayAll() t = self.load_template() stack = self.parse_stack(t) resource = self.create_resource(t, stack, 'SwiftContainerWebsite') resource.delete() self.m.VerifyAll()
def test_got_auth_code(self): comparator = mox.Regex('.*/oauth/access_token\?.*&code=my_auth_code.*') self.expect_urlfetch(comparator, 'foo=bar&access_token=my_access_token') self.mox.ReplayAll() resp = facebook.application.get_response( '/facebook/got_auth_code?code=my_auth_code&state=http://my/redirect_to', environ={'HTTP_HOST': 'HOST'}) self.assertEqual(302, resp.status_int) self.assertEqual('http://my/redirect_to?access_token=my_access_token', resp.headers['Location'])
def test_deallocate_ip_address(self): ipam = self.mox.CreateMock(melange_ipam_lib.QuantumMelangeIPAMLib) ipam.get_tenant_id_by_net_id('context', 'net_id', {'uuid': 1}, 'project_id').AndRaise(Exception()) self.net_man.ipam = ipam self.mox.StubOutWithMock(quantum_manager.LOG, 'exception') quantum_manager.LOG.exception(mox.Regex(r'ipam deallocation failed')) self.mox.ReplayAll() self.net_man.deallocate_ip_address('context', 'net_id', 'project_id', {'uuid': 1}, 'instance_id')
def testMain(self): """Verify that running main method runs expected functons. Expected: LoadAndMergeTables, WriteTable. """ self.mox.StubOutWithMock(mps, 'LoadAndMergeTables') self.mox.StubOutWithMock(mps, 'WriteTable') mps.LoadAndMergeTables(mox.IgnoreArg()).AndReturn('csv_table') mps.WriteTable(mox.Regex(r'csv_table'), 'any-out') self.mox.ReplayAll() mps.main(['--out=any-out', 'any-package']) self.mox.VerifyAll()
def test_sync(self): # prepare mock for GitBranches and mock out all methods mocked_gitbranches = self.mox.CreateMock(syncgit.GitBranches) mocked_gitbranches.get_branches().AndReturn( set(["dev/ACME-987-branch", "dev/ACME-123-branch"])) # mock constructor, return instance mock self.mox.StubOutWithMock(syncgit, 'GitBranches') (syncgit.GitBranches( "/path/to/repo", "^refs/remotes/origin/(int/.*|dev/ACME-[0-9]{1,}-.*)$", 42).AndReturn(mocked_gitbranches)) # prepare mock for Jenkins and mock out all methods mocked_jenkins = self.mox.CreateMock(syncgit.Jenkins) mocked_jenkins.get_currently_configured_branches().AndReturn( ["dev/ACME-987-branch", "dev/ACME-000-branch"]) mocked_jenkins.remove_job( mox.Regex("^dev/ACME-000-branch$")).AndReturn(None) mocked_jenkins.create_job( mox.Regex("^dev/ACME-123-branch$")).AndReturn(None) # mock constructor, return instance mock self.mox.StubOutWithMock(syncgit, 'Jenkins') (syncgit.Jenkins("hostname", "/tmp/cli.jar", "/tmp/ssh-key", "TEMPLATE Build X", "Build X %s").AndReturn(mocked_jenkins)) self.mox.ReplayAll() sync = syncgit.GitJenkinsSync( "hostname", "/tmp/cli.jar", "/tmp/ssh-key", "TEMPLATE Build X", "Build X %s", "/path/to/repo", "^refs/remotes/origin/(int/.*|dev/ACME-[0-9]{1,}-.*)$", 42) sync.sync() self.mox.VerifyAll()
def test_deallocate_port_logs_error(self): quantum = self.mox.CreateMock( quantum_connection.QuantumClientConnection) quantum.get_port_by_attachment('q_tenant_id', 'net_id', 'interface_id').AndRaise(Exception) self.net_man.q_conn = quantum self.mox.StubOutWithMock(quantum_manager.LOG, 'exception') quantum_manager.LOG.exception(mox.Regex(r'port deallocation failed')) self.mox.ReplayAll() self.net_man.deallocate_port('interface_id', 'net_id', 'q_tenant_id', 'instance_id')
def expectSubscribe(self, phone=None, pledgePageSlug=None): if phone is None: phone = '212-234-5432' if pledgePageSlug is None: pledgePageSlug = '28e9-Team-Shant-is-Shant' self.mailing_list_subscriber \ .Subscribe(email=self.pledge['email'], first_name=u'Pik\u00E1', last_name='Chu', amount_cents=4200, ip_addr=None, # Not sure why this is None in unittests time=mox.IsA(datetime.datetime), phone=phone, source='pledge', nonce=mox.Regex('.*'),)
def testSendSendmail(self): """Tests sending via sendmail.""" mail_service = mail_stub.MailServiceStub(enable_sendmail=True) message = self.CreateRequest(sender='*****@*****.**', to=['*****@*****.**'], cc=['*****@*****.**', '*****@*****.**'], bcc=['blind <*****@*****.**>'], subject='a subject', body='a body', html='<html>') send = self.mox.CreateMockAnything() receive = self.mox.CreateMockAnything() child = self.mox.CreateMock(subprocess.Popen) child.stdin = send child.stdout = receive self.popen( 'sendmail \'[email protected]\' \'[email protected]\' ' '\'[email protected]\' \'blind <*****@*****.**>\'', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE).AndReturn(child) send.write( mox.Regex(b'^(?s)(?!From ).*' + re.escape(b'MIME-Version: 1.0\n' b'To: [email protected]\n' b'Cc: [email protected], [email protected]\n' b'Bcc: blind <*****@*****.**>\n' b'From: [email protected]\n' b'Reply-To: \n' b'Subject: a subject\n\n'))) send.close() child.poll().AndReturn(None) receive.read(100) child.poll().AndReturn(None) receive.read(100) child.poll().AndReturn(0) receive.close() self.mox.ReplayAll() mail_service._Send(message.ToProto(), None, self.DoNothing, self.smtp, self.popen) self.mox.VerifyAll()
def test_send(self): self.mox.StubOutWithMock(xmpp_request_handler.XmppRequestHandler, 'dispatcher') handler = xmpp_request_handler.XmppRequestHandler() handler.dispatcher = self.mox.CreateMock(dispatcher.Dispatcher) handler.dispatcher.add_request( method='POST', relative_url='url', headers=[('Content-Type', mox.Regex('multipart/form-data; boundary=".*?"'))], body=mox.IsA(str), source_ip='0.1.0.10', fake_login=True) data = xmpp_request_handler._FormData() self.mox.ReplayAll() handler._send('url', data) self.mox.VerifyAll()
def testSendSMTPDisableTls(self): """Tests the ability to disable TLS for SMTP. Note: testSendFull tests when the server announces TLS and we use it, testSendSMTP checks when server does not announce TLS. """ mail_service = mail_stub.MailServiceStub('smtp-host', 25, 'smtp-user', 'smtp-password', True, allow_tls=False) message = self.CreateRequest(sender='*****@*****.**', to=['*****@*****.**'], cc=['*****@*****.**'], bcc=['*****@*****.**'], subject='a subject', body='a body', html='<html>') smtp_object = self.mox.CreateMock(smtplib.SMTP) self.smtp().AndReturn(smtp_object) smtp_object.connect('smtp-host', 25) smtp_object.ehlo_or_helo_if_needed() smtp_object.login('smtp-user', 'smtp-password') smtp_object.sendmail( '*****@*****.**', ['*****@*****.**', '*****@*****.**', '*****@*****.**'], mox.Regex('^(?s)(?!From ).*' + re.escape('MIME-Version: 1.0\n' 'To: [email protected]\n' 'Cc: [email protected]\n' 'Bcc: [email protected]\n' 'From: [email protected]\n' 'Reply-To: \n' 'Subject: a subject\n\n'))) smtp_object.quit() self.mox.ReplayAll() mail_service._Send(message.ToProto(), None, self.DoNothing, self.smtp, self.popen) self.mox.VerifyAll()
def testSendSMTP(self): """Tests that sendmail is not used when SMTP is configured.""" mail_service = mail_stub.MailServiceStub('smtp-host', 25, 'smtp-user', 'smtp-password', True, allow_tls=True) message = self.CreateRequest(sender='*****@*****.**', to=['*****@*****.**'], cc=['*****@*****.**'], bcc=['*****@*****.**'], subject='a subject', body='a body', html='<html>') smtp_object = self.mox.CreateMock(smtplib.SMTP) self.smtp().AndReturn(smtp_object) smtp_object.connect('smtp-host', 25) smtp_object.ehlo_or_helo_if_needed() smtp_object.has_extn('STARTTLS').AndReturn(False) smtp_object.login('smtp-user', 'smtp-password') smtp_object.sendmail( '*****@*****.**', ['*****@*****.**', '*****@*****.**', '*****@*****.**'], mox.Regex('^(?s)(?!From ).*' + re.escape('MIME-Version: 1.0\n' 'To: [email protected]\n' 'Cc: [email protected]\n' 'Bcc: [email protected]\n' 'From: [email protected]\n' 'Reply-To: \n' 'Subject: a subject\n\n'))) smtp_object.quit() self.mox.ReplayAll() mail_service._Send(message.ToProto(), None, self.DoNothing, self.smtp, self.popen) self.mox.VerifyAll()
def test_fanout_reconnect(self): expected_address = mox.Regex( r'^impl_qpid_test_fanout ; ' '{"node": {"x-declare": {"auto-delete": true, "durable": ' 'false, "type": "fanout"}, "type": "topic"}, "create": ' '"always", "link": {"x-declare": {"auto-delete": true, ' '"exclusive": true, "durable": false}, "durable": true, ' '"name": "impl_qpid_test_fanout_.*"}}$') self.mock_connection = self.mox.CreateMock(self.orig_connection) self.mock_session = self.mox.CreateMock(self.orig_session) self.mock_receiver = self.mox.CreateMock(self.orig_receiver) # First connection and create_consumer self.mock_connection.opened().AndReturn(False) self.mock_connection.open() self.mock_connection.session().AndReturn(self.mock_session) self.mock_session.receiver(expected_address).AndReturn( self.mock_receiver) self.mock_receiver.capacity = 1 # Now call reconnect self.mock_connection.opened().AndReturn(False) self.mock_connection.open() self.mock_connection.session().AndReturn(self.mock_session) # FIXME(wilsonmh): connect is currently part of __init__(), # causing a reconnect to declare two receivers :( self.mock_session.receiver(expected_address).AndReturn( self.mock_receiver) self.mock_session.receiver(expected_address).AndReturn( self.mock_receiver) self.mock_receiver.capacity = 1 self.mock_connection.close() self.mox.ReplayAll() connection = impl_qpid.create_connection(self.FLAGS) connection.create_consumer("impl_qpid_test", None, True) connection.reconnect() connection.close()