This is an automated email from the ASF dual-hosted git repository. brondsem pushed a commit to branch db/8566 in repository https://gitbox.apache.org/repos/asf/allura.git
commit a9143bceb1b06b9492c57dbe8a35ed037ac6737b Author: Dave Brondsema <[email protected]> AuthorDate: Fri Jul 12 10:39:26 2024 -0400 [#8566] cleaner "raises" checking in tests --- Allura/allura/tests/model/test_artifact.py | 3 +- Allura/allura/tests/model/test_notification.py | 4 +- Allura/allura/tests/model/test_repo.py | 4 +- Allura/allura/tests/test_app.py | 6 ++- Allura/allura/tests/test_commands.py | 56 +++++++++++----------- Allura/allura/tests/test_globals.py | 7 ++- Allura/allura/tests/test_helpers.py | 7 ++- Allura/allura/tests/test_plugin.py | 19 ++++---- Allura/allura/tests/test_utils.py | 30 ++++++------ .../tests/unit/test_helpers/test_set_context.py | 18 +++---- .../allura/tests/unit/test_package_path_loader.py | 15 +++--- .../forgeimporters/tests/forge/test_tracker.py | 8 ++-- .../forgeimporters/trac/tests/test_tickets.py | 11 ++--- ForgeSVN/forgesvn/tests/model/test_repository.py | 4 +- 14 files changed, 100 insertions(+), 92 deletions(-) diff --git a/Allura/allura/tests/model/test_artifact.py b/Allura/allura/tests/model/test_artifact.py index d63a2041e..33274bda6 100644 --- a/Allura/allura/tests/model/test_artifact.py +++ b/Allura/allura/tests/model/test_artifact.py @@ -165,7 +165,8 @@ class TestArtifact: assert ss.shorthand_id() == pg.shorthand_id() + '#2' assert ss.title == pg.title assert ss.text == pg.text - pytest.raises(IndexError, pg.get_version, 42) + with pytest.raises(IndexError): + pg.get_version(42) pg.revert(1) pg.commit() ThreadLocalODMSession.flush_all() diff --git a/Allura/allura/tests/model/test_notification.py b/Allura/allura/tests/model/test_notification.py index 920157598..9fdf2385c 100644 --- a/Allura/allura/tests/model/test_notification.py +++ b/Allura/allura/tests/model/test_notification.py @@ -19,6 +19,7 @@ import unittest from datetime import timedelta import collections +import pytest from tg import tmpl_context as c, app_globals as g from ming.odm import ThreadLocalODMSession import mock @@ -341,7 +342,8 @@ class TestSubscriptionTypes(unittest.TestCase): M.notification.MAILBOX_QUIESCENT = timedelta(minutes=1) # will raise "assert msg is not None" since the new message is not 1 # min old: - self.assertRaises(AssertionError, self._test_message) + with pytest.raises(AssertionError): + self._test_message() def _test_message(self): self._subscribe() diff --git a/Allura/allura/tests/model/test_repo.py b/Allura/allura/tests/model/test_repo.py index 9081319e0..0a91d690b 100644 --- a/Allura/allura/tests/model/test_repo.py +++ b/Allura/allura/tests/model/test_repo.py @@ -20,6 +20,7 @@ from collections import defaultdict, OrderedDict import unittest import mock +import pytest from tg import tmpl_context as c from bson import ObjectId from ming.odm import session @@ -413,7 +414,8 @@ class TestModelCache(unittest.TestCase): n = mock.Mock(spec_set=['foo'], foo='qux') self.assertEqual(self.cache._model_query(q), 'foo') self.assertEqual(self.cache._model_query(m), 'bar') - self.assertRaises(AttributeError, self.cache._model_query, [n]) + with pytest.raises(AttributeError): + self.cache._model_query([n]) @mock.patch.object(M.repository.Tree.query, 'get') @mock.patch.object(M.repository.LastCommit.query, 'get') diff --git a/Allura/allura/tests/test_app.py b/Allura/allura/tests/test_app.py index cffe3fb5d..913840315 100644 --- a/Allura/allura/tests/test_app.py +++ b/Allura/allura/tests/test_app.py @@ -71,8 +71,10 @@ class TestApp: v = fev.NotEmpty() opt = app.ConfigOption('test1', str, None, validator=v) assert opt.validate('val') == 'val' - pytest.raises(fev.Invalid, opt.validate, None) - pytest.raises(fev.Invalid, opt.validate, '') + with pytest.raises(fev.Invalid): + opt.validate(None) + with pytest.raises(fev.Invalid): + opt.validate('') def test_options_on_install_default(self): a = app.Application(c.project, c.app.config) diff --git a/Allura/allura/tests/test_commands.py b/Allura/allura/tests/test_commands.py index 660b0f172..b5d74d78c 100644 --- a/Allura/allura/tests/test_commands.py +++ b/Allura/allura/tests/test_commands.py @@ -53,8 +53,8 @@ def test_script(): cmd = script.ScriptCommand('script') cmd.run( [test_config, pkg_resources.resource_filename('allura', 'tests/tscript.py')]) - pytest.raises(ValueError, cmd.run, - [test_config, pkg_resources.resource_filename('allura', 'tests/tscript_error.py')]) + with pytest.raises(ValueError): + cmd.run([test_config, pkg_resources.resource_filename('allura', 'tests/tscript_error.py')]) def test_set_neighborhood_max_projects(): @@ -74,10 +74,10 @@ def test_set_neighborhood_max_projects(): assert neighborhood.features['max_projects'] is None # check validation - pytest.raises(InvalidNBFeatureValueError, cmd.run, - [test_config, str(n_id), 'max_projects', 'string']) - pytest.raises(InvalidNBFeatureValueError, cmd.run, - [test_config, str(n_id), 'max_projects', '2.8']) + with pytest.raises(InvalidNBFeatureValueError): + cmd.run([test_config, str(n_id), 'max_projects', 'string']) + with pytest.raises(InvalidNBFeatureValueError): + cmd.run([test_config, str(n_id), 'max_projects', '2.8']) def test_set_neighborhood_private(): @@ -97,12 +97,12 @@ def test_set_neighborhood_private(): assert not neighborhood.features['private_projects'] # check validation - pytest.raises(InvalidNBFeatureValueError, cmd.run, - [test_config, str(n_id), 'private_projects', 'string']) - pytest.raises(InvalidNBFeatureValueError, cmd.run, - [test_config, str(n_id), 'private_projects', '1']) - pytest.raises(InvalidNBFeatureValueError, cmd.run, - [test_config, str(n_id), 'private_projects', '2.8']) + with pytest.raises(InvalidNBFeatureValueError): + cmd.run([test_config, str(n_id), 'private_projects', 'string']) + with pytest.raises(InvalidNBFeatureValueError): + cmd.run([test_config, str(n_id), 'private_projects', '1']) + with pytest.raises(InvalidNBFeatureValueError): + cmd.run([test_config, str(n_id), 'private_projects', '2.8']) def test_set_neighborhood_google_analytics(): @@ -122,12 +122,12 @@ def test_set_neighborhood_google_analytics(): assert not neighborhood.features['google_analytics'] # check validation - pytest.raises(InvalidNBFeatureValueError, cmd.run, - [test_config, str(n_id), 'google_analytics', 'string']) - pytest.raises(InvalidNBFeatureValueError, cmd.run, - [test_config, str(n_id), 'google_analytics', '1']) - pytest.raises(InvalidNBFeatureValueError, cmd.run, - [test_config, str(n_id), 'google_analytics', '2.8']) + with pytest.raises(InvalidNBFeatureValueError): + cmd.run([test_config, str(n_id), 'google_analytics', 'string']) + with pytest.raises(InvalidNBFeatureValueError): + cmd.run([test_config, str(n_id), 'google_analytics', '1']) + with pytest.raises(InvalidNBFeatureValueError): + cmd.run([test_config, str(n_id), 'google_analytics', '2.8']) def test_set_neighborhood_css(): @@ -152,16 +152,16 @@ def test_set_neighborhood_css(): assert neighborhood.features['css'] == 'custom' # check validation - pytest.raises(InvalidNBFeatureValueError, cmd.run, - [test_config, str(n_id), 'css', 'string']) - pytest.raises(InvalidNBFeatureValueError, cmd.run, - [test_config, str(n_id), 'css', '1']) - pytest.raises(InvalidNBFeatureValueError, cmd.run, - [test_config, str(n_id), 'css', '2.8']) - pytest.raises(InvalidNBFeatureValueError, cmd.run, - [test_config, str(n_id), 'css', 'None']) - pytest.raises(InvalidNBFeatureValueError, cmd.run, - [test_config, str(n_id), 'css', 'True']) + with pytest.raises(InvalidNBFeatureValueError): + cmd.run([test_config, str(n_id), 'css', 'string']) + with pytest.raises(InvalidNBFeatureValueError): + cmd.run([test_config, str(n_id), 'css', '1']) + with pytest.raises(InvalidNBFeatureValueError): + cmd.run([test_config, str(n_id), 'css', '2.8']) + with pytest.raises(InvalidNBFeatureValueError): + cmd.run([test_config, str(n_id), 'css', 'None']) + with pytest.raises(InvalidNBFeatureValueError): + cmd.run([test_config, str(n_id), 'css', 'True']) def test_update_neighborhood(): diff --git a/Allura/allura/tests/test_globals.py b/Allura/allura/tests/test_globals.py index dfd9d492a..ec2718da5 100644 --- a/Allura/allura/tests/test_globals.py +++ b/Allura/allura/tests/test_globals.py @@ -18,6 +18,9 @@ import inspect import re import os from textwrap import dedent + +import pytest + import allura import unittest import hashlib @@ -768,8 +771,8 @@ class TestCachedMarkdown(unittest.TestCase): self.expected_html = '<div class="markdown_content"><p><strong>bold</strong></p></div>' def test_bad_source_field_name(self): - self.assertRaises(AttributeError, self.md.cached_convert, - self.post, 'no_such_field') + with pytest.raises(AttributeError): + self.md.cached_convert(self.post, 'no_such_field') def test_missing_cache_field(self): delattr(self.post, 'text_cache') diff --git a/Allura/allura/tests/test_helpers.py b/Allura/allura/tests/test_helpers.py index 8bd613ef8..1504a1adb 100644 --- a/Allura/allura/tests/test_helpers.py +++ b/Allura/allura/tests/test_helpers.py @@ -624,10 +624,9 @@ class TestIterEntryPoints(TestCase): self._make_ep('myapp', BetterApp), self._make_ep('myapp', BestApp)] - self.assertRaisesRegex(ImportError, - r'Ambiguous \[allura\] entry points detected. ' - 'Multiple entry points with name "myapp".', - list, h.iter_entry_points('allura')) + with pytest.raises(ImportError, match=r'Ambiguous \[allura\] entry points detected. ' + 'Multiple entry points with name "myapp".'): + list(h.iter_entry_points('allura')) def test_get_user_status(): diff --git a/Allura/allura/tests/test_plugin.py b/Allura/allura/tests/test_plugin.py index a75e444f5..90e65ee1c 100644 --- a/Allura/allura/tests/test_plugin.py +++ b/Allura/allura/tests/test_plugin.py @@ -70,16 +70,17 @@ class TestProjectRegistrationProvider: v = self.provider.shortname_validator.to_python v('thisislegit', neighborhood=nbhd) - pytest.raises(ProjectShortnameInvalid, v, - 'not valid', neighborhood=nbhd) - pytest.raises(ProjectShortnameInvalid, v, - 'this-is-valid-but-too-long', neighborhood=nbhd) - pytest.raises(ProjectShortnameInvalid, v, - 'this is invalid and too long', neighborhood=nbhd) - pytest.raises(ProjectShortnameInvalid, v, - 'end-dash-', neighborhood=nbhd) + with pytest.raises(ProjectShortnameInvalid): + v('not valid', neighborhood=nbhd) + with pytest.raises(ProjectShortnameInvalid): + v('this-is-valid-but-too-long', neighborhood=nbhd) + with pytest.raises(ProjectShortnameInvalid): + v('this is invalid and too long', neighborhood=nbhd) + with pytest.raises(ProjectShortnameInvalid): + v('end-dash-', neighborhood=nbhd) Project.query.get.return_value = Mock() - pytest.raises(ProjectConflict, v, 'thisislegit', neighborhood=nbhd) + with pytest.raises(ProjectConflict): + v('thisislegit', neighborhood=nbhd) class TestProjectRegistrationProviderParseProjectFromUrl: diff --git a/Allura/allura/tests/test_utils.py b/Allura/allura/tests/test_utils.py index 57b1b830b..fbe721b7d 100644 --- a/Allura/allura/tests/test_utils.py +++ b/Allura/allura/tests/test_utils.py @@ -118,10 +118,8 @@ class TestAntispam(unittest.TestCase): def test_invalid_old(self): form = dict(a='1', b='2') r = Request.blank('/', POST=self._encrypt_form(**form)) - self.assertRaises( - ValueError, - utils.AntiSpam.validate_request, - r, now=time.time() + 24 * 60 * 60 * 4 + 1) + with pytest.raises(ValueError): + utils.AntiSpam.validate_request(r, now=time.time() + 24 * 60 * 60 * 4 + 1) def test_valid_submit(self): form = dict(a='1', b='2') @@ -134,30 +132,31 @@ class TestAntispam(unittest.TestCase): def test_invalid_future(self): form = dict(a='1', b='2') r = Request.blank('/', POST=self._encrypt_form(**form)) - self.assertRaises( - ValueError, - utils.AntiSpam.validate_request, - r, now=time.time() - 10) + with pytest.raises(ValueError): + utils.AntiSpam.validate_request(r, now=time.time() - 10) def test_invalid_spinner(self): form = dict(a='1', b='2') eform = self._encrypt_form(**form) eform['spinner'] += 'a' r = Request.blank('/', POST=eform) - self.assertRaises(ValueError, utils.AntiSpam.validate_request, r) + with pytest.raises(ValueError): + utils.AntiSpam.validate_request(r) def test_invalid_honey(self): form = dict(a='1', b='2', honey0='a') eform = self._encrypt_form(**form) r = Request.blank('/', POST=eform) - self.assertRaises(ValueError, utils.AntiSpam.validate_request, r) + with pytest.raises(ValueError): + utils.AntiSpam.validate_request(r) def test_missing_honey(self): form = dict(a='1', b='2') eform = self._encrypt_form(**form) del eform[self.a.enc('honey0')] r = Request.blank('/', POST=eform) - self.assertRaises(ValueError, utils.AntiSpam.validate_request, r) + with pytest.raises(ValueError): + utils.AntiSpam.validate_request(r) def _encrypt_form(self, **kwargs): encrypted_form = { @@ -326,9 +325,12 @@ def test_empty_cursor(): assert cursor.hint('index') == cursor assert cursor.extensions == [] assert cursor.options(arg1='val1', arg2='val2') == cursor - pytest.raises(ValueError, cursor.one) - pytest.raises(StopIteration, cursor.next) - pytest.raises(StopIteration, cursor._next_impl) + with pytest.raises(ValueError): + cursor.one() + with pytest.raises(StopIteration): + cursor.next() + with pytest.raises(StopIteration): + cursor._next_impl() def test_DateJSONEncoder(): diff --git a/Allura/allura/tests/unit/test_helpers/test_set_context.py b/Allura/allura/tests/unit/test_helpers/test_set_context.py index 171cf4425..b7c1e14ca 100644 --- a/Allura/allura/tests/unit/test_helpers/test_set_context.py +++ b/Allura/allura/tests/unit/test_helpers/test_set_context.py @@ -95,23 +95,17 @@ class TestWhenProjectIsNotFound(WithDatabase): def test_that_it_raises_an_exception(self): nbhd = create_neighborhood() - pytest.raises(NoSuchProjectError, - set_context, - 'myproject', - neighborhood=nbhd) + with pytest.raises(NoSuchProjectError): + set_context('myproject', neighborhood=nbhd) def test_proper_exception_when_id_lookup(self): create_neighborhood() - pytest.raises(NoSuchProjectError, - set_context, - ObjectId(), - neighborhood=None) + with pytest.raises(NoSuchProjectError): + set_context(ObjectId(), neighborhood=None) class TestWhenNeighborhoodIsNotFound(WithDatabase): def test_that_it_raises_an_exception(self): - pytest.raises(NoSuchNeighborhoodError, - set_context, - 'myproject', - neighborhood='myneighborhood') + with pytest.raises(NoSuchNeighborhoodError): + set_context('myproject', neighborhood='myneighborhood') diff --git a/Allura/allura/tests/unit/test_package_path_loader.py b/Allura/allura/tests/unit/test_package_path_loader.py index 192eed615..40ed20fd0 100644 --- a/Allura/allura/tests/unit/test_package_path_loader.py +++ b/Allura/allura/tests/unit/test_package_path_loader.py @@ -79,7 +79,8 @@ class TestPackagePathLoader(TestCase): for ep in eps: ep.name = ep.ep_name ep.load.return_value.template_path_rules = ep.rules - pytest.raises(jinja2.TemplateError, PackagePathLoader()._load_rules) + with pytest.raises(jinja2.TemplateError): + PackagePathLoader()._load_rules() def test_replace_signposts(self): ppl = PackagePathLoader() @@ -217,14 +218,12 @@ class TestPackagePathLoader(TestCase): ppl.init_paths = mock.Mock() fs_loader().get_source.side_effect = jinja2.TemplateNotFound('test') - pytest.raises( - jinja2.TemplateError, - ppl.get_source, 'env', 'allura.ext.admin:templates/audit.html') + with pytest.raises(jinja2.TemplateError): + ppl.get_source('env', 'allura.ext.admin:templates/audit.html') assert fs_loader().get_source.call_count == 1 fs_loader().get_source.reset_mock() - with mock.patch.dict(config, {'disable_template_overrides': False}): - pytest.raises( - jinja2.TemplateError, - ppl.get_source, 'env', 'allura.ext.admin:templates/audit.html') + with mock.patch.dict(config, {'disable_template_overrides': False}), \ + pytest.raises(jinja2.TemplateError): + ppl.get_source('env', 'allura.ext.admin:templates/audit.html') assert fs_loader().get_source.call_count == 2 diff --git a/ForgeImporters/forgeimporters/tests/forge/test_tracker.py b/ForgeImporters/forgeimporters/tests/forge/test_tracker.py index 7e800c5d0..53e251f82 100644 --- a/ForgeImporters/forgeimporters/tests/forge/test_tracker.py +++ b/ForgeImporters/forgeimporters/tests/forge/test_tracker.py @@ -19,6 +19,8 @@ from datetime import datetime from unittest import TestCase import mock +import pytest + from ming.odm import ThreadLocalODMSession import webtest @@ -236,9 +238,9 @@ class TestTrackerImporter(TestCase): importer = tracker.ForgeTrackerImporter() importer._load_json = mock.Mock(return_value=tracker_json) - self.assertRaises( - ValueError, importer.import_tool, project, user, project_name='project_name', - mount_point='mount_point', mount_label='mount_label') + with pytest.raises(ValueError): + importer.import_tool(project, user, project_name='project_name', + mount_point='mount_point', mount_label='mount_label') h.make_app_admin_only.assert_called_once_with( project.install_app.return_value) diff --git a/ForgeImporters/forgeimporters/trac/tests/test_tickets.py b/ForgeImporters/forgeimporters/trac/tests/test_tickets.py index 9f975c78c..9336faf30 100644 --- a/ForgeImporters/forgeimporters/trac/tests/test_tickets.py +++ b/ForgeImporters/forgeimporters/trac/tests/test_tickets.py @@ -19,6 +19,8 @@ import json import os from unittest import TestCase, skipIf + +import pytest from mock import Mock, patch from ming.odm import ThreadLocalODMSession from tg import tmpl_context as c, config @@ -98,12 +100,9 @@ class TestTracTicketImporter(TestCase): user = Mock(name='User', _id='id') export.side_effect = ValueError - self.assertRaises(ValueError, importer.import_tool, project, user, - mount_point='bugs', - mount_label='Bugs', - trac_url='http://example.com/trac/url', - user_map=None, - ) + with pytest.raises(ValueError): + importer.import_tool(project, user, mount_point='bugs', mount_label='Bugs', + trac_url='http://example.com/trac/url', user_map=None) h.make_app_admin_only.assert_called_once_with(app) diff --git a/ForgeSVN/forgesvn/tests/model/test_repository.py b/ForgeSVN/forgesvn/tests/model/test_repository.py index 5165c6ced..9ab8de8e8 100644 --- a/ForgeSVN/forgesvn/tests/model/test_repository.py +++ b/ForgeSVN/forgesvn/tests/model/test_repository.py @@ -27,6 +27,7 @@ from zipfile import ZipFile from io import BytesIO from collections import defaultdict +import pytest from tg import tmpl_context as c, app_globals as g import mock import tg @@ -92,7 +93,8 @@ class TestNewRepo(unittest.TestCase): assert self.rev.tree.by_name['README'] assert self.rev.tree.is_blob('README') is True assert self.rev.tree['a']['b']['c'].ls() == [] - self.assertRaises(KeyError, lambda: self.rev.tree['a']['b']['d']) + with pytest.raises(KeyError): + self.rev.tree['a']['b']['d'] assert self.rev.authored_user is None assert self.rev.committed_user is None
