def test_authtkt_timeout_defined(self, set_authorization_policy, set_authentication_policy): """Ensure that main() uses the setting when authtkt.timeout is defined in settings.""" with mock.patch.dict( self.app_settings, {'authtkt.timeout': '10', 'authtkt.secret': 'hunter2', 'authtkt.secure': 'true'}): server.main({}, **self.app_settings) policy = set_authentication_policy.mock_calls[0][1][0] self.assertTrue(isinstance(policy, authentication.AuthTktAuthenticationPolicy)) self.assertEqual(policy.callback, server.groupfinder) self.assertEqual(policy.cookie.hashalg, 'sha512') self.assertEqual(policy.cookie.max_age, 10) self.assertEqual(policy.cookie.secure, True) self.assertEqual(policy.cookie.secret, 'hunter2') self.assertEqual(policy.cookie.timeout, 10) set_authentication_policy.assert_called_once_with(policy) # Ensure that the ACLAuthorizationPolicy was used policy = set_authorization_policy.mock_calls[0][1][0] self.assertTrue(isinstance(policy, authorization.ACLAuthorizationPolicy)) set_authorization_policy.assert_called_once_with(policy)
def test_sets_up_home_page_cache(self, _generate_home_page_stats): """Ensure that the home page cache is configured.""" _generate_home_page_stats.return_value = 5 # Let's pull invalidate off of the mock so that main() will decorate it again as a cache. del _generate_home_page_stats.invalidate self.assertFalse(hasattr(_generate_home_page_stats, 'invalidate')) server.main({}, testing='guest', session=self.db) # main() should have given it a cache, which would give it an invalidate attribute. self.assertTrue( hasattr(generic._generate_home_page_stats, 'invalidate')) self.assertEqual(generic._generate_home_page_stats(), 5) # Changing the return value of the mock should not affect the return value since it is # cached. _generate_home_page_stats.return_value = 7 self.assertEqual(generic._generate_home_page_stats(), 5) # If we invalidate the cache, we should see the new return value. generic._generate_home_page_stats.invalidate() self.assertEqual(generic._generate_home_page_stats(), 7)
def test_admin_unauthed(self): """Test that an unauthed user cannot see the admin endpoint""" anonymous_settings = copy.copy(self.app_settings) anonymous_settings.update({ 'authtkt.secret': 'whatever', 'authtkt.secure': True, }) app = TestApp(main({}, session=self.db, **anonymous_settings)) res = app.get('/admin/', status=403) self.assertIn('<h1>403 <small>Forbidden</small></h1>', res) self.assertIn( '<p class="lead">Access was denied to this resource.</p>', res)
def setUp(self): """Set up Bodhi for testing.""" # Ensure "cached" objects are cleared before each test. models.Release._all_releases = None models.Release._tag_cache = None if engine is None: self.engine = _configure_test_db() else: self.engine = engine self.connection = self.engine.connect() models.Base.metadata.create_all(bind=self.connection) self.transaction = self.connection.begin() Session.remove() Session.configure(bind=self.engine, autoflush=False, expire_on_commit=False) self.Session = Session self.db = Session() self.db.begin_nested() if self._populate_db: populate(self.db) bugs.set_bugtracker() buildsys.setup_buildsystem({'buildsystem': 'dev'}) def request_db(request=None): """ Replace the db session function with one that doesn't close the session. This allows tests to make assertions about the database. Without it, all the changes would be rolled back to when the nested transaction is started. """ def cleanup(request): if request.exception is not None: Session().rollback() else: Session().commit() request.add_finished_callback(cleanup) return Session() self._request_sesh = mock.patch('bodhi.server.get_db_session_for_request', request_db) self._request_sesh.start() # Create the test WSGI app one time. We should avoid creating too many # of these since Pyramid holds global references to the objects it creates # and this results in a substantial memory leak. Long term we should figure # out how to make Pyramid forget about these. global _app if _app is None: _app = TestApp(main({}, testing=u'guest', **self.app_settings)) self.app = _app
def test_new_stack_form_unauthed(self): """ Assert we get a 403 if the user is not logged in """ anonymous_settings = copy.copy(self.app_settings) anonymous_settings.update({ 'authtkt.secret': 'whatever', 'authtkt.secure': True, }) app = TestApp(main({}, session=self.db, **anonymous_settings)) res = app.get('/stacks/new', status=403) self.assertIn('<h1>403 <small>Forbidden</small></h1>', res) self.assertIn('<p class="lead">Access was denied to this resource.</p>', res)
def test_authtkt_timeout_undefined(self, set_authorization_policy, set_authentication_policy): """Ensure that main() uses a default if authtkt.timeout is undefined in settings.""" with mock.patch.dict(self.app_settings, { 'authtkt.secret': 'hunter2', 'authtkt.secure': 'true' }): server.main({}, session=self.db, **self.app_settings) policy = set_authentication_policy.mock_calls[0][1][0] assert isinstance(policy, authentication.AuthTktAuthenticationPolicy) assert policy.callback == server.groupfinder assert policy.cookie.hashalg == 'sha512' assert policy.cookie.max_age == 86400 assert policy.cookie.secure == True assert policy.cookie.secret == 'hunter2' assert policy.cookie.timeout == 86400 set_authentication_policy.assert_called_once_with(policy) # Ensure that the ACLAuthorizationPolicy was used policy = set_authorization_policy.mock_calls[0][1][0] assert isinstance(policy, authorization.ACLAuthorizationPolicy) set_authorization_policy.assert_called_once_with(policy)
def test_override_new_not_loggedin(self): """ Test a non logged in User is forbidden from viewing the new overrides page """ anonymous_settings = copy.copy(self.app_settings) anonymous_settings.update({ 'authtkt.secret': 'whatever', 'authtkt.secure': True, }) app = webtest.TestApp(main({}, session=self.db, **anonymous_settings)) resp = app.get('/overrides/new', status=403, headers={'Accept': 'text/html'}) self.assertIn('<h1>403 <small>Forbidden</small></h1>', resp) self.assertIn('<p class="lead">Access was denied to this resource.</p>', resp)
def _setup_method(self): """Set up Bodhi for testing.""" # Ensure "cached" objects are cleared before each test. models.Release.clear_all_releases_cache() models.Release._tag_cache = None if engine is None: self.engine = _configure_test_db() else: self.engine = engine self.connection = self.engine.connect() models.Base.metadata.create_all(bind=self.connection) self.transaction = self.connection.begin() Session.remove() Session.configure(bind=self.engine, autoflush=False, expire_on_commit=False) self.Session = Session self.db = Session() self.db.begin_nested() if self._populate_db: populate(self.db) bugs.set_bugtracker() buildsys.setup_buildsystem({'buildsystem': 'dev'}) self._request_sesh = mock.patch( 'bodhi.server.webapp._complete_database_session', webapp._rollback_or_commit) self._request_sesh.start() # Create the test WSGI app one time. We should avoid creating too many # of these since Pyramid holds global references to the objects it creates # and this results in a substantial memory leak. Long term we should figure # out how to make Pyramid forget about these. global _app if _app is None: # We don't want to call Session.remove() during the unit tests, because that will # trigger the restart_savepoint() callback defined above which will remove the data # added by populate(). with mock.patch('bodhi.server.Session.remove'): _app = TestApp(main({}, testing='guest', **self.app_settings)) self.app = _app # ensure a clean state of the dev build system buildsys.DevBuildsys.clear()
def test_override_view_not_loggedin(self): """ Test a non logged in User can't see the edit overrides form """ anonymous_settings = copy.copy(self.app_settings) anonymous_settings.update({ 'authtkt.secret': 'whatever', 'authtkt.secure': True, }) with mock.patch('bodhi.server.Session.remove'): app = webtest.TestApp(main({}, session=self.db, **anonymous_settings)) resp = app.get('/overrides/bodhi-2.0-1.fc17', status=200, headers={'Accept': 'text/html'}) self.assertNotIn('<span>New Buildroot Override Form Requires JavaScript</span>', resp) self.assertIn('<h2>Buildroot Override for <code>bodhi-2.0-1.fc17</code></h2>', resp)
def test_anonymous_cant_edit_release(self): """Ensure that an unauthenticated user cannot edit a release, since only an admin should.""" name = u"F22" # Create a new app so we are the anonymous user. app = webtest.TestApp(server.main({}, session=self.db, **self.app_settings)) res = app.get('/releases/%s' % name, status=200) r = res.json_body r["edited"] = name r["state"] = "current" r["csrf_token"] = self.get_csrf_token() # The anonymous user should receive a 403. res = app.post("/releases/", r, status=403) r = self.db.query(Release).filter(Release.name == name).one() self.assertEquals(r.state, ReleaseState.disabled)
def test_home(self): res = self.app.get('/', status=200) assert 'Log out' in res assert 'Fedora Update System' in res assert 'My Active Updates' in res # Test the unlogged in user view anonymous_settings = copy.copy(self.app_settings) anonymous_settings.update({ 'authtkt.secret': 'whatever', 'authtkt.secure': True, }) app = webtest.TestApp(main({}, session=self.db, **anonymous_settings)) res = app.get('/', status=200) assert 'Create, test, and publish package updates for Fedora.' in res assert 'Log out' not in res assert 'My Active Updates' not in res
def test_new_update_form(self): """Test the new update Form page""" # Test that a logged in user sees the New Update form res = self.app.get('/updates/new') self.assertIn('Creating a new update requires JavaScript', res) # Test that the unlogged in user cannot see the New Update form anonymous_settings = copy.copy(self.app_settings) anonymous_settings.update({ 'authtkt.secret': 'whatever', 'authtkt.secure': True, }) app = TestApp(main({}, session=self.db, **anonymous_settings)) res = app.get('/updates/new', status=403) self.assertIn('<h1>403 <small>Forbidden</small></h1>', res) self.assertIn( '<p class="lead">Access was denied to this resource.</p>', res)
def test_new_override_form(self): """Test the New Override form page""" headers = {'Accept': 'text/html'} # Test that the New Override form shows when logged in res = self.app.get('/overrides/new', headers=headers) self.assertIn('<span>New Buildroot Override Form Requires JavaScript</span>', res) # Test that the unlogged in user cannot see the New Override form anonymous_settings = copy.copy(self.app_settings) anonymous_settings.update({ 'authtkt.secret': 'whatever', 'authtkt.secure': True, }) app = webtest.TestApp(main({}, session=self.db, **anonymous_settings)) res = app.get('/overrides/new', status=403, headers=headers) self.assertIn('<h1>403 <small>Forbidden</small></h1>', res) self.assertIn('<p class="lead">Access was denied to this resource.</p>', res)
def test_anonymous_commenting_with_no_author(self): anonymous_settings = copy.copy(self.app_settings) anonymous_settings.update({ 'authtkt.secret': 'whatever', 'authtkt.secure': True, }) app = TestApp(main({}, session=self.db, **anonymous_settings)) comment = { u'update': 'bodhi-2.0-1.fc17', u'text': 'Test', u'karma': 0, u'csrf_token': app.get('/csrf').json_body['csrf_token'], } res = app.post_json('/comments/', comment, status=400) self.assertEquals(res.json_body['errors'][0]['name'], 'email') self.assertEquals(res.json_body['errors'][0]['description'], "You must provide an author")
def test_new_update_form(self): """Test the new update Form page""" headers = {'Accept': 'text/html'} # Test that a logged in user sees the New Update form res = self.app.get('/updates/new', headers=headers) assert 'Creating a new update requires JavaScript' in res # Make sure that unspecified comes first, as it should be the default. assert ('<select id="suggest" name="suggest">\n ' ' <option value="unspecified"') in res # Test that the unlogged in user cannot see the New Update form anonymous_settings = copy.copy(self.app_settings) anonymous_settings.update({ 'authtkt.secret': 'whatever', 'authtkt.secure': True, }) app = webtest.TestApp(main({}, session=self.db, **anonymous_settings)) res = app.get('/updates/new', status=403, headers=headers) assert '<h1>403 <small>Forbidden</small></h1>' in res assert '<p class="lead">Access was denied to this resource.</p>' in res
def test_comment_not_loggedin(self): """ Test that 403 error is returned if a non-authenticated 'post comment' request is received. It's important that we return 403 here so the client will know to re-authenticate """ anonymous_settings = copy.copy(self.app_settings) anonymous_settings.update({ 'authtkt.secret': 'whatever', 'authtkt.secure': True, }) with mock.patch('bodhi.server.Session.remove'): app = webtest.TestApp(main({}, session=self.db, **anonymous_settings)) csrf = app.get('/csrf', headers={'Accept': 'application/json'}).json_body['csrf_token'] update = Build.query.filter_by(nvr='bodhi-2.0-1.fc17').one().update.alias comment = { 'update': update, 'text': 'Test', 'karma': 0, 'csrf_token': csrf, } res = app.post_json('/comments/', comment, status=403) assert 'errors' in res.json_body
def test_popup_toggle(self): """Check that the toggling of pop-up notifications works""" # first we check that popups are enabled by default res = self.app.get('/') self.assertIn('Disable popups', res) # toggle popups off self.app.post('/popup_toggle') # now check popups are off res = self.app.get('/') self.assertIn('Enable popups', res) # test that the unlogged in user cannot toggle popups anonymous_settings = copy.copy(self.app_settings) anonymous_settings.update({ 'authtkt.secret': 'whatever', 'authtkt.secure': True, }) app = TestApp(main({}, session=self.db, **anonymous_settings)) res = app.post('/popup_toggle', status=403) self.assertIn('<h1>403 <small>Forbidden</small></h1>', res) self.assertIn( '<p class="lead">Access was denied to this resource.</p>', res)
def test_new_update_form(self): """Test the new update Form page""" headers = {'Accept': 'text/html'} # Test that a logged in user sees the New Update form res = self.app.get('/updates/new', headers=headers) self.assertIn('Creating a new update requires JavaScript', res) # Make sure that unspecified comes first, as it should be the default. regex = r'' for value in ('unspecified', 'reboot', 'logout'): regex = regex + r'name="suggest" value="{}".*'.format(value) self.assertTrue(re.search(regex, res.body.decode('utf8').replace('\n', ' '))) # Test that the unlogged in user cannot see the New Update form anonymous_settings = copy.copy(self.app_settings) anonymous_settings.update({ 'authtkt.secret': 'whatever', 'authtkt.secure': True, }) app = webtest.TestApp(main({}, session=self.db, **anonymous_settings)) res = app.get('/updates/new', status=403, headers=headers) self.assertIn('<h1>403 <small>Forbidden</small></h1>', res) self.assertIn('<p class="lead">Access was denied to this resource.</p>', res)
def test_calls_initialize_db(self): """main() should call initialize_db() when called without a session arg.""" with mock.patch('bodhi.server.initialize_db') as init_db: server.main({}, **self.app_settings) init_db.assert_called_once()
def test_calls_session_remove(self): """Let's assert that main() calls Session.remove().""" with mock.patch('bodhi.server.Session.remove') as remove: server.main({}, session=self.db, **self.app_settings) remove.assert_called_once_with()