def test_sends_bundle_when_patch_error(self): """Testing DownloadPatchErrorBundleView sends a patch error bundle when a PatchError is raised by the renderer. """ review_request = self.create_review_request(publish=True, create_repository=True) diffset = self.create_diffset(review_request=review_request) self.create_diffcommit(diffset=diffset) filediff_id = diffset.files.all()[0].pk patch_error = PatchError(filename='filename', error_output='error_output', orig_file=b'orig_file', new_file=b'new_file', diff=b'diff', rejects=b'rejects') self.spy_on(DiffRenderer.render_to_response, op=kgb.SpyOpRaise(patch_error)) response = self.client.get( local_site_reverse('patch-error-bundle', kwargs={ 'review_request_id': review_request.pk, 'revision': diffset.revision, 'filediff_id': filediff_id, })) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/zip')
def test_post_with_unknown_cert(self): """Testing the POST repositories/ API with Unknown Certificate error""" class Certificate(object): failures = ['failures'] fingerprint = 'fingerprint' hostname = 'example.com' issuer = 'issuer' valid_from = 'valid_from' valid_until = 'valid_until' cert = Certificate() self.spy_on(TestTool.check_repository, owner=TestTool, op=kgb.SpyOpRaise(UnverifiedCertificateError(cert))) rsp = self._post_repository(expected_status=403) self.assertEqual(rsp['stat'], 'fail') self.assertEqual(rsp['err']['code'], UNVERIFIED_HOST_CERT.code) self.assertIn('certificate', rsp) self.assertEqual(rsp['certificate']['failures'], cert.failures) self.assertEqual(rsp['certificate']['fingerprint'], cert.fingerprint) self.assertEqual(rsp['certificate']['hostname'], cert.hostname) self.assertEqual(rsp['certificate']['issuer'], cert.issuer) self.assertEqual(rsp['certificate']['valid']['from'], cert.valid_from) self.assertEqual(rsp['certificate']['valid']['until'], cert.valid_until)
def test_authenticate_with_invalid_credentials(self): """Testing ActiveDirectoryBackend.authenticate with invalid credentials """ self.spy_on(TestLDAPObject.simple_bind_s, owner=TestLDAPObject, op=kgb.SpyOpRaise(ldap.INVALID_CREDENTIALS())) self.spy_on(TestLDAPObject.search_s, owner=TestLDAPObject, op=kgb.SpyOpReturn([ ('CN=Test User,OU=MyOrg,DC=example,DC=com', { 'givenName': [b'Test'], 'sn': [b'User'], 'mail': [b'*****@*****.**'], }), ])) user = self.backend.authenticate(request=None, username='******', password='******') self.assertIsNone(user) self.assertSpyCalledWith(TestLDAPObject.simple_bind_s, '*****@*****.**', 'test-pass') self.assertSpyNotCalled(TestLDAPObject.search_s)
def test_authenticate_with_exception(self): """Testing ActiveDirectoryBackend.authenticate with unexpected exception """ self.spy_on(TestLDAPObject.simple_bind_s, owner=TestLDAPObject, op=kgb.SpyOpRaise(Exception('Kaboom!'))) self.spy_on(TestLDAPObject.search_s, owner=TestLDAPObject, op=kgb.SpyOpReturn([ ('CN=Test User,OU=MyOrg,DC=example,DC=com', { 'givenName': [b'Test'], 'sn': [b'User'], 'mail': [b'*****@*****.**'], }), ])) user = self.backend.authenticate(request=None, username='******', password='******') self.assertIsNone(user) self.assertSpyCalledWith(TestLDAPObject.simple_bind_s, '*****@*****.**', 'test-pass') self.assertSpyNotCalled(TestLDAPObject.search_s)
def test_authenticate_with_invalid_credentials(self): """Testing LDAPBackend.authenticate with invalid credentials""" self.spy_on(TestLDAPObject.bind_s, owner=TestLDAPObject, op=kgb.SpyOpRaise(ldap.INVALID_CREDENTIALS())) self.spy_on(TestLDAPObject.search_s, owner=TestLDAPObject, op=kgb.SpyOpReturn([ ('CN=Doc Dwarf,OU=MyOrg,DC=example,DC=COM', {}), ])) user = self.backend.authenticate(request=None, username='******', password='******') self.assertIsNone(user) self.assertSpyCalledWith( TestLDAPObject.bind_s, 'CN=Doc Dwarf,OU=MyOrg,DC=example,DC=COM', 'mypass') self.assertSpyCalledWith( TestLDAPObject.search_s, 'CN=admin,DC=example,DC=com', ldap.SCOPE_SUBTREE, '(uid=doc)')
def test_authenticate_with_server_down(self): """Testing ActiveDirectoryBackend.authenticate with Server Down error """ self.spy_on(TestLDAPObject.simple_bind_s, owner=TestLDAPObject, op=kgb.SpyOpRaise(ldap.SERVER_DOWN())) self.spy_on(TestLDAPObject.search_s, owner=TestLDAPObject, op=kgb.SpyOpReturn([ ('CN=Test User,OU=MyOrg,DC=example,DC=com', { 'givenName': ['Test'], 'sn': ['User'], 'mail': ['*****@*****.**'], }), ])) user = self.backend.authenticate(request=None, username='******', password='******') self.assertIsNone(user) self.assertSpyCalledWith(TestLDAPObject.simple_bind_s, '*****@*****.**', 'test-pass') self.assertSpyNotCalled(TestLDAPObject.search_s)
def test_get_ldap_connections_from_dns_with_error(self): """Testing ActiveDirectoryBackend.get_ldap_connections with AD_FIND_DC_FROM_DNS=True with error """ self.spy_on(dns.resolver.query, op=kgb.SpyOpRaise(Exception('Kaboom!'))) self.assertEqual( list(self.backend.get_ldap_connections('example.com')), [])
def test_get_ldap_connections_from_dns_with_not_found(self): """Testing ActiveDirectoryBackend.get_ldap_connections with AD_FIND_DC_FROM_DNS=True with domain not found """ self.spy_on(dns.resolver.query, op=kgb.SpyOpRaise(dns.resolver.NXDOMAIN())) self.assertEqual( list(self.backend.get_ldap_connections('example.com')), [])
def test_find_domain_controllers_from_dns_with_not_found(self): """Testing ActiveDirectoryBackend.find_domain_controllers_from_dns with domain not found """ self.spy_on(dns.resolver.query, op=kgb.SpyOpRaise(dns.resolver.NXDOMAIN())) self.assertEqual(self.backend.find_domain_controllers_from_dns(), []) self.assertSpyCalledWith(dns.resolver.query, '_ldap._tcp.example.com', rdtype='SRV')
def test_find_domain_controllers_from_dns_with_error(self): """Testing ActiveDirectoryBackend.find_domain_controllers_from_dns with error """ self.spy_on(dns.resolver.query, op=kgb.SpyOpRaise(Exception('Kaboom!'))) self.assertEqual(self.backend.find_domain_controllers_from_dns(), []) self.assertSpyCalledWith(dns.resolver.query, '_ldap._tcp.example.com', rdtype='SRV')
def test_post_with_missing_user_key(self): """Testing the POST repositories/ API with Missing User Key error""" self.spy_on( TestTool.check_repository, owner=TestTool, op=kgb.SpyOpRaise(AuthenticationError(allowed_types=['publickey'], user_key=None))) rsp = self._post_repository(expected_status=403) self.assertEqual(rsp['stat'], 'fail') self.assertEqual(rsp['err']['code'], MISSING_USER_KEY.code)
def test_post_with_authentication_error(self): """Testing the POST repositories/ API with Authentication Error""" self.spy_on( TestTool.check_repository, owner=TestTool, op=kgb.SpyOpRaise(AuthenticationError())) rsp = self._post_repository(expected_status=403) self.assertEqual(rsp['stat'], 'fail') self.assertEqual(rsp['err']['code'], REPO_AUTHENTICATION_ERROR.code) self.assertIn('reason', rsp)
def test_can_process_signals_without_siteconfig(self): """Testing SignalProcessor.can_process_signals without stored SiteConfiguration """ self.spy_on(SiteConfiguration.objects.get_current, op=kgb.SpyOpRaise(SiteConfiguration.DoesNotExist)) signal_processor = self._create_signal_processor() self.assertFalse(signal_processor.can_process_signals) # Make sure it works once one has been created. SiteConfiguration.objects.get_current.unspy() self.assertTrue(signal_processor.can_process_signals)
def test_post_with_unknown_host_key(self): """Testing the POST repositories/ API with Unknown Host Key error""" self.spy_on(TestTool.check_repository, owner=TestTool, op=kgb.SpyOpRaise(UnknownHostKeyError('example.com', key1))) rsp = self._post_repository(expected_status=403) self.assertEqual(rsp['stat'], 'fail') self.assertEqual(rsp['err']['code'], UNVERIFIED_HOST_KEY.code) self.assertIn('hostname', rsp) self.assertIn('key', rsp) self.assertEqual(rsp['hostname'], 'example.com') self.assertEqual(rsp['key'], key1.get_base64())
def _spy_on_smtp(self, data_result=None): """Spy on the SMTP connection process and fake a result. Args: data_result (tuple): The value to fake from the final data request. This will be what's stored and processed by our e-mail backend. """ # We want to simulate as much of the SMTP flow as possible, since # we're trying to ensure that the final response is caught in our # subclass. To do this, we need to stub out much of the communication. # # We'll simulate connection management (connect() and quit()), stub # out responses for the mail sending process (ehlo_or_helo_if_needed(), # rcpt(), mail(), and data()), and raise exceptions if we somehow get # to any actual socket communication code (putcmd() and getreply()). # # We're explicitly spying on the base class, so we don't turn off our # subclass's overridden behavior. self.spy_on(SMTP.connect, owner=SMTP, op=kgb.SpyOpReturn((220, b''))) self.spy_on(SMTP.quit, owner=SMTP, op=kgb.SpyOpReturn((221, b''))) self.spy_on(SMTP.rset, owner=SMTP, call_original=False) self.spy_on(SMTP.putcmd, owner=SMTP, op=kgb.SpyOpRaise(Exception('not reached'))) self.spy_on(SMTP.getreply, owner=SMTP, op=kgb.SpyOpRaise(Exception('not reached'))) self.spy_on(SMTP.ehlo_or_helo_if_needed, owner=SMTP, call_original=False) self.spy_on(SMTP.rcpt, owner=SMTP, op=kgb.SpyOpReturn((250, b''))) self.spy_on(SMTP.mail, owner=SMTP, op=kgb.SpyOpReturn((250, b''))) self.spy_on(SMTP.data, owner=SMTP, op=kgb.SpyOpReturn(data_result))
def test_validate_with_failure(self): """Testing SearchBackend.validate with failure""" self.spy_on(SimpleSearchBackend.search, owner=SimpleSearchBackend, func_name='search', op=kgb.SpyOpRaise(Exception('Things went broken.'))) message = ( 'Performing a test query failed. Make sure your configuration is ' 'correct. The error we received from the search backend was: ' 'Things went broken.') with self.assertRaisesMessage(ValidationError, message): self.backend.validate(configuration={ 'setting1': 'new value', 'setting3': [4, 5, 6], })
def test_get_file_http_with_http_error_404(self): """Testing SCMClient.get_file_http with HTTPError 404""" self.spy_on(urlopen, op=kgb.SpyOpRaise( HTTPError(url='https://example.com', code=404, msg=None, hdrs=None, fp=None))) client = SCMClient(path='/path/to/repo') with self.assertRaises(FileNotFoundError) as ctx: client.get_file_http('https://example.com', path='/path/to/file', revision='abc123') e = ctx.exception self.assertEqual(e.path, '/path/to/file') self.assertEqual(e.revision, 'abc123')
def test_handle_save_with_error(self): """Testing SignalProcessor.handle_save with error""" exception = Exception('kaboom!') self.spy_on(BaseSignalProcessor.handle_save, owner=BaseSignalProcessor, op=kgb.SpyOpRaise(exception)) self.spy_on(logger.error) signal_processor = self._create_signal_processor() # This should not raise an exception. # # We'll use some garbage values. signal_processor.handle_save(sender=None, instance=None) self.assertSpyCalled(BaseSignalProcessor.handle_save) self.assertSpyCalledWith( logger.error, ('Error updating the search index. Check to make sure the ' 'search backend is running and configured correctly, and then ' 'rebuild the search index. Error: %s'), exception)
def test_get_file_http_with_http_error(self): """Testing SCMClient.get_file_http with HTTPError""" self.spy_on(urlopen, op=kgb.SpyOpRaise( HTTPError(url='https://example.com', code=500, msg='Kablam', hdrs=None, fp=None))) client = SCMClient(path='/path/to/repo') message = ( 'HTTP error code 500 when fetching file from https://example.com: ' 'HTTP Error 500: Kablam') with self.assertRaisesMessage(SCMError, message) as ctx: client.get_file_http('https://example.com', path='/path/to/file', revision='abc123') self.assertNotIsInstance(ctx.exception, FileNotFoundError)
def test_authenticate_with_exception(self): """Testing LDAPBackend.authenticate with unexpected exception""" self.spy_on(TestLDAPObject.bind_s, owner=TestLDAPObject, op=kgb.SpyOpRaise(Exception('oh no!'))) self.spy_on(TestLDAPObject.search_s, owner=TestLDAPObject, op=kgb.SpyOpReturn([ ('CN=Doc Dwarf,OU=MyOrg,DC=example,DC=COM', {}), ])) user = self.backend.authenticate(request=None, username='******', password='******') self.assertIsNone(user) self.assertSpyCalledWith(TestLDAPObject.bind_s, 'CN=Doc Dwarf,OU=MyOrg,DC=example,DC=COM', 'mypass') self.assertSpyCalledWith(TestLDAPObject.search_s, 'CN=admin,DC=example,DC=com', ldap.SCOPE_SUBTREE, '(uid=doc)')
def test_save_with_send_test_mail_without_request_and_error(self): """Testing EMailSettingsForm.save with send_test_mail=True without HTTP request and error sending e-mail """ self.spy_on(logger.exception) self.spy_on(mail.send_mail, op=kgb.SpyOpRaise(Exception('Kaboom!'))) siteconfig = SiteConfiguration.objects.get_current() form = EMailSettingsForm(siteconfig, data={ 'mail_default_from': '*****@*****.**', 'send_test_mail': True, }) self.assertTrue(form.is_valid()) form.save() self.assertEqual(len(mail.outbox), 0) self.assertSpyCalledWith(logger.exception, 'Failed to send test e-mail to %s: %s', '*****@*****.**', 'Kaboom!')
def test_save_with_send_test_mail_with_request_and_error(self): """Testing EMailSettingsForm.save with send_test_mail=True with HTTP request and error sending e-mail """ self.spy_on(logger.exception) self.spy_on(mail.send_mail, op=kgb.SpyOpRaise(Exception('Kaboom!'))) user = self.create_user(username='******', email='*****@*****.**') request = self.create_http_request(user=user) siteconfig = SiteConfiguration.objects.get_current() form = EMailSettingsForm(siteconfig, request=request, data={ 'mail_default_from': '*****@*****.**', 'send_test_mail': True, }) self.assertTrue(form.is_valid()) form.save() self.assertEqual(len(mail.outbox), 0) self.assertSpyCalledWith(logger.exception, 'Failed to send test e-mail to %s: %s', '*****@*****.**', 'Kaboom!') msgs = list(messages.get_messages(request)) self.assertEqual(len(msgs), 1) msg = msgs[0] self.assertEqual(msg.level, messages.ERROR) self.assertEqual( msg.message, 'Failed to send the test e-mail: "Kaboom!". Check ' 'the server logs for additional details.')