def test_check_release_exception(self, mock_log, mock_check): """ Assert that exception thrown in check_project release is correctly handled. """ mock_check.side_effect = exceptions.AnityaPluginException("Error") request_data = { "backend": "PyPI", "homepage": "http://python-requests.org", "name": "requests", "check_release": "True", } with fml_testing.mock_sends(anitya_schema.ProjectCreated): output = self.app.post("/api/v2/projects/", headers=self.auth, data=request_data) mock_check.assert_called_once_with(mock.ANY, mock.ANY) self.assertEqual(output.status_code, 201) self.assertIn("Error", mock_log.error.call_args_list[0][0])
def test_valid_request(self): request_data = { "backend": "PyPI", "homepage": "http://python-requests.org", "name": "requests", } with fml_testing.mock_sends(anitya_schema.ProjectCreated): output = self.app.post("/api/v2/projects/", headers=self.auth, data=request_data) data = _read_json(output) self.assertEqual(output.status_code, 201) self.assertIn("backend", data) self.assertIn("homepage", data) self.assertIn("name", data) self.assertEqual("PyPI", data["backend"]) self.assertEqual("http://python-requests.org", data["homepage"]) self.assertEqual("requests", data["name"])
def test_override_expired_date(self, get): """ Test that a User can see the expired date of the override """ get.return_value.humanize.return_value = '82 seconds bro' expiration_date = datetime.utcnow() + timedelta(days=1) data = {'nvr': 'bodhi-2.0-1.fc17', 'notes': 'blah blah blah', 'expiration_date': expiration_date, 'edited': 'bodhi-2.0-1.fc17', 'expired': True, 'csrf_token': self.get_csrf_token()} with fml_testing.mock_sends(api.Message): self.app.post('/overrides/', data) resp = self.app.get('/overrides/bodhi-2.0-1.fc17', status=200, headers={'Accept': 'text/html'}) self.assertRegex( str(resp), ("<span class='col-xs-auto pr-2 ml-auto text-danger'><small>" "expired <strong>82 seconds bro ago</strong></small></span>")) self.assertTrue(abs((get.mock_calls[0][1][0] - expiration_date).seconds) < 64)
def test_autotime_update_meeting_stable_days_get_pushed(self): """ Ensure that an autotime update that meets the stable days gets pushed. """ update = self.db.query(models.Update).all()[0] update.autokarma = False update.autotime = True update.request = None update.stable_karma = 10 update.stable_days = 10 update.date_testing = datetime.utcnow() - timedelta(days=10) update.status = models.UpdateStatus.testing # Clear pending messages self.db.info['messages'] = [] self.db.commit() with fml_testing.mock_sends(api.Message, api.Message): approve_testing_main() assert update.request == models.UpdateRequest.stable
def test_step_3(client, post_data_step_3, token_for_dummy_user, cleanup_dummy_user, mocker): """Register a user, step 3""" record_signal = mocker.Mock() with fml_testing.mock_sends( UserCreateV1({"msg": { "agent": "dummy", "user": "******" }})), user_registered.connected_to(record_signal): result = client.post( f"/register/activate?token={token_for_dummy_user}", data=post_data_step_3) assert_redirects_with_flash( result, expected_url="/", expected_message= "Congratulations, your account has been created! Welcome, Dummy User.", expected_category="success", ) record_signal.assert_called_once()
def test_new_project_configured_on(self): """Assert that a libraries.io event about an unknown project creates that project""" event = sseclient.Event( data="{" '"name": "ImageMetaTag",' '"platform": "PyPi",' '"version": "0.6.9",' '"package_manager_url": "https://pypi.org/project/ImageMetaTag/"' "}") with mock.patch.object(self.client, "whitelist", ["pypi"]), fml_testing.mock_sends( anitya_schema.ProjectCreated, anitya_schema.ProjectVersionUpdated): self.client.process_message(event) self.assertEqual(1, self.session.query(Project).count()) project = self.session.query(Project).first() self.assertEqual("ImageMetaTag", project.name) self.assertEqual("pypi", project.ecosystem_name) self.assertEqual("0.6.9", project.latest_version)
def test_autotime_update_does_no_mandatory_days_in_testing(self): """ Ensure that an autotime update that does not have mandatory days in testing does get pushed to stable. """ update = self.db.query(models.Update).all()[0] update.autokarma = False update.autotime = True update.request = None update.stable_karma = 10 update.date_testing = datetime.utcnow() update.status = models.UpdateStatus.testing # Clear pending messages self.db.info['messages'] = [] self.db.commit() with fml_testing.mock_sends(api.Message, api.Message): approve_testing_main() assert update.request == models.UpdateRequest.stable
def test_update_project_error_threshold_reached(self): """ Assert that project is deleted when error threshold is reached. """ project = models.Project( name="Foobar", backend="GitHub", homepage="www.fakeproject.com", next_check=arrow.utcnow().datetime, error_counter=100, ) self.session.add(project) self.session.commit() with fml_testing.mock_sends(anitya_schema.ProjectDeleted): self.checker.update_project(project.id) projects = self.session.query(models.Project).all() self.assertEqual(len(projects), 0)
def test_comment_on_locked_update(self): """ Make sure you can comment on locked updates. """ # Lock it up = self.db.query(Build).filter_by(nvr=up2).one().update up.locked = True up.status = UpdateStatus.testing up.request = None assert len(up.comments) == 0 # Before assert up.karma == 0 # Before # Clear pending messages self.db.info['messages'] = [] self.db.flush() comment = self.make_comment(up2, karma=1) with fml_testing.mock_sends(api.Message): self.app.post_json('/comments/', comment) up = self.db.query(Build).filter_by(nvr=up2).one().update assert len(up.comments) == 1 # After assert up.karma == 1 # After
def test_correct_msg_in_file(self): """Assert providing path to file with correct message via the CLI works.""" cli_options = {"file": GOOD_MSG_DUMP, "exchange": "test_pe"} expected_msg = message.Message(body={"test_key1": "test_value1"}, topic="test_topic", severity=message.INFO) with testing.mock_sends(expected_msg): result = self.runner.invoke( cli.cli, [ "--conf=" + GOOD_CONF, "publish", "--exchange=" + cli_options["exchange"], cli_options["file"], ], ) self.assertIn("Publishing message with topic test_topic", result.output) self.assertEqual(0, result.exit_code)
def test_override_expired_date(self, get): """ Test that a User can see the expired date of the override """ get.return_value.humanize.return_value = '82 seconds ago bro' expiration_date = datetime.utcnow() + timedelta(days=1) data = {'nvr': 'bodhi-2.0-1.fc17', 'notes': 'blah blah blah', 'expiration_date': expiration_date, 'edited': 'bodhi-2.0-1.fc17', 'expired': True, 'csrf_token': self.get_csrf_token()} with fml_testing.mock_sends(api.Message): self.app.post('/overrides/', data) resp = self.app.get('/overrides/bodhi-2.0-1.fc17', status=200, headers={'Accept': 'text/html'}) self.assertRegex( str(resp), ('Expired\\n.*<span class="text-muted" ' 'data-toggle="tooltip" title=".*"> 82 seconds ago bro </span>')) self.assertTrue(abs((get.mock_calls[0][1][0] - expiration_date).seconds) < 64)
def test_no_self_karma(self): " Make sure you can't give +1 karma to your own updates.. " comment = self.make_comment('bodhi-2.0-1.fc17', karma=1) # The author of this comment is "guest" up = self.db.query(Build).filter_by( nvr='bodhi-2.0-1.fc17').one().update assert up.user.name == 'guest' with fml_testing.mock_sends(api.Message): r = self.app.post_json('/comments/', comment) comment = r.json_body['comment'] assert comment['user']['name'] == 'guest' assert comment['update']['title'] == 'bodhi-2.0-1.fc17' caveats = r.json_body['caveats'] assert len(caveats) == 1 assert caveats[0]['name'] == 'karma' assert caveats[0][ 'description'] == "You may not give karma to your own updates." assert comment['karma'] == 0 # This is the real check
def test_user_edit_post_minimal_values(client, logged_in_dummy_user): """Test posting to the user edit page: /user/<username>/settings/profile/ with the bare minimum of values """ with fml_testing.mock_sends( UserUpdateV1({ "msg": { "agent": "dummy", "user": "******", "fields": ['timezone', 'locale'], } })): result = client.post('/user/dummy/settings/profile/', data=POST_CONTENTS_MIN) assert_redirects_with_flash( result, expected_url="/user/dummy/settings/profile/", expected_message= "Profile Updated: <a href=\"/user/dummy/\">view your profile</a>", expected_category="success", )
def test_project_flag_search_count(self): """ Assert that 'ProjectFlag.search' returns correct project if count is set. """ flag = create_flagged_project(self.session) with fml_testing.mock_sends(anitya_schema.ProjectFlag): flag_add = utilities.flag_project( self.session, flag.project, "This is a duplicate.", "*****@*****.**", "user_openid_id", ) flag_add.state = "closed" self.session.add(flag_add) self.session.commit() flags = models.ProjectFlag.search(self.session, count=True) self.assertEqual(flags, 2)
def test_non_autokarma_critpath_update_not_meeting_time_requirements_gets_no_comment( self): """ Ensure that a non-autokarma critical path update that does not meet the required time in testing does not get any comment from bodhi saying it can be pushed to stable. There was an issue[0] where Bodhi was incorrectly detecting that the update could be pushed and was commenting to that effect. This test ensures that issue stays fixed. [0] https://github.com/fedora-infra/bodhi/issues/1009 """ update = self.db.query(models.Update).all()[0] update.autokarma = False # Make this update a critpath update to force meets_testing_requirements into a different # code path. update.critpath = True update.request = None update.stable_karma = 1 update.status = models.UpdateStatus.testing update.comment(self.db, 'testing', author='hunter2', karma=1) with fml_testing.mock_sends(api.Message): self.db.commit() with patch('bodhi.server.scripts.approve_testing.initialize_db'): with patch('bodhi.server.scripts.approve_testing.get_appsettings', return_value=''): approve_testing.main(['nosetests', 'some_config.ini']) # Now we will run main() again, but this time we expect Bodhi not to add any # further comments. approve_testing.main(['nosetests', 'some_config.ini']) # The bodhi user shouldn't exist, since it shouldn't have made any comments self.assertEqual( self.db.query(models.User).filter_by(name='bodhi').count(), 0) # There are three comments, but none from the non-existing bodhi user. self.assertEqual(self.db.query(models.Comment).count(), 3) usernames = [ c.user.name for c in self.db.query(models.Comment).order_by( models.Comment.timestamp).all() ] self.assertEqual(usernames, ['guest', 'anonymous', 'hunter2'])
def test_non_autokarma_critpath_update_meeting_karma_requirements_gets_one_comment( self): """ Ensure that a non-autokarma critical path update that meets the required karma threshold and required time in testing gets only one comment from Bodhi to that effect, even on subsequent runs of main(). There was an issue[0] where Bodhi wasn't correctly detecting when it should add these comments, and with detecting that it has already commented on critical path updates, and would repeatedly comment that these updates could be pushed. This test ensures that issue stays fixed. [0] https://github.com/fedora-infra/bodhi/issues/1009 """ update = self.db.query(models.Update).all()[0] update.autokarma = False # Make this update a critpath update to force meets_testing_requirements into a different # code path. update.critpath = True # It's been in testing long enough to get the comment from bodhi that it can be pushed. update.date_testing = datetime.utcnow() - timedelta(days=15) update.request = None update.stable_karma = 1 update.status = models.UpdateStatus.testing update.comment(self.db, 'testing', author='hunter2', karma=1) with fml_testing.mock_sends(api.Message): self.db.commit() with patch('bodhi.server.scripts.approve_testing.initialize_db'): with patch('bodhi.server.scripts.approve_testing.get_appsettings', return_value=''): approve_testing.main(['nosetests', 'some_config.ini']) # Now we will run main() again, but this time we expect Bodhi not to add any # further comments. approve_testing.main(['nosetests', 'some_config.ini']) bodhi = self.db.query(models.User).filter_by(name='bodhi').one() comment_q = self.db.query(models.Comment).filter_by( update_id=update.id, user_id=bodhi.id) self.assertEqual(comment_q.count(), 1) self.assertEqual(comment_q[0].text, config.get('testing_approval_msg_based_on_karma'))
def test_short_password_policy( client, post_data_step_3, token_for_dummy_user, cleanup_dummy_user ): """Register a user with a password rejected by the server policy""" with fml_testing.mock_sends( UserCreateV1({"msg": {"agent": "dummy", "user": "******"}}) ): post_data_step_3["password"] = post_data_step_3["password_confirm"] = "1234567" result = client.post( f"/register/activate?token={token_for_dummy_user}", data=post_data_step_3 ) assert_redirects_with_flash( result, expected_url="/", expected_message=( 'Your account has been activated, but the password you chose does not comply ' 'with the policy (Constraint violation: Password is too short) and has thus ' 'been set as expired. You will be asked to change it after logging in.' ), expected_category="warning", )
def test_project_flag_search_by_user(self): """ Assert that 'ProjectFlag.search' returns correct project if from date is provided. """ flag = create_flagged_project(self.session) with fml_testing.mock_sends(anitya_schema.ProjectFlag): flag_add = utilities.flag_project( self.session, flag.project, "This is a duplicate.", "*****@*****.**", "user_openid_id", ) flag_add.state = "closed" self.session.add(flag_add) self.session.commit() user = flag.user flags = models.ProjectFlag.search(self.session, user=user) self.assertEqual(len(flags), 1)
def test_consume(self, caplog): """Assert that messages about tagged builds create an update.""" caplog.set_level(logging.DEBUG) # process the message with mock_sends(UpdateMessage): self.handler(self.sample_message) # check if the update exists... update = self.db.query(Update).filter( Update.builds.any(Build.nvr == self.sample_nvr) ).first() # ...and some of its properties assert update is not None assert update.type == UpdateType.unspecified expected_username = base.buildsys.DevBuildsys._build_data['owner_name'] assert update.user and update.user.name == expected_username assert not any(r.levelno >= logging.WARNING for r in caplog.records)
def test_password_changes(client, dummy_user): """Verify that password changes""" with fml_testing.mock_sends( UserUpdateV1( {"msg": {"agent": "dummy", "user": "******", "fields": ["password"]}} ) ): result = client.post( '/password-reset?username=dummy', data={ "current_password": "******", "password": "******", "password_confirm": "secretpw", }, ) assert_redirects_with_flash( result, expected_url="/", expected_message="Your password has been changed", expected_category="success", )
def test_autotime_update_does_not_meet_stable_days_doesnt_get_pushed(self): """ Ensure that an autotime update that meets the test requirements but has a longer stable days define does not get push. """ update = self.db.query(models.Update).all()[0] update.autokarma = False update.autotime = True update.request = None update.stable_karma = 10 update.stable_days = 10 update.date_testing = datetime.utcnow() - timedelta(days=7) update.status = models.UpdateStatus.testing # Clear pending messages self.db.info['messages'] = [] self.db.commit() with fml_testing.mock_sends(api.Message): approve_testing_main() assert update.request is None
def test_no_autotime_update_meeting_stable_days_and_test_requirement(self): """ Ensure that a normal update that meets the stable days and test requirements doe not get pushed. """ update = self.db.query(models.Update).all()[0] update.autokarma = False update.autotime = False update.request = None update.stable_karma = 10 update.stable_days = 10 update.date_testing = datetime.utcnow() - timedelta(days=10) update.status = models.UpdateStatus.testing # Clear pending messages self.db.info['messages'] = [] self.db.commit() with fml_testing.mock_sends(api.Message): approve_testing_main() assert update.request is None
def test_user_in_blacklist(self, caplog): """Test that update not created if the koji build owner is in the blacklist""" caplog.set_level(logging.DEBUG) body = { 'build_id': 4425622, 'name': 'python-pants', 'tag_id': 214, 'instance': 's390', 'tag': 'f17-updates-testing-pending', 'user': '******', 'version': '1.3.4', 'owner': 'lmacken', 'release': '1.fc26', } self.sample_message = Message(topic='', body=body) self.sample_nvr = f"{body['name']}-{body['version']}-{body['release']}" with mock_sends(): self.handler(self.sample_message) assert (f"{self.sample_nvr} owned by lmacken who is listed in " "automatic_updates_blacklist, skipping." in caplog.messages)
def test_non_autokarma_critpath_update_not_meeting_time_requirements_gets_no_comment( self): """ Ensure that a non-autokarma critical path update that does not meet the required time in testing does not get any comment from bodhi saying it can be pushed to stable. There was an issue[0] where Bodhi was incorrectly detecting that the update could be pushed and was commenting to that effect. This test ensures that issue stays fixed. [0] https://github.com/fedora-infra/bodhi/issues/1009 """ update = self.db.query(models.Update).all()[0] update.autokarma = False # Make this update a critpath update to force meets_testing_requirements into a different # code path. update.critpath = True update.request = None update.stable_karma = 1 update.status = models.UpdateStatus.testing self.db.flush() # Clear pending messages self.db.info['messages'] = [] approve_testing_main() # Now we will run main() again, but this time we expect Bodhi not to add any # further comments. with fml_testing.mock_sends(): approve_testing_main() # The update should have one +1, which is as much as the stable karma but not as much as the # required +2 to go stable. assert update._composite_karma == (1, 0) # The bodhi user shouldn't exist, since it shouldn't have made any comments assert self.db.query(models.User).filter_by(name='bodhi').count() == 0 # There are two comments, but none from the non-existing bodhi user. assert self.db.query(models.Comment).count() == 2 usernames = [ c.user.name for c in self.db.query(models.Comment).order_by( models.Comment.timestamp).all() ] assert usernames == ['guest', 'anonymous']
def test_create_duplicate_override(self): release = Release.get('F17') package = RpmPackage(name='not-bodhi') self.db.add(package) build = RpmBuild(nvr='not-bodhi-2.0-2.fc17', package=package, release=release) self.db.add(build) self.db.flush() expiration_date = datetime.utcnow() + timedelta(days=1) data = { 'nvr': build.nvr, 'notes': 'blah blah blah', 'expiration_date': expiration_date, 'csrf_token': self.get_csrf_token() } with fml_testing.mock_sends(override_schemas.BuildrootOverrideTagV1): res = self.app.post('/overrides/', data) o = res.json_body self.assertEqual(o['build_id'], build.id) self.assertEqual(o['notes'], 'blah blah blah') self.assertEqual(o['expiration_date'], expiration_date.strftime("%Y-%m-%d %H:%M:%S")) self.assertEqual(o['expired_date'], None) # Submit it again data['notes'] = 'new blah blah' res = self.app.post('/overrides/', data) o = res.json_body new_notes = """blah blah blah _@guest ({})_ _____________ new blah blah""".format(datetime.utcnow().strftime("%b %d, %Y")) self.assertEqual(o['notes'], new_notes)
def test_autotime_update_negative_karma_does_not_get_pushed(self): """ Ensure that an autotime update with negative karma does not get pushed. """ update = self.db.query(models.Update).all()[0] update.autokarma = False update.autotime = True update.request = None update.stable_karma = 10 update.stable_days = 0 update.date_testing = datetime.utcnow() - timedelta(days=0) update.status = models.UpdateStatus.testing # Clear pending messages self.db.info['messages'] = [] update.comment(self.db, u'Failed to work', author=u'luke', karma=-1) with fml_testing.mock_sends(api.Message): self.db.commit() approve_testing_main() assert update.request is None
def test_create_duplicate_override(self): """When creating a duplicate override, old notes are appended.""" release = Release.get('F17') package = RpmPackage(name='not-bodhi') self.db.add(package) build = RpmBuild(nvr='not-bodhi-2.0-2.fc17', package=package, release=release) self.db.add(build) self.db.flush() expiration_date = datetime.utcnow() + timedelta(days=1) data = { 'nvr': build.nvr, 'notes': 'blah blah blah', 'expiration_date': expiration_date, 'csrf_token': self.get_csrf_token() } with fml_testing.mock_sends(override_schemas.BuildrootOverrideTagV1): res = self.app.post('/overrides/', data) o = res.json_body assert o['build_id'] == build.id assert o['notes'] == 'blah blah blah' assert o['expiration_date'] == expiration_date.strftime( "%Y-%m-%d %H:%M:%S") assert o['expired_date'] is None # Submit it again data['notes'] = 'new blah blah' res = self.app.post('/overrides/', data) o = res.json_body new_notes = f"""new blah blah _____________ _@guest ({datetime.utcnow().strftime('%b %d, %Y')})_ blah blah blah""" assert o['notes'] == new_notes
def test_autotime_update_meeting_test_requirements_gets_pushed(self): """ Ensure that an autotime update that meets the test requirements gets pushed to stable. """ update = self.db.query(models.Update).all()[0] update.autokarma = False update.autotime = True update.request = None update.stable_karma = 10 update.stable_days = 7 update.date_testing = datetime.utcnow() - timedelta(days=7) update.status = models.UpdateStatus.testing # Clear pending messages self.db.info['messages'] = [] self.db.commit() with fml_testing.mock_sends( update_schemas.UpdateRequirementsMetStableV1, update_schemas.UpdateRequestStableV1): approve_testing_main() assert update.request == models.UpdateRequest.stable
def test_create_override_with_missing_pkg(self): nvr = 'not-bodhi-2.0-2.fc17' expiration_date = datetime.utcnow() + timedelta(days=1) data = { 'nvr': nvr, 'notes': 'blah blah blah', 'expiration_date': expiration_date, 'csrf_token': self.get_csrf_token() } with fml_testing.mock_sends(override_schemas.BuildrootOverrideTagV1): res = self.app.post('/overrides/', data, headers={'Accept': 'application/json'}) o = res.json_body self.assertEqual(o['nvr'], nvr) self.assertEqual(o['notes'], 'blah blah blah') self.assertEqual(o['expiration_date'], expiration_date.strftime("%Y-%m-%d %H:%M:%S")) self.assertEqual(o['expired_date'], None)
def test_expire_override(self): old_nvr = 'bodhi-2.0-1.fc17' res = self.app.get('/overrides/%s' % old_nvr, headers={'Accept': 'application/json'}) o = res.json_body['override'] o.update({ 'nvr': o['build']['nvr'], 'expired': True, 'edited': old_nvr, 'csrf_token': self.get_csrf_token() }) with fml_testing.mock_sends(override_schemas.BuildrootOverrideUntagV1): res = self.app.post('/overrides/', o) override = res.json_body self.assertEqual(override['build'], o['build']) self.assertEqual(override['notes'], o['notes']) self.assertEqual(override['expiration_date'], o['expiration_date']) self.assertNotEqual(override['expired_date'], None)