Skip to content

Commit

Permalink
[#8539] code simplifications
Browse files Browse the repository at this point in the history
  • Loading branch information
brondsem authored and webjunkie01 committed Mar 26, 2024
1 parent 468ed46 commit 0ca5177
Show file tree
Hide file tree
Showing 20 changed files with 71 additions and 77 deletions.
4 changes: 2 additions & 2 deletions Allura/allura/command/taskd_cleanup.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def _taskd_status(self, pid, retry=False):

def _check_taskd_status(self, pid):
for i in range(self.options.num_retry):
retry = False if i == 0 else True
retry = i != 0
status = self._taskd_status(pid, retry)
if ('taskd pid %s' % pid) in status:
return 'OK'
Expand All @@ -164,7 +164,7 @@ def _check_taskd_status(self, pid):

def _check_task(self, taskd_pid, task):
for i in range(self.options.num_retry):
retry = False if i == 0 else True
retry = i != 0
status = self._taskd_status(taskd_pid, retry)
line = 'taskd pid {} is currently handling task {}'.format(
taskd_pid, task)
Expand Down
2 changes: 1 addition & 1 deletion Allura/allura/controllers/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -564,7 +564,7 @@ def overview(self, **kw):
set_nav(self.neighborhood)
c.overview_form = W.neighborhood_overview_form
allow_undelete = asbool(config.get('allow_project_undelete', True))
allow_wiki_as_root = True if get_default_wiki_page() else False
allow_wiki_as_root = bool(get_default_wiki_page())

return dict(
neighborhood=self.neighborhood,
Expand Down
2 changes: 1 addition & 1 deletion Allura/allura/controllers/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ def enforce_ssl(self) -> bool:
if request.environ.get('paste.testing'):
# test suite is running
return False
elif asbool(config.get('debug')) and config['base_url'].startswith('http://'):
elif asbool(config.get('debug')) and config['base_url'].startswith('http://'): # noqa: SIM103
# development w/o https
return False
else:
Expand Down
2 changes: 1 addition & 1 deletion Allura/allura/controllers/site_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ def new_projects(self, **kwargs):
try:
end_dt = datetime.strptime(end_dt, '%Y/%m/%d %H:%M:%S')
except ValueError:
end_dt = start_dt - timedelta(days=3) if not end_dt else end_dt
end_dt = end_dt if end_dt else start_dt - timedelta(days=3)
start = bson.ObjectId.from_datetime(start_dt)
end = bson.ObjectId.from_datetime(end_dt)
nb = M.Neighborhood.query.get(name='Users')
Expand Down
2 changes: 1 addition & 1 deletion Allura/allura/lib/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ def validate_request(cls, request=None, now=None, params=None):
if params is None:
params = request.params
new_params = dict(params)
if not request.method == 'GET':
if request.method != 'GET':
obj = None
try:
new_params.pop('timestamp', None)
Expand Down
8 changes: 2 additions & 6 deletions Allura/allura/tests/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,12 +109,8 @@ def __enter__(self):
def __exit__(self, exc_type, exc_val, exc_t):
if exc_type:
self.exc = exc_val
if issubclass(exc_type, self.ExcType):
# ok
return True
else:
# root exception will be raised, untouched
return False
# otherwise root exception will be raised, untouched
return issubclass(exc_type, self.ExcType)
else:
raise AssertionError('Did not raise %s' % self.ExcType)

Expand Down
4 changes: 2 additions & 2 deletions Allura/allura/tests/functional/test_neighborhood.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ def test_custom_css(self):
neighborhood = M.Neighborhood.query.get(name='Adobe')
neighborhood.features['css'] = 'picker'
r = self.app.get('/adobe/')
while isinstance(r.response, HTTPFound) or isinstance(r.response, HTTPMovedPermanently):
while isinstance(r.response, (HTTPFound, HTTPMovedPermanently)):
r = r.follow()
assert test_css in r
r = self.app.get('/adobe/_admin/overview',
Expand All @@ -352,7 +352,7 @@ def test_custom_css(self):
neighborhood = M.Neighborhood.query.get(name='Adobe')
neighborhood.features['css'] = 'custom'
r = self.app.get('/adobe/')
while isinstance(r.response, HTTPFound) or isinstance(r.response, HTTPMovedPermanently):
while isinstance(r.response, (HTTPFound, HTTPMovedPermanently)):
r = r.follow()
assert test_css in r
r = self.app.get('/adobe/_admin/overview',
Expand Down
29 changes: 14 additions & 15 deletions Allura/allura/tests/functional/test_personal_dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,21 +50,20 @@ def ep(n):
return m
eps = list(map(ep, ['a', 'b', 'c', 'd']))
order = {'personal_dashboard_sections.order': 'b, d,c , f '}
with mock.patch('allura.lib.helpers.iter_entry_points') as iep:
with mock.patch.dict(tg.config, order):
iep.return_value = eps
sections = SectionsUtil.load_sections('personal_dashboard')
assert sections == [
eps[1].load(),
eps[3].load(),
eps[2].load(),
eps[0].load()]
r = self.app.get('/dashboard')
assert 'Section a' in r.text
assert 'Section b' in r.text
assert 'Section c' in r.text
assert 'Section d' in r.text
assert 'Section f' not in r.text
with mock.patch('allura.lib.helpers.iter_entry_points') as iep, mock.patch.dict(tg.config, order):
iep.return_value = eps
sections = SectionsUtil.load_sections('personal_dashboard')
assert sections == [
eps[1].load(),
eps[3].load(),
eps[2].load(),
eps[0].load()]
r = self.app.get('/dashboard')
assert 'Section a' in r.text
assert 'Section b' in r.text
assert 'Section c' in r.text
assert 'Section d' in r.text
assert 'Section f' not in r.text


class TestTicketsSection(TrackerTestController):
Expand Down
17 changes: 8 additions & 9 deletions Allura/allura/tests/functional/test_user_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,14 @@ def ep(n):
order = {'user_profile_sections.order': 'b, d,c , f '}
if hasattr(type(app), '_sections'):
delattr(type(app), '_sections')
with mock.patch('allura.lib.helpers.iter_entry_points') as iep:
with mock.patch.dict(tg.config, order):
iep.return_value = eps
sections = app.profile_sections
assert sections == [
eps[1].load(),
eps[3].load(),
eps[2].load(),
eps[0].load()]
with mock.patch('allura.lib.helpers.iter_entry_points') as iep, mock.patch.dict(tg.config, order):
iep.return_value = eps
sections = app.profile_sections
assert sections == [
eps[1].load(),
eps[3].load(),
eps[2].load(),
eps[0].load()]
r = self.app.get('/u/test-user/profile')
assert 'Section a' in r.text
assert 'Section b' in r.text
Expand Down
11 changes: 5 additions & 6 deletions Allura/allura/tests/model/test_project.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,12 +120,11 @@ def test_project_index(self):

def test_subproject(self):
project = M.Project.query.get(shortname='test')
with td.raises(ToolError):
with patch('allura.lib.plugin.ProjectRegistrationProvider') as Provider:
Provider.get().shortname_validator.to_python.side_effect = Invalid(
'name', 'value', {})
# name doesn't validate
sp = project.new_subproject('test-proj-nose')
with td.raises(ToolError), patch('allura.lib.plugin.ProjectRegistrationProvider') as Provider:
Provider.get().shortname_validator.to_python.side_effect = Invalid(
'name', 'value', {})
# name doesn't validate
sp = project.new_subproject('test-proj-nose')
sp = project.new_subproject('test-proj-nose')
spp = sp.new_subproject('spp')
ThreadLocalODMSession.flush_all()
Expand Down
4 changes: 2 additions & 2 deletions Allura/allura/tests/test_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -435,14 +435,14 @@ def test_status_log_retries():
cmd._taskd_status.return_value = ''
cmd.options = Mock(num_retry=10)
cmd._check_taskd_status(123)
expected_calls = [call(123, False if i == 0 else True) for i in range(10)]
expected_calls = [call(123, i != 0) for i in range(10)]
assert cmd._taskd_status.mock_calls == expected_calls

cmd._taskd_status = Mock()
cmd._taskd_status.return_value = ''
cmd.options = Mock(num_retry=3)
cmd._check_task(123, Mock())
expected_calls = [call(123, False if i == 0 else True) for i in range(3)]
expected_calls = [call(123, i != 0) for i in range(3)]
assert cmd._taskd_status.mock_calls == expected_calls


Expand Down
5 changes: 2 additions & 3 deletions Allura/allura/tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -542,9 +542,8 @@ def test_login_overlay():
raise HTTPUnauthorized()
with h.login_overlay(exceptions=['foo']):
raise HTTPUnauthorized()
with td.raises(HTTPUnauthorized):
with h.login_overlay(exceptions=['foobar']):
raise HTTPUnauthorized()
with td.raises(HTTPUnauthorized), h.login_overlay(exceptions=['foobar']):
raise HTTPUnauthorized()


class TestIterEntryPoints(TestCase):
Expand Down
10 changes: 5 additions & 5 deletions Allura/allura/tests/test_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -584,11 +584,11 @@ def setup_method(self, method):
setup_global_objects()

def test_delivers_messages(self):
with mock.patch.object(M.Mailbox, 'deliver') as deliver:
with mock.patch.object(M.Mailbox, 'fire_ready') as fire_ready:
notification_tasks.notify('42', ['52'], 'none')
deliver.assert_called_with('42', ['52'], 'none')
fire_ready.assert_called_with()
with mock.patch.object(M.Mailbox, 'deliver') as deliver, \
mock.patch.object(M.Mailbox, 'fire_ready') as fire_ready:
notification_tasks.notify('42', ['52'], 'none')
deliver.assert_called_with('42', ['52'], 'none')
fire_ready.assert_called_with()


@event_handler('my_event')
Expand Down
5 changes: 2 additions & 3 deletions Allura/allura/tests/test_webhooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -564,9 +564,8 @@ def test_send_no_configured_webhooks(self, send_webhook):
def test_get_payload(self):
sender = RepoPushWebhookSender()
_ci = lambda x: MagicMock(webhook_info={'id': str(x)}, parent_ids=['0'])
with patch.object(self.git.repo, 'commit', new=_ci):
with h.push_config(c, app=self.git):
result = sender.get_payload(commit_ids=['1', '2', '3'], ref='ref')
with patch.object(self.git.repo, 'commit', new=_ci), h.push_config(c, app=self.git):
result = sender.get_payload(commit_ids=['1', '2', '3'], ref='ref')
expected_result = {
'size': 3,
'commits': [{'id': '1'}, {'id': '2'}, {'id': '3'}],
Expand Down
28 changes: 13 additions & 15 deletions Allura/allura/tests/unit/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,13 @@ def test_extensions_cm():
def test_extensions_cm_raises():
session = mock.Mock(_kwargs=dict(extensions=[]))
extension = mock.Mock()
with td.raises(ValueError):
with substitute_extensions(session, [extension]) as sess:
session.flush.side_effect = AttributeError
assert session.flush.call_count == 1
assert session.close.call_count == 1
assert sess == session
assert sess._kwargs['extensions'] == [extension]
raise ValueError('test')
with td.raises(ValueError), substitute_extensions(session, [extension]) as sess:
session.flush.side_effect = AttributeError
assert session.flush.call_count == 1
assert session.close.call_count == 1
assert sess == session
assert sess._kwargs['extensions'] == [extension]
raise ValueError('test')
assert session.flush.call_count == 1
assert session.close.call_count == 1
assert session._kwargs['extensions'] == []
Expand All @@ -62,13 +61,12 @@ def test_extensions_cm_raises():
def test_extensions_cm_flush_raises():
session = mock.Mock(_kwargs=dict(extensions=[]))
extension = mock.Mock()
with td.raises(AttributeError):
with substitute_extensions(session, [extension]) as sess:
session.flush.side_effect = AttributeError
assert session.flush.call_count == 1
assert session.close.call_count == 1
assert sess == session
assert sess._kwargs['extensions'] == [extension]
with td.raises(AttributeError), substitute_extensions(session, [extension]) as sess:
session.flush.side_effect = AttributeError
assert session.flush.call_count == 1
assert session.close.call_count == 1
assert sess == session
assert sess._kwargs['extensions'] == [extension]
assert session.flush.call_count == 2
assert session.close.call_count == 1
assert session._kwargs['extensions'] == []
Expand Down
2 changes: 1 addition & 1 deletion ForgeActivity/forgeactivity/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ def _get_activities_data(self, **kw):
followee=followee,
following=following,
timeline=filtered_timeline,
noindex=False if filtered_timeline else True,
noindex=not filtered_timeline,
page=page,
limit=limit,
has_more=has_more,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@ def setup_method(self, method):

def test_index(self):
reviews = feedback_main.RootController().index()
assert True if not reviews['user_has_already_reviewed'] else False
assert bool(not reviews['user_has_already_reviewed'])
create_feedbacks()
reviews = feedback_main.RootController().index()
assert True if reviews['user_has_already_reviewed'] else False
assert bool(reviews['user_has_already_reviewed'])

def test_feedback(self):
create_feedbacks()
Expand Down
2 changes: 1 addition & 1 deletion ForgeImporters/forgeimporters/github/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ def oauth_app_basic_auth(config):

def valid_access_token(access_token, scopes_required=None):
tok_details = access_token_details(access_token)
if not tok_details.status_code == 200:
if tok_details.status_code != 200:
return False
if scopes_required and not all(scope_req in tok_details.json()['scopes']
for scope_req in scopes_required):
Expand Down
2 changes: 1 addition & 1 deletion ForgeTracker/forgetracker/tracker_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -1329,7 +1329,7 @@ def get_changed(self):
if key in self.originals:
orig_value = self.originals[key]
curr_value = self.data[key]
if not orig_value == curr_value:
if orig_value != curr_value:
t.append((key, (orig_value, curr_value)))
return t

Expand Down
5 changes: 5 additions & 0 deletions ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ lint.select = [
"PLC",
"PLE",
"PLW",
"SIM101",
"SIM103",
"SIM117",
"SIM2",
"SIM401",
"FA", # future annotations (to ensure compatibility with `target-version`)
]

Expand Down

0 comments on commit 0ca5177

Please sign in to comment.