This is an automated email from the ASF dual-hosted git repository. gcruz pushed a commit to branch pep8-cleanup in repository https://gitbox.apache.org/repos/asf/allura.git
commit 85a8e249059d67b4a5b7573f6ae679de5aa26d66 Author: Guillermo Cruz <guillermo.c...@slashdotmedia.com> AuthorDate: Mon May 13 14:53:15 2024 -0600 code cleanup using autopep8 --- Allura/allura/app.py | 3 ++- Allura/allura/command/script.py | 4 ++-- Allura/allura/command/taskd.py | 4 ++-- Allura/allura/config/app_cfg.py | 1 + Allura/allura/controllers/auth.py | 6 ++--- Allura/allura/controllers/repository.py | 2 +- Allura/allura/controllers/rest.py | 16 ++++++------- Allura/allura/controllers/site_admin.py | 4 ++-- Allura/allura/controllers/task.py | 1 - Allura/allura/eventslistener.py | 1 + Allura/allura/ext/admin/widgets.py | 4 ++-- Allura/allura/lib/app_globals.py | 7 +++--- Allura/allura/lib/custom_middleware.py | 12 ++++++---- Allura/allura/lib/helpers.py | 3 ++- Allura/allura/lib/macro.py | 6 ++--- Allura/allura/lib/mail_util.py | 2 ++ Allura/allura/lib/package_path_loader.py | 4 ++-- Allura/allura/lib/phone/nexmo.py | 2 +- Allura/allura/lib/plugin.py | 2 ++ Allura/allura/lib/repository.py | 4 ++-- Allura/allura/lib/search.py | 10 ++++---- Allura/allura/lib/security.py | 7 ++++-- Allura/allura/lib/utils.py | 8 +++---- Allura/allura/lib/validators.py | 7 +++--- Allura/allura/lib/widgets/discuss.py | 20 ++++++++-------- Allura/allura/lib/widgets/forms.py | 28 +++++++++++----------- Allura/allura/lib/widgets/user_profile.py | 6 ++--- Allura/allura/model/filesystem.py | 4 ++-- Allura/allura/model/oauth.py | 3 +-- Allura/allura/model/project.py | 5 ++-- Allura/allura/model/repository.py | 2 +- Allura/allura/model/stats.py | 4 ++-- Allura/allura/model/types.py | 1 + Allura/allura/scripts/create_sitemap_files.py | 4 ++-- Allura/allura/scripts/disable_users.py | 1 + Allura/allura/scripts/scripttask.py | 2 -- Allura/allura/tasks/index_tasks.py | 2 ++ Allura/allura/tasks/notification_tasks.py | 2 ++ Allura/allura/tasks/repo_tasks.py | 3 +-- Allura/allura/tests/functional/test_auth.py | 11 ++++----- Allura/allura/tests/functional/test_discuss.py | 5 ---- Allura/allura/tests/functional/test_gravatar.py | 4 ++-- .../allura/tests/functional/test_neighborhood.py | 2 +- Allura/allura/tests/functional/test_rest.py | 8 +++---- Allura/allura/tests/functional/test_site_admin.py | 6 ++--- .../allura/tests/functional/test_trovecategory.py | 4 ++-- Allura/allura/tests/model/test_neighborhood.py | 8 +++---- Allura/allura/tests/model/test_notification.py | 10 ++++---- Allura/allura/tests/model/test_project.py | 4 ++-- Allura/allura/tests/model/test_repo.py | 6 ++--- Allura/allura/tests/model/test_timeline.py | 2 +- Allura/allura/tests/test_app.py | 5 ++-- Allura/allura/tests/test_commands.py | 3 ++- Allura/allura/tests/test_helpers.py | 1 + Allura/allura/tests/test_mail_util.py | 10 ++++---- Allura/allura/tests/test_middlewares.py | 14 +++++------ Allura/allura/tests/test_security.py | 4 ++-- Allura/allura/tests/test_webhooks.py | 12 +++++----- .../allura/tests/unit/test_ldap_auth_provider.py | 4 ++-- Allura/allura/tests/unit/test_project.py | 2 +- Allura/allura/webhooks.py | 6 ++--- AlluraTest/alluratest/controller.py | 6 ++--- .../forgeactivity/tests/functional/test_rest.py | 3 +-- ForgeBlog/forgeblog/tests/functional/test_feeds.py | 8 +++---- ForgeBlog/forgeblog/tests/test_app.py | 8 +++---- ForgeBlog/forgeblog/tests/test_commands.py | 3 ++- .../forgediscussion/tests/functional/test_forum.py | 8 +++---- .../tests/functional/test_forum_admin.py | 3 +-- .../tests/functional/test_import.py | 6 ++--- ForgeGit/forgegit/model/git_repo.py | 7 +++--- .../forgegit/tests/functional/test_controllers.py | 2 +- ForgeGit/forgegit/tests/model/test_repository.py | 8 +++---- ForgeImporters/forgeimporters/base.py | 4 ++-- ForgeImporters/forgeimporters/github/__init__.py | 4 +++- .../forgeimporters/github/tests/test_wiki.py | 4 ++-- .../forgeimporters/tests/github/test_extractor.py | 1 - ForgeImporters/forgeimporters/tests/test_base.py | 4 ++-- ForgeLink/forgelink/link_main.py | 2 +- ForgeLink/forgelink/tests/functional/test_root.py | 6 ++--- ForgeSVN/forgesvn/model/svn.py | 11 +++++---- .../forgesvn/tests/model/test_svnimplementation.py | 4 ++-- .../forgetracker/tests/functional/test_rest.py | 4 ++-- .../forgetracker/tests/functional/test_root.py | 4 ++-- .../forgetracker/tests/unit/test_search.py | 8 +++---- ForgeTracker/forgetracker/tracker_main.py | 4 ++-- ForgeTracker/forgetracker/widgets/ticket_form.py | 6 ++--- ForgeUserStats/forgeuserstats/model/stats.py | 1 + ForgeWiki/forgewiki/tests/functional/test_rest.py | 6 ++--- ForgeWiki/forgewiki/tests/test_app.py | 4 ++-- ForgeWiki/forgewiki/wiki_main.py | 2 +- .../033-change-comment-anon-permissions.py | 6 ++--- scripts/perf/generate-projects.py | 6 +++-- scripts/perf/parse_timings.py | 2 +- scripts/scrub-allura-data.py | 6 ++--- scripts/trac_import.py | 11 ++++----- 95 files changed, 263 insertions(+), 247 deletions(-) diff --git a/Allura/allura/app.py b/Allura/allura/app.py index 55cb7d299..2376f1102 100644 --- a/Allura/allura/app.py +++ b/Allura/allura/app.py @@ -801,7 +801,7 @@ class Application(ActivityObject): def make_dir_for_attachments(self, path): if not os.path.exists(path): - os.makedirs(path) + os.makedirs(path) def save_attachments(self, path, attachments): self.make_dir_for_attachments(path) @@ -835,6 +835,7 @@ class Application(ActivityObject): class AdminControllerMixin: """Provides common functionality admin controllers need""" + def _before(self, *remainder, **params): # Display app's sidebar on admin page, instead of :class:`AdminApp`'s c.app = self.app diff --git a/Allura/allura/command/script.py b/Allura/allura/command/script.py index 78edd8746..a13e121ff 100644 --- a/Allura/allura/command/script.py +++ b/Allura/allura/command/script.py @@ -95,8 +95,8 @@ class SetToolAccessCommand(base.Command): for s in self.args[3:]: s = s.lower() if s == 'production': - print ('All projects always have access to prodcution tools,' - ' so removing from list.') + print('All projects always have access to prodcution tools,' + ' so removing from list.') continue if s not in ('alpha', 'beta'): print('Unknown tool status %s' % s) diff --git a/Allura/allura/command/taskd.py b/Allura/allura/command/taskd.py index 782c216cd..2268d0426 100644 --- a/Allura/allura/command/taskd.py +++ b/Allura/allura/command/taskd.py @@ -136,11 +136,11 @@ class TaskdCommand(base.Command): waitfunc=waitfunc, only=only) if self.task: - with(proctitle("taskd:{}:{}".format( + with (proctitle("taskd:{}:{}".format( self.task.task_name, self.task._id))): # Build the (fake) request request_path = '/--{}--/{}/'.format(self.task.task_name, - self.task._id) + self.task._id) r = Request.blank(request_path, base_url=tg.config['base_url'].rstrip( '/') + request_path, diff --git a/Allura/allura/config/app_cfg.py b/Allura/allura/config/app_cfg.py index e0a5cfb4c..dd4b975ef 100644 --- a/Allura/allura/config/app_cfg.py +++ b/Allura/allura/config/app_cfg.py @@ -61,6 +61,7 @@ class MinimalApplicationConfiguratorNoRegistry(ApplicationConfigurator): Copied from tg.MinimalApplicationConfigurator but without the registry since we use RegistryManager in a specific part of our middleware already """ + def __init__(self): super().__init__() self.register(MimeTypesConfigurationComponent, after=False) diff --git a/Allura/allura/controllers/auth.py b/Allura/allura/controllers/auth.py index 1b9ea3d55..cade4f936 100644 --- a/Allura/allura/controllers/auth.py +++ b/Allura/allura/controllers/auth.py @@ -1447,9 +1447,9 @@ class OAuth2Controller(BaseController): @validate(F.oauth2_application_form, error_handler=index) def register(self, application_name=None, application_description=None, redirect_url=None, **kw): M.OAuth2ClientApp(name=application_name, - description=application_description, - redirect_uris=[redirect_url], - user_id=c.user._id) + description=application_description, + redirect_uris=[redirect_url], + user_id=c.user._id) flash('Oauth2 Client registered') redirect('.') diff --git a/Allura/allura/controllers/repository.py b/Allura/allura/controllers/repository.py index 351d3642f..8138fd57b 100644 --- a/Allura/allura/controllers/repository.py +++ b/Allura/allura/controllers/repository.py @@ -737,7 +737,7 @@ class CommitBrowser(BaseController): # ('removed', u'bbb.txt', 'tree', None), # ('removed', u'ddd.txt', 'tree', None), # ('changed', u'ccc.txt', 'blob', True)] - result['artifacts'].sort(key=lambda x: x[1]['old'] if(isinstance(x[1], dict)) else x[1]) + result['artifacts'].sort(key=lambda x: x[1]['old'] if (isinstance(x[1], dict)) else x[1]) return result @expose('jinja:allura:templates/repo/commit_basic.html') diff --git a/Allura/allura/controllers/rest.py b/Allura/allura/controllers/rest.py index b1bafea33..bb0496a8a 100644 --- a/Allura/allura/controllers/rest.py +++ b/Allura/allura/controllers/rest.py @@ -338,12 +338,12 @@ class Oauth2Validator(oauthlib.oauth2.RequestValidator): M.OAuth2AccessToken.query.remove({'client_id': request.client_id, 'user_id': c.user._id}) bearer_token = M.OAuth2AccessToken( - client_id = request.client_id, - scopes = token.get('scope', []), - access_token = token.get('access_token'), - refresh_token = token.get('refresh_token'), - expires_at = datetime.utcnow() + timedelta(seconds=token.get('expires_in')), - user_id = authorization_code.user_id + client_id=request.client_id, + scopes=token.get('scope', []), + access_token=token.get('access_token'), + refresh_token=token.get('refresh_token'), + expires_at=datetime.utcnow() + timedelta(seconds=token.get('expires_in')), + user_id=authorization_code.user_id ) session(bearer_token).flush() @@ -501,7 +501,7 @@ class Oauth2Negotiator: if not valid: raise exc.HTTPUnauthorized - bearer_token_prefix = 'Bearer ' # noqa: S105 + bearer_token_prefix = 'Bearer ' # noqa: S105 auth_header = req.headers.get('Authorization') if auth_header and auth_header.startswith(bearer_token_prefix): access_token = auth_header[len(bearer_token_prefix):] @@ -512,7 +512,6 @@ class Oauth2Negotiator: token.last_access = datetime.utcnow() return token - @expose('jinja:allura:templates/oauth2_authorize.html') @without_trailing_slash def authorize(self, **kwargs): @@ -524,7 +523,6 @@ class Oauth2Negotiator: decoded_body = str(request.body, 'utf-8') json_body = json.loads(decoded_body) - scopes, credentials = self.server.validate_authorization_request(uri=request.url, http_method=request.method, headers=request.headers, body=json_body) client_id = request.params.get('client_id') diff --git a/Allura/allura/controllers/site_admin.py b/Allura/allura/controllers/site_admin.py index 252aea353..22b1c3fab 100644 --- a/Allura/allura/controllers/site_admin.py +++ b/Allura/allura/controllers/site_admin.py @@ -288,7 +288,7 @@ class SiteAdminController: def convert_fields(obj): # throw the type away (e.g. '_s' from 'url_s') result = {} - for k,val in obj.items(): + for k, val in obj.items(): name = k.rsplit('_', 1) if len(name) == 2: name = name[0] @@ -776,4 +776,4 @@ class StatsSiteAdminExtension(SiteAdminExtension): def update_sidebar_menu(self, links): links.append(SitemapEntry('Stats', '/nf/admin/stats', - ui_icon=g.icons['stats'])) + ui_icon=g.icons['stats'])) diff --git a/Allura/allura/controllers/task.py b/Allura/allura/controllers/task.py index dfaf4186f..66b572546 100644 --- a/Allura/allura/controllers/task.py +++ b/Allura/allura/controllers/task.py @@ -16,7 +16,6 @@ # under the License. - import six diff --git a/Allura/allura/eventslistener.py b/Allura/allura/eventslistener.py index f9f7431d0..0a0af38ae 100644 --- a/Allura/allura/eventslistener.py +++ b/Allura/allura/eventslistener.py @@ -47,6 +47,7 @@ class EventsListener: def addUserToOrganization(self, newMembership): pass + '''This class simply allows to iterate through all the registered listeners, so that all of them are called to update statistics.''' diff --git a/Allura/allura/ext/admin/widgets.py b/Allura/allura/ext/admin/widgets.py index ac0f0c67c..3e3538920 100644 --- a/Allura/allura/ext/admin/widgets.py +++ b/Allura/allura/ext/admin/widgets.py @@ -127,7 +127,7 @@ class ScreenshotAdmin(ff.ForgeFormResponsive): ff.ForgeForm.defaults, enctype='multipart/form-data', submit_text='Upload', - ) + ) @property def fields(self): @@ -137,7 +137,7 @@ class ScreenshotAdmin(ff.ForgeFormResponsive): attrs={ 'accept': 'image/*', 'required': 'true', - }), + }), ew.InputField(name='caption', field_type="text", label='Caption', diff --git a/Allura/allura/lib/app_globals.py b/Allura/allura/lib/app_globals.py index 0bdf8be08..d4bf931a4 100644 --- a/Allura/allura/lib/app_globals.py +++ b/Allura/allura/lib/app_globals.py @@ -148,7 +148,7 @@ class ForgeMarkdown: except ValueError: threshold = None log.warning('Skipping Markdown caching - The value for config param ' - '"markdown_cache_threshold" must be a float.') + '"markdown_cache_threshold" must be a float.') # Check if contains macro and never cache if self.uncacheable_macro_regex.search(source_text): @@ -178,7 +178,7 @@ class ForgeMarkdown: log.exception('Could not get session for %s', artifact) else: with utils.skip_mod_date(artifact.__class__), \ - utils.skip_last_updated(artifact.__class__): + utils.skip_last_updated(artifact.__class__): sess.flush(artifact) return html @@ -588,7 +588,7 @@ class Globals: return asbool(config['user_profile_url_with_profile_path']) def user_profile_disabled_tools(self): - return aslist(config.get('user_prefs.disabled_tools',''), sep=',') + return aslist(config.get('user_prefs.disabled_tools', ''), sep=',') def app_static(self, resource, app=None): base = config['static.url_base'] @@ -666,6 +666,7 @@ class Globals: def commit_statuses_enabled(self): return asbool(config['scm.commit_statuses']) + class Icon: def __init__(self, css, title=None): diff --git a/Allura/allura/lib/custom_middleware.py b/Allura/allura/lib/custom_middleware.py index e5c64d497..4a09325a5 100644 --- a/Allura/allura/lib/custom_middleware.py +++ b/Allura/allura/lib/custom_middleware.py @@ -496,8 +496,9 @@ class ContentSecurityPolicyMiddleware: if environ.get('csp_form_actions'): srcs += ' ' + ' '.join(environ['csp_form_actions']) - oauth_endpoints = ('/rest/oauth2/authorize', '/rest/oauth2/do_authorize', '/rest/oauth/authorize', '/rest/oauth/do_authorize') - if not req.path.startswith(oauth_endpoints): # Do not enforce CSP for OAuth1 and OAuth2 authorization + oauth_endpoints = ( + '/rest/oauth2/authorize', '/rest/oauth2/do_authorize', '/rest/oauth/authorize', '/rest/oauth/do_authorize') + if not req.path.startswith(oauth_endpoints): # Do not enforce CSP for OAuth1 and OAuth2 authorization if asbool(self.config.get('csp.form_actions_enforce', False)): rules.add(f"form-action {srcs}") else: @@ -516,7 +517,8 @@ class ContentSecurityPolicyMiddleware: if asbool(self.config.get('csp.script_src_enforce', False)): rules.add(f"script-src {script_srcs} {self.config.get('csp.script_src.extras','')} 'report-sample'") else: - report_rules.add(f"script-src {script_srcs} {self.config.get('csp.script_src.extras','')} 'report-sample'") + report_rules.add( + f"script-src {script_srcs} {self.config.get('csp.script_src.extras', '')} 'report-sample'") if self.config.get('csp.script_src_attr'): if asbool(self.config.get('csp.script_src_attr_enforce', False)): @@ -581,6 +583,7 @@ def _call_wsgi_application(application, environ): """ captured = [] output = [] + def _start_response(status, headers, exc_info=None): captured[:] = [status, headers, exc_info] return output.append @@ -607,6 +610,7 @@ class StatusCodeRedirect: purposely return a 401), set ``environ['tg.status_code_redirect'] = False`` in the application. """ + def __init__(self, app, errors=(400, 401, 403, 404), path='/error/document'): """Initialize the ErrorRedirect @@ -626,7 +630,7 @@ class StatusCodeRedirect: def __call__(self, environ, start_response): status, headers, app_iter, exc_info = _call_wsgi_application(self.app, environ) if status[:3] in self.errors and \ - 'tg.status_code_redirect' not in environ and self.error_path: + 'tg.status_code_redirect' not in environ and self.error_path: # Create a response object environ['tg.original_response'] = Response(status=status, headerlist=headers, app_iter=app_iter) environ['tg.original_request'] = Request(environ) diff --git a/Allura/allura/lib/helpers.py b/Allura/allura/lib/helpers.py index 26d031446..c2e83eec2 100644 --- a/Allura/allura/lib/helpers.py +++ b/Allura/allura/lib/helpers.py @@ -1068,7 +1068,7 @@ def urlopen(url: str | urllib.request.Request, retries=3, codes=(408, 500, 502, """ if isinstance(url, urllib.request.Request): - url_str = url.full_url + url_str = url.full_url else: url_str = url if not url_str.startswith(('http://', 'https://')): @@ -1375,6 +1375,7 @@ def pluralize_tool_name(tool_name: string, count: int): return f"{tool_name}{'s'[:count^1]}" return tool_name + def parse_fediverse_address(username: str): pieces = username.split('@') return f'https://{pieces[-1]}/@{pieces[1]}' diff --git a/Allura/allura/lib/macro.py b/Allura/allura/lib/macro.py index 3d2970747..f0e32e150 100644 --- a/Allura/allura/lib/macro.py +++ b/Allura/allura/lib/macro.py @@ -103,8 +103,8 @@ class parse: return response except (ValueError, TypeError) as ex: log.warning('macro error. Upwards stack is %s', - ''.join(traceback.format_stack()), - exc_info=True) + ''.join(traceback.format_stack()), + exc_info=True) msg = html.escape(f'[[{s}]] ({repr(ex)})') return '\n<div class="error"><pre><code>%s</code></pre></div>' % msg @@ -184,7 +184,7 @@ def project_blog_posts(max_number=5, sort='timestamp', summary=False, mount_poin ago=h.ago(post.timestamp), description=summary and ' ' or g.markdown.cached_convert(post, 'text')) for post in posts if security.has_access(post, 'read', project=post.app.project) and - security.has_access(post.app.project, 'read', project=post.app.project) + security.has_access(post.app.project, 'read', project=post.app.project) ] posts = BlogPosts(posts=output) g.resource_manager.register(posts) diff --git a/Allura/allura/lib/mail_util.py b/Allura/allura/lib/mail_util.py index 285c12d73..d086dc9f4 100644 --- a/Allura/allura/lib/mail_util.py +++ b/Allura/allura/lib/mail_util.py @@ -50,6 +50,7 @@ MAX_MAIL_LINE_OCTETS = 990 email_policy = email.policy.SMTP + email.policy.strict + def Header(text, *more_text) -> str: ''' Helper to make sure we encode headers properly @@ -69,6 +70,7 @@ def Header(text, *more_text) -> str: hdr_text += ' ' + m return hdr_text + def AddrHeader(fromaddr) -> str: '''Accepts any of: Header() instance diff --git a/Allura/allura/lib/package_path_loader.py b/Allura/allura/lib/package_path_loader.py index 9be2d9445..58416a827 100644 --- a/Allura/allura/lib/package_path_loader.py +++ b/Allura/allura/lib/package_path_loader.py @@ -145,7 +145,7 @@ class PackagePathLoader(jinja2.BaseLoader): # TODO: How does one handle project-theme? if default_paths is None: default_paths = [ - #['project-theme', None], + # ['project-theme', None], ['site-theme', None], ['allura', '/'], ] @@ -237,7 +237,7 @@ class PackagePathLoader(jinja2.BaseLoader): This mutates paths. """ - p_idx = lambda n: [e[0] for e in paths].index(n) + def p_idx(n): return [e[0] for e in paths].index(n) for target, replacement in rules.items(): try: removed = paths.pop(p_idx(replacement)) diff --git a/Allura/allura/lib/phone/nexmo.py b/Allura/allura/lib/phone/nexmo.py index 630d7b94f..fa1443eb7 100644 --- a/Allura/allura/lib/phone/nexmo.py +++ b/Allura/allura/lib/phone/nexmo.py @@ -89,7 +89,7 @@ class NexmoPhoneService(PhoneService): return self.error() if resp.get('status') == '0': return self.ok(request_id=resp.get('request_id')) - return self.error(code=resp.get('status'), msg=resp.get('error_text'), number=params.get('number','')) + return self.error(code=resp.get('status'), msg=resp.get('error_text'), number=params.get('number', '')) def verify(self, number): url = urljoin(self.BASE_URL, 'verify') diff --git a/Allura/allura/lib/plugin.py b/Allura/allura/lib/plugin.py index 879c82fd3..5f3add94c 100644 --- a/Allura/allura/lib/plugin.py +++ b/Allura/allura/lib/plugin.py @@ -635,6 +635,7 @@ class LocalAuthenticationProvider(AuthenticationProvider): d = self.user_registration_date(user) return d + def ldap_conn_staysopen(who=None, cred=None): ''' You must call .unbind_s() when done with this @@ -644,6 +645,7 @@ def ldap_conn_staysopen(who=None, cred=None): cred or config['auth.ldap.admin_password']) return con + @contextmanager def ldap_conn(who=None, cred=None): ''' diff --git a/Allura/allura/lib/repository.py b/Allura/allura/lib/repository.py index bd7bf0a6e..d4d21ff9f 100644 --- a/Allura/allura/lib/repository.py +++ b/Allura/allura/lib/repository.py @@ -156,7 +156,7 @@ class RepositoryApp(Application): self.repo.push_upstream_context() except Exception: log.warning('Could not get upstream repo (perhaps it is gone) for: %s %s', - self.repo, self.repo.upstream_repo.name, exc_info=True) + self.repo, self.repo.upstream_repo.name, exc_info=True) else: has_upstream_repo = True @@ -218,7 +218,7 @@ class RepositoryApp(Application): for b in tags[:max_tags]: links.append(SitemapEntry( b.name, - h.urlquote(self.repo.url_for_commit(b.name) + 'tree/'), + h.urlquote(self.repo.url_for_commit(b.name) + 'tree/'), extra_html_attrs=dict(rel='nofollow'))) if len(tags) > max_tags: links.append( diff --git a/Allura/allura/lib/search.py b/Allura/allura/lib/search.py index 388384798..0489f1ac2 100644 --- a/Allura/allura/lib/search.py +++ b/Allura/allura/lib/search.py @@ -225,7 +225,7 @@ def site_admin_search(model, q, field, **kw): # escaping spaces with '\ ' isn't sufficient for display_name_t since its stored as text_general (why??) # and wouldn't handle f...@bar.com split on @ either # This should work, but doesn't for unknown reasons: q = u'{!term f=%s}%s' % (field, q) - q = q.replace(':', r'\:') # Must escape the colon for IPv6 addresses + q = q.replace(':', r'\:') # Must escape the colon for IPv6 addresses q = obj.translate_query(f'{field}:({q})', fields) kw['q.op'] = 'AND' # so that all terms within the () are required fq = ['type_s:%s' % model.type_s] @@ -314,12 +314,12 @@ def search_app(q='', fq=None, app=True, **kw): text = h.get_first(m, 'text') if title: title = (markupsafe.escape(title) - .replace('#ALLURA-HIGHLIGHT-START#', markupsafe.Markup('<strong>')) - .replace('#ALLURA-HIGHLIGHT-END#', markupsafe.Markup('</strong>'))) + .replace('#ALLURA-HIGHLIGHT-START#', markupsafe.Markup('<strong>')) + .replace('#ALLURA-HIGHLIGHT-END#', markupsafe.Markup('</strong>'))) if text: text = (markupsafe.escape(text) - .replace('#ALLURA-HIGHLIGHT-START#', markupsafe.Markup('<strong>')) - .replace('#ALLURA-HIGHLIGHT-END#', markupsafe.Markup('</strong>'))) + .replace('#ALLURA-HIGHLIGHT-START#', markupsafe.Markup('<strong>')) + .replace('#ALLURA-HIGHLIGHT-END#', markupsafe.Markup('</strong>'))) doc['title_match'] = title doc['text_match'] = text or h.get_first(doc, 'text') return doc diff --git a/Allura/allura/lib/security.py b/Allura/allura/lib/security.py index 53a675f55..0fbacf6d6 100644 --- a/Allura/allura/lib/security.py +++ b/Allura/allura/lib/security.py @@ -293,6 +293,7 @@ def is_denied(obj, permission: str, user: M.User, project: M.Project) -> bool: return False + def debug_obj(obj) -> str: if hasattr(obj, 'url'): url = obj.url @@ -384,7 +385,8 @@ def has_access(obj, permission: str, user: M.User | None = None, project: M.Proj if ace.access == M.ACE.ALLOW: # access is allowed if DEBUG: - log.debug(f"{user.username} '{permission}' granted on {debug_obj(obj)} ({debug_obj(project)})") + log.debug( + f"{user.username} '{permission}' granted on {debug_obj(obj)} ({debug_obj(project)})") return True else: # access is denied for this particular role @@ -406,7 +408,8 @@ def has_access(obj, permission: str, user: M.User | None = None, project: M.Proj result = False result = bool(result) if DEBUG: - log.debug(f"{user.username} '{permission}' {result} from parent(s) on {debug_obj(obj)} ({debug_obj(project)})") + log.debug( + f"{user.username} '{permission}' {result} from parent(s) on {debug_obj(obj)} ({debug_obj(project)})") return result return TruthyCallable(predicate) diff --git a/Allura/allura/lib/utils.py b/Allura/allura/lib/utils.py index de33f559b..bba85e618 100644 --- a/Allura/allura/lib/utils.py +++ b/Allura/allura/lib/utils.py @@ -201,9 +201,9 @@ def chunked_list(l, n): def chunked_iter(iterable, max_size): - '''return iterable 'chunks' from the iterable of max size max_size''' + """return iterable 'chunks' from the iterable of max size max_size""" eiter = enumerate(iterable) - keyfunc = lambda i_x: i_x[0] // max_size + def keyfunc(i_x): return i_x[0] // max_size for _, chunk in groupby(eiter, keyfunc): yield (x for i, x in chunk) @@ -247,11 +247,11 @@ class AntiSpam: @staticmethod def _wrap(s): - '''Encode bytes to make it HTML id-safe (starts with alpha, includes + """Encode bytes to make it HTML id-safe (starts with alpha, includes only digits, hyphens, underscores, colons, and periods). Luckily, base64 encoding doesn't use hyphens, underscores, colons, nor periods, so we'll use these characters to replace its plus, slash, equals, and newline. - ''' + """ s = base64.b64encode(six.ensure_binary(s)) s = s.rstrip(b'=\n') s = s.replace(b'+', b'-').replace(b'/', b'_') diff --git a/Allura/allura/lib/validators.py b/Allura/allura/lib/validators.py index ebc72cba9..2f2776b39 100644 --- a/Allura/allura/lib/validators.py +++ b/Allura/allura/lib/validators.py @@ -335,7 +335,7 @@ class UserMapJsonFile(JsonFile): value = super(self.__class__, self)._convert_to_python(value, state) try: for k, v in value.items(): - if not(isinstance(k, str) and isinstance(v, str)): + if not (isinstance(k, str) and isinstance(v, str)): raise return json.dumps(value) if self.as_string else value except Exception: @@ -489,8 +489,10 @@ class IconValidator(fev.FancyValidator): return value + FEDIVERSE_REGEX = r'^@[\w-]+@[\w-]+(\.[\w-]+)+$' + class LinkedinValidator(fev.FancyValidator): def _convert_to_python(self, value, state): if value.startswith('@') and not re.match(FEDIVERSE_REGEX, value): @@ -534,7 +536,6 @@ class FediverseValidator(fev.FancyValidator): value = f'{url.path.replace("/", "")}@{url.netloc}' if not re.match(FEDIVERSE_REGEX, value): raise fe.Invalid('Invalid Mastodon address', value, state) - elif not re.match(FEDIVERSE_REGEX , value): + elif not re.match(FEDIVERSE_REGEX, value): raise fe.Invalid('Invalid Mastodon address', value, state) return value - diff --git a/Allura/allura/lib/widgets/discuss.py b/Allura/allura/lib/widgets/discuss.py index feef86db8..302a8af40 100644 --- a/Allura/allura/lib/widgets/discuss.py +++ b/Allura/allura/lib/widgets/discuss.py @@ -111,17 +111,17 @@ class PostFilter(ff.ForgeForm): name='page', validator=fev.Int()), ew.SingleSelectField( - name='status', - label='Filter By Status', - options=[ - ew.Option(py_value='-', label='Any'), - ew.Option(py_value='spam', label='Spam'), - ew.Option(py_value='pending', - label='Pending moderation'), - ew.Option(py_value='ok', label='Ok')], - if_missing='pending'), + name='status', + label='Filter By Status', + options=[ + ew.Option(py_value='-', label='Any'), + ew.Option(py_value='spam', label='Spam'), + ew.Option(py_value='pending', + label='Pending moderation'), + ew.Option(py_value='ok', label='Ok')], + if_missing='pending'), ew.InputField(name='username', - label='Filter by Username'), + label='Filter by Username'), ew.SubmitButton(label='Filter Posts') ] diff --git a/Allura/allura/lib/widgets/forms.py b/Allura/allura/lib/widgets/forms.py index 65121ed5c..1c737ba5d 100644 --- a/Allura/allura/lib/widgets/forms.py +++ b/Allura/allura/lib/widgets/forms.py @@ -257,7 +257,7 @@ class PersonalDataForm(ForgeForm): [ew.Option(py_value=c, label=n, selected=False) for c, n in sorted(list(country_names.items()), key=lambda k_v: k_v[1])], - ), + ), ew.TextField( name='city', label='City of residence', @@ -777,8 +777,8 @@ class RegistrationForm(ForgeForm): fields += [ ew.PasswordField( name='pw', - label='New Password', - attrs=dict(minlength=asint(tg.config.get('auth.min_password_len', 6)), maxlength=asint(tg.config.get('auth.max_password_len', 30))), + label='New Password', attrs=dict(minlength=asint(tg.config.get('auth.min_password_len', 6)), + maxlength=asint(tg.config.get('auth.max_password_len', 30))), validator=V.UnicodeString( not_empty=True, min=asint(tg.config.get('auth.min_password_len', 6)), @@ -859,17 +859,17 @@ class NeighborhoodOverviewForm(ForgeForm): if inp['value'] is None or inp['value'] == '': empty_val = True display += Markup('<tr><td class="left"><label>%(label)s</label></td>' - '<td><input type="checkbox" name="%(ctx_name)s-%(inp_name)s-def" %(def_checked)s>default</td>' - '<td class="right"><div class="%(ctx_name)s-%(inp_name)s-inp"><table class="input_inner">' - '<tr><td><input type="text" class="%(inp_type)s" name="%(ctx_name)s-%(inp_name)s" ' - 'value="%(inp_value)s"></td><td>%(inp_additional)s</td></tr></table></div></td></tr>\n') % { - 'ctx_name': ctx['name'], - 'inp_name': inp['name'], - 'inp_value': inp['value'], - 'label': inp['label'], - 'inp_type': inp['type'], - 'def_checked': 'checked="checked"' if empty_val else '', - 'inp_additional': additional_inputs} + '<td><input type="checkbox" name="%(ctx_name)s-%(inp_name)s-def" %(def_checked)s>default</td>' + '<td class="right"><div class="%(ctx_name)s-%(inp_name)s-inp"><table class="input_inner">' + '<tr><td><input type="text" class="%(inp_type)s" name="%(ctx_name)s-%(inp_name)s" ' + 'value="%(inp_value)s"></td><td>%(inp_additional)s</td></tr></table></div></td></tr>\n') % { + 'ctx_name': ctx['name'], + 'inp_name': inp['name'], + 'inp_value': inp['value'], + 'label': inp['label'], + 'inp_type': inp['type'], + 'def_checked': 'checked="checked"' if empty_val else '', + 'inp_additional': additional_inputs} display += Markup('</table>') if ctx['errors'] and field.show_errors and not ignore_errors: diff --git a/Allura/allura/lib/widgets/user_profile.py b/Allura/allura/lib/widgets/user_profile.py index 830d23709..6d1eb3588 100644 --- a/Allura/allura/lib/widgets/user_profile.py +++ b/Allura/allura/lib/widgets/user_profile.py @@ -148,9 +148,9 @@ class ProjectsSectionBase(SectionBase): project for project in self.user.my_projects() if project != c.project - and (self.user == c.user or h.has_access(project, 'read')) - and not project.is_nbhd_project - and not project.is_user_project] + and (self.user == c.user or h.has_access(project, 'read')) + and not project.is_nbhd_project + and not project.is_user_project] def prepare_context(self, context): context['projects'] = self.get_projects() diff --git a/Allura/allura/model/filesystem.py b/Allura/allura/model/filesystem.py index bd5da977b..7926cb68a 100644 --- a/Allura/allura/model/filesystem.py +++ b/Allura/allura/model/filesystem.py @@ -195,13 +195,13 @@ class File(MappedClass): format = image.format save_anim = False - if format == 'BMP' and convert_bmp: # use jpg format if bitmap is provided + if format == 'BMP' and convert_bmp: # use jpg format if bitmap is provided format = 'PNG' content_type = 'image/png' filename = re.sub('.bmp$', '.png', filename, flags=re.IGNORECASE) if format == 'GIF': - save_anim = True # save all frames if GIF is provided + save_anim = True # save all frames if GIF is provided if save_original: original_meta = original_meta or {} diff --git a/Allura/allura/model/oauth.py b/Allura/allura/model/oauth.py index 6ce08776a..0e9b752c8 100644 --- a/Allura/allura/model/oauth.py +++ b/Allura/allura/model/oauth.py @@ -176,7 +176,6 @@ class OAuth2ClientApp(MappedClass): user = RelationProperty('User') - @classmethod def for_user(cls, user=None): if user is None: @@ -251,4 +250,4 @@ def dummy_oauths(): api_key=Oauth1Validator().dummy_access_token, user_id=None, ) - session(dummy_access_tok).flush(dummy_access_tok) \ No newline at end of file + session(dummy_access_tok).flush(dummy_access_tok) diff --git a/Allura/allura/model/project.py b/Allura/allura/model/project.py index c302e2487..4d673ae2c 100644 --- a/Allura/allura/model/project.py +++ b/Allura/allura/model/project.py @@ -199,6 +199,7 @@ class ProjectNameFieldProperty(FieldProperty): Particularly nice if the username and user-project name don't match exactly. (This is a python "descriptor") """ + def __get__(self, instance, cls=None): if instance: owning_user = instance.user_project_of @@ -548,7 +549,7 @@ class Project(SearchIndexable, MappedClass, ActivityNode, ActivityObject): return result def sitemap(self, excluded_tools=None, included_tools=None, - tools_only=False, per_tool_limit=SITEMAP_PER_TOOL_LIMIT, xml=False): + tools_only=False, per_tool_limit=SITEMAP_PER_TOOL_LIMIT, xml=False): """ Return the project sitemap. @@ -658,7 +659,7 @@ class Project(SearchIndexable, MappedClass, ActivityNode, ActivityObject): 'Moderate', "%s_moderate/" % self.neighborhood.url(), ui_icon="tool-admin") - }) + }) max_ordinal += 1 entries = sorted(entries, key=lambda e: e['ordinal']) diff --git a/Allura/allura/model/repository.py b/Allura/allura/model/repository.py index 0a4856ba6..c947ec1b3 100644 --- a/Allura/allura/model/repository.py +++ b/Allura/allura/model/repository.py @@ -747,7 +747,7 @@ class Repository(Artifact, ActivityObject): def forks(self): all_forks = self.query.find({'upstream_repo.name': self.url()}).all() return [fork for fork in all_forks if fork.app_config is not None - and fork.app_config.project is not None] + and fork.app_config.project is not None] def tarball(self, revision, path=None): if path: diff --git a/Allura/allura/model/stats.py b/Allura/allura/model/stats.py index 92b74b9cd..038a6afbf 100644 --- a/Allura/allura/model/stats.py +++ b/Allura/allura/model/stats.py @@ -179,8 +179,8 @@ class Stats(MappedClass): return {} entry = self.general[i].messages by_type = {el.messagetype: dict(created=el.created, - modified=el.modified) - for el in entry} + modified=el.modified) + for el in entry} return by_type def getTicketsByCategory(self): diff --git a/Allura/allura/model/types.py b/Allura/allura/model/types.py index 8a7c15cb5..5ed80ffd8 100644 --- a/Allura/allura/model/types.py +++ b/Allura/allura/model/types.py @@ -111,4 +111,5 @@ class ACL(S.Array): if clear_reason(a) == ace_without_reason: return a + DENY_ALL = ACE.deny(EVERYONE, ALL_PERMISSIONS) diff --git a/Allura/allura/scripts/create_sitemap_files.py b/Allura/allura/scripts/create_sitemap_files.py index 624f65d09..36030c8a2 100644 --- a/Allura/allura/scripts/create_sitemap_files.py +++ b/Allura/allura/scripts/create_sitemap_files.py @@ -117,8 +117,8 @@ class CreateSitemapFiles(ScriptTask): 'date': p.last_updated.strftime("%Y-%m-%d")}) except Exception as e: - print("Error creating sitemap for project '%s': %s" %\ - (p.shortname, e)) + print("Error creating sitemap for project '%s': %s" % + (p.shortname, e)) creds.clear() if len(locs) >= options.urls_per_file: write_sitemap(locs[:options.urls_per_file], file_count) diff --git a/Allura/allura/scripts/disable_users.py b/Allura/allura/scripts/disable_users.py index 6c6f8b3ce..a5a2f0f99 100644 --- a/Allura/allura/scripts/disable_users.py +++ b/Allura/allura/scripts/disable_users.py @@ -75,5 +75,6 @@ class DisableUsers(ScriptTask): def get_parser(): return DisableUsers.parser() + if __name__ == '__main__': DisableUsers.main() diff --git a/Allura/allura/scripts/scripttask.py b/Allura/allura/scripts/scripttask.py index 0a1255c4c..5315c8b51 100644 --- a/Allura/allura/scripts/scripttask.py +++ b/Allura/allura/scripts/scripttask.py @@ -132,7 +132,6 @@ else: pass return stderr.getvalue() - class DefOptScriptTask(metaclass=MetaDefOpt): """Base class for a command-line script that is also executable as a task.""" @@ -156,4 +155,3 @@ else: def execute(cls, *args, **kwargs): """User code goes here, using defopt kwargs with type annotations""" raise NotImplementedError - diff --git a/Allura/allura/tasks/index_tasks.py b/Allura/allura/tasks/index_tasks.py index b38aec1a7..aec34c917 100644 --- a/Allura/allura/tasks/index_tasks.py +++ b/Allura/allura/tasks/index_tasks.py @@ -67,6 +67,7 @@ def check_for_dirty_ming_records(msg_prefix, ming_sessions=None): log.warning(msg_prefix + ' changed objects, causing writes back to mongo: %s', dirty_objects) + @task def add_projects(project_ids): from allura.model.project import Project @@ -177,6 +178,7 @@ def commit(): def solr_del_tool(project_id, mount_point_s): g.solr.delete(q=f'project_id_s:"{project_id}" AND mount_point_s:"{mount_point_s}"') + @contextmanager def _indexing_disabled(session): session.disable_index = session.skip_mod_date = True diff --git a/Allura/allura/tasks/notification_tasks.py b/Allura/allura/tasks/notification_tasks.py index f82063d24..8b73594c4 100644 --- a/Allura/allura/tasks/notification_tasks.py +++ b/Allura/allura/tasks/notification_tasks.py @@ -19,12 +19,14 @@ from allura.lib.decorators import task from allura.lib import utils from tg import tmpl_context as c + @task def notify(n_id, ref_ids, topic): from allura import model as M M.Mailbox.deliver(n_id, ref_ids, topic) M.Mailbox.fire_ready() + @task def send_usermentions_notification(artifact_id, text, old_text=None): from allura import model as M diff --git a/Allura/allura/tasks/repo_tasks.py b/Allura/allura/tasks/repo_tasks.py index b7185bc39..b0f24bf5f 100644 --- a/Allura/allura/tasks/repo_tasks.py +++ b/Allura/allura/tasks/repo_tasks.py @@ -192,8 +192,7 @@ def update_head_reference(fs_path, branch_name): else: # it is detached there's no refs in repo.refs default to first repo.head.reference = repo.refs[0] - #lookup for new default branch + # lookup for new default branch new_branch = [ref for ref in repo.refs if ref.name == branch_name] _ref = SymbolicReference.create(repo, 'HEAD', repo.head.reference) _ref.reference = new_branch[0] - diff --git a/Allura/allura/tests/functional/test_auth.py b/Allura/allura/tests/functional/test_auth.py index e50a34817..a5e69e2d9 100644 --- a/Allura/allura/tests/functional/test_auth.py +++ b/Allura/allura/tests/functional/test_auth.py @@ -1764,7 +1764,6 @@ To update your password on %s, please visit the following URL: r = r.follow().follow() assert 'Log Out' in r, r - @patch('allura.tasks.mail_tasks.sendsimplemail') @patch('allura.lib.helpers.gen_message_id') def test_capitalized_email_entered(self, gen_message_id, sendmail): @@ -2070,16 +2069,16 @@ class TestOAuth(TestController): class TestOAuth2(TestController): @mock.patch.dict(config, {'auth.oauth2.enabled': True}) def test_register_deregister_client(self): - #register + # register r = self.app.get('/auth/oauth2/') r = self.app.post('/auth/oauth2/register', params={'application_name': 'testoauth2', 'application_description': 'Oauth2 Test', - 'redirect_url': '', '_session_id': self.app.cookies['_session_id'], + 'redirect_url': '', '_session_id': self.app.cookies['_session_id'], }).follow() assert 'testoauth2' in r - #deregister + # deregister assert r.forms[0].action == 'do_client_action' r.forms[0].submit('deregister') r = self.app.get('/auth/oauth2/') @@ -2164,8 +2163,8 @@ class TestOAuth2(TestController): # The submit authorization for the authorization code to be created mock_credentials = dict(client_id='client_12345', redirect_uri='https://localhost/', response_type='code', state=None) r = self.app.post('/rest/oauth2/do_authorize', - params={'yes': '1', 'client_id': 'client_12345', 'response_type': 'code', - 'redirect_uri': 'https://localhost/', 'credentials': json.dumps(mock_credentials)}) + params={'yes': '1', 'client_id': 'client_12345', 'response_type': 'code', + 'redirect_uri': 'https://localhost/', 'credentials': json.dumps(mock_credentials)}) ac = M.OAuth2AuthorizationCode.query.get(client_id='client_12345') assert ac is not None diff --git a/Allura/allura/tests/functional/test_discuss.py b/Allura/allura/tests/functional/test_discuss.py index 100f9b276..0b88c576d 100644 --- a/Allura/allura/tests/functional/test_discuss.py +++ b/Allura/allura/tests/functional/test_discuss.py @@ -84,8 +84,6 @@ class TestDiscuss(TestDiscussBase): r = self.app.post('/wiki/_discuss/subscribe', params=params) assert not self._is_subscribed(user, thread) - - @patch('allura.controllers.discuss.g.spam_checker.check') @patch('allura.controllers.discuss.g.spam_checker.submit_spam') def test_post(self, submit_spam, check_spam): @@ -533,6 +531,3 @@ class TestAttachment(TestDiscussBase): # ... but moderator can self.app.get(alink, status=200, extra_environ=moderator) self.app.get(thumblink, status=200, extra_environ=moderator) - - - diff --git a/Allura/allura/tests/functional/test_gravatar.py b/Allura/allura/tests/functional/test_gravatar.py index 8c3daa154..ca2dc3b1e 100644 --- a/Allura/allura/tests/functional/test_gravatar.py +++ b/Allura/allura/tests/functional/test_gravatar.py @@ -51,7 +51,7 @@ class TestGravatar(TestController): url = urlparse(gravatar.url(email=email, rating='x')) query = parse_qs(url.query) assert (query == - {'rating': ['x']}) + {'rating': ['x']}) @patch.dict(tg.config, {'default_avatar_image': 'https://example.com/img/icon.png'}) def test_default_image(self): @@ -59,4 +59,4 @@ class TestGravatar(TestController): url = urlparse(gravatar.url(email=email)) query = parse_qs(url.query) assert (query == - {'r': ['pg'], 'd': ['https://example.com/img/icon.png']}) + {'r': ['pg'], 'd': ['https://example.com/img/icon.png']}) diff --git a/Allura/allura/tests/functional/test_neighborhood.py b/Allura/allura/tests/functional/test_neighborhood.py index e7e675920..f6f43c54c 100644 --- a/Allura/allura/tests/functional/test_neighborhood.py +++ b/Allura/allura/tests/functional/test_neighborhood.py @@ -852,7 +852,7 @@ class TestNeighborhood(TestController): r = self.app.get( '/p/check_names?neighborhood=Projects&project_unixname=test') assert (r.json == - {'project_unixname': 'This project name is taken.'}) + {'project_unixname': 'This project name is taken.'}) @td.with_tool('test/sub1', 'Wiki', 'wiki') def test_neighborhood_project(self): diff --git a/Allura/allura/tests/functional/test_rest.py b/Allura/allura/tests/functional/test_rest.py index 3cac55f34..5368b871b 100644 --- a/Allura/allura/tests/functional/test_rest.py +++ b/Allura/allura/tests/functional/test_rest.py @@ -328,7 +328,7 @@ class TestRestHome(TestRestApiBase): 'title': 'tést'.encode(), 'text': 'sometext', 'labels': '', - }) + }) r = self.api_get(h.urlquote('/rest/p/test/wiki/tést/')) assert r.status_int == 200 assert r.json['title'] == 'tést', r.json @@ -428,9 +428,9 @@ class TestRestNbhdAddProject(TestRestApiBase): M.TroveCategory(fullname="Root", trove_cat_id=1, trove_parent_id=0) M.TroveCategory(fullname="License", trove_cat_id=2, trove_parent_id=1) M.TroveCategory(fullname="Apache License V2.0", fullpath="License :: Apache License V2.0", - trove_cat_id=4, trove_parent_id=2) + trove_cat_id=4, trove_parent_id=2) M.TroveCategory(fullname="Public Domain", fullpath="License :: Public Domain", - trove_cat_id=5, trove_parent_id=2) + trove_cat_id=5, trove_parent_id=2) p_nbhd = M.Neighborhood.query.get(url_prefix='/p/') p_nbhd.features['private_projects'] = False @@ -592,7 +592,7 @@ class TestDoap(TestRestApiBase): assert user.find(self.foaf + 'name').text == 'Test Admin' assert user.find(self.foaf + 'nick').text == 'test-admin' assert (list(user.find(self.foaf + 'homepage').items())[0][1] == - 'http://localhost/u/test-admin/') + 'http://localhost/u/test-admin/') @td.with_tool('test', 'Tickets', 'bugs') @td.with_tool('test', 'Tickets', 'private-bugs') diff --git a/Allura/allura/tests/functional/test_site_admin.py b/Allura/allura/tests/functional/test_site_admin.py index f54228795..c38816b46 100644 --- a/Allura/allura/tests/functional/test_site_admin.py +++ b/Allura/allura/tests/functional/test_site_admin.py @@ -332,7 +332,7 @@ class TestSiteAdminNotifications(TestController): count = M.notification.SiteNotification.query.find().count() self.app.post(f'/nf/admin/site_notifications/{note._id}/delete') - assert M.notification.SiteNotification.query.find().count() == count -1 + assert M.notification.SiteNotification.query.find().count() == count - 1 assert M.notification.SiteNotification.query.get(_id=bson.ObjectId(note._id)) is None @@ -430,7 +430,7 @@ class TestUsersSearch(TestController): assert options == ['username', 'display_name', '__custom__'] ths = [th.text for th in r.html.findAll('th')] assert ths == ['Username', 'Display name', 'Email', 'Registered', - 'Status', 'Details'] + 'Status', 'Details'] @patch('allura.controllers.site_admin.search.site_admin_search') def test_additional_fields(self, site_admin_search): @@ -442,7 +442,7 @@ class TestUsersSearch(TestController): assert options == ['username', 'display_name', 'email_addresses', 'url', '__custom__'] ths = [th.text for th in r.html.findAll('th')] assert ths == ['Username', 'Display name', 'Email', 'Registered', - 'Status', 'url', 'Details'] + 'Status', 'url', 'Details'] class TestUserDetails(TestController): diff --git a/Allura/allura/tests/functional/test_trovecategory.py b/Allura/allura/tests/functional/test_trovecategory.py index e1a71052d..b49605944 100644 --- a/Allura/allura/tests/functional/test_trovecategory.py +++ b/Allura/allura/tests/functional/test_trovecategory.py @@ -142,7 +142,7 @@ class TestTroveCategoryController(TestController): form = r.forms[0] r = form.submit() assert ("This category contains at least one sub-category, therefore it can't be removed" in - self.webflash(r)) + self.webflash(r)) r = self.app.get('/categories/2') form = r.forms[0] @@ -173,7 +173,7 @@ class TestTroveCategoryController(TestController): form['categoryname'].value = "New Child" form.submit() - possible =M.TroveCategory.query.find(dict(fullname='New Child')).all() + possible = M.TroveCategory.query.find(dict(fullname='New Child')).all() assert len(possible) == 1 assert possible[0].fullname == 'New Child' assert possible[0].shortname == 'new-child' diff --git a/Allura/allura/tests/model/test_neighborhood.py b/Allura/allura/tests/model/test_neighborhood.py index aaa6a963c..b8297fcb3 100644 --- a/Allura/allura/tests/model/test_neighborhood.py +++ b/Allura/allura/tests/model/test_neighborhood.py @@ -53,10 +53,10 @@ class TestNeighboorhoodModel: # Check picker css styles test_css_dict = {'barontop': '#444', - 'titlebarbackground': '#555', - 'projecttitlefont': 'arial,sans-serif', - 'projecttitlecolor': '#333', - 'titlebarcolor': '#666'} + 'titlebarbackground': '#555', + 'projecttitlefont': 'arial,sans-serif', + 'projecttitlecolor': '#333', + 'titlebarcolor': '#666'} css_text = neighborhood.compile_css_for_picker(test_css_dict) assert '#333' in css_text assert '#444' in css_text diff --git a/Allura/allura/tests/model/test_notification.py b/Allura/allura/tests/model/test_notification.py index 563f90a80..920157598 100644 --- a/Allura/allura/tests/model/test_notification.py +++ b/Allura/allura/tests/model/test_notification.py @@ -220,7 +220,7 @@ class TestPostNotifications(unittest.TestCase): ThreadLocalODMSession.flush_all() assert (M.Notification.query.get() - ['from_address'] == '"Test Admin" <test-admin@users.localhost>') + ['from_address'] == '"Test Admin" <test-admin@users.localhost>') assert M.Mailbox.query.find().count() == 2 # sends the notification out into "mailboxes", and from mailboxes into @@ -241,13 +241,13 @@ class TestPostNotifications(unittest.TestCase): assert str(c.user._id) in first_destinations assert str(user2._id) in first_destinations assert (email_tasks[0].kwargs['fromaddr'] == - '"Test Admin" <test-admin@users.localhost>') + '"Test Admin" <test-admin@users.localhost>') assert (email_tasks[1].kwargs['fromaddr'] == - '"Test Admin" <test-admin@users.localhost>') + '"Test Admin" <test-admin@users.localhost>') assert (email_tasks[0].kwargs['sender'] == - 'w...@test.p.in.localhost') + 'w...@test.p.in.localhost') assert (email_tasks[1].kwargs['sender'] == - 'w...@test.p.in.localhost') + 'w...@test.p.in.localhost') assert email_tasks[0].kwargs['text'].startswith( 'Home modified by Test Admin') assert 'you indicated interest in ' in email_tasks[0].kwargs['text'] diff --git a/Allura/allura/tests/model/test_project.py b/Allura/allura/tests/model/test_project.py index fc7b2bb02..83172780f 100644 --- a/Allura/allura/tests/model/test_project.py +++ b/Allura/allura/tests/model/test_project.py @@ -141,8 +141,8 @@ class TestProjectModel: def test_set_ordinal_to_admin_tool(self): with h.push_config(c, - user=M.User.by_username('test-admin'), - project=M.Project.query.get(shortname='test')): + user=M.User.by_username('test-admin'), + project=M.Project.query.get(shortname='test')): sm = c.project.sitemap() assert sm[-1].tool_name == 'admin' diff --git a/Allura/allura/tests/model/test_repo.py b/Allura/allura/tests/model/test_repo.py index f45d0b1bf..9081319e0 100644 --- a/Allura/allura/tests/model/test_repo.py +++ b/Allura/allura/tests/model/test_repo.py @@ -38,7 +38,7 @@ class TestGitLikeTree: assert tree.blobs == {} assert tree.get_tree('dir').blobs == {} assert (tree.get_tree('dir').get_tree('dir2') - .blobs == {'file': 'file-oid'}) + .blobs == {'file': 'file-oid'}) def test_hex(self): tree = M.GitLikeTree() @@ -47,9 +47,9 @@ class TestGitLikeTree: # check the reprs. In case hex (below) fails, this'll be useful assert (repr(tree.get_tree('dir').get_tree('dir2')) == - 'b file-oid file') + 'b file-oid file') assert (repr(tree) == - 't 96af1772ecce1e6044e6925e595d9373ffcd2615 dir') + 't 96af1772ecce1e6044e6925e595d9373ffcd2615 dir') # the hex() value shouldn't change, it's an important key assert hex == '4abba29a43411b9b7cecc1a74f0b27920554350d' diff --git a/Allura/allura/tests/model/test_timeline.py b/Allura/allura/tests/model/test_timeline.py index 264057b68..9de2f64ef 100644 --- a/Allura/allura/tests/model/test_timeline.py +++ b/Allura/allura/tests/model/test_timeline.py @@ -37,4 +37,4 @@ class TestActivityObject_Functional: app_config = wiki_app.config assert (bool(app_config.has_activity_access('read', user=M.User.anonymous(), activity=None)) is - True) \ No newline at end of file + True) diff --git a/Allura/allura/tests/test_app.py b/Allura/allura/tests/test_app.py index a23274168..cffe3fb5d 100644 --- a/Allura/allura/tests/test_app.py +++ b/Allura/allura/tests/test_app.py @@ -53,7 +53,7 @@ class TestApp: def test_config_options(self): options = [ app.ConfigOption('test1', str, 'MyTestValue'), - app.ConfigOption('test2', str, lambda:'MyTestValue')] + app.ConfigOption('test2', str, lambda: 'MyTestValue')] assert options[0].default == 'MyTestValue' assert options[1].default == 'MyTestValue' @@ -81,6 +81,7 @@ class TestApp: def test_options_on_install(self): opts = [app.ConfigOption('url', str, None), app.ConfigOption('private', bool, None)] + class TestApp(app.Application): config_options = app.Application.config_options + opts + [ app.ConfigOption('not_on_install', str, None), @@ -108,7 +109,7 @@ class TestApp: sm = app.SitemapEntry('test', '')[ app.SitemapEntry('a', 'a/'), app.SitemapEntry('b', 'b/')] - sm[app.SitemapEntry(lambda app:app.config.script_name(), 'c/')] + sm[app.SitemapEntry(lambda app: app.config.script_name(), 'c/')] bound_sm = sm.bind_app(c.app) assert bound_sm.url == 'http://testproject/test_application/', bound_sm.url assert bound_sm.children[ diff --git a/Allura/allura/tests/test_commands.py b/Allura/allura/tests/test_commands.py index ed304676c..660b0f172 100644 --- a/Allura/allura/tests/test_commands.py +++ b/Allura/allura/tests/test_commands.py @@ -457,6 +457,7 @@ class TestShowModels: - <FieldProperty content> ''' in output.captured + class TestReindexAsTask: cmd = 'allura.command.show_models.ReindexCommand' @@ -521,7 +522,7 @@ class TestReindexCommand: assert ( {Solr.call_args_list[0][0][0], Solr.call_args_list[1][0][0]} == {'http://blah.com/solr/forge', - 'https://other.net/solr/forge'}) + 'https://other.net/solr/forge'}) @patch('allura.command.show_models.utils') def test_project_regex(self, utils): diff --git a/Allura/allura/tests/test_helpers.py b/Allura/allura/tests/test_helpers.py index 18c96aa1c..7bf3a55bc 100644 --- a/Allura/allura/tests/test_helpers.py +++ b/Allura/allura/tests/test_helpers.py @@ -707,6 +707,7 @@ def test_querystring(): assert (h.querystring(req, dict(page=5, limit=2, count=None)) == 'https://mysite.com/p/test/foobar/p/test/foobar?page=5&limit=2') + def test_clean_html(): assert h.clean_html('<script>alert(1)</script>') == '<script>alert(1)</script>' assert h.clean_html('<b style="color: red; right: 0">ok</b>') == '<b style="color: red;">ok</b>' diff --git a/Allura/allura/tests/test_mail_util.py b/Allura/allura/tests/test_mail_util.py index 50b5b208b..f5d1705be 100644 --- a/Allura/allura/tests/test_mail_util.py +++ b/Allura/allura/tests/test_mail_util.py @@ -285,7 +285,7 @@ class TestIdentifySender: def test_arg(self, EA): EA.canonical = lambda e: e EA.get.side_effect = [ - mock.Mock(claimed_by_user_id=True, claimed_by_user=lambda:'user')] + mock.Mock(claimed_by_user_id=True, claimed_by_user=lambda: 'user')] assert identify_sender(None, 'arg', None, None) == 'user' EA.get.assert_called_once_with(email='arg', confirmed=True) @@ -293,11 +293,11 @@ class TestIdentifySender: def test_header(self, EA): EA.canonical = lambda e: e EA.get.side_effect = [ - None, mock.Mock(claimed_by_user_id=True, claimed_by_user=lambda:'user')] + None, mock.Mock(claimed_by_user_id=True, claimed_by_user=lambda: 'user')] assert ( identify_sender(None, 'arg', {'From': 'from'}, None) == 'user') assert (EA.get.call_args_list == - [mock.call(email='arg', confirmed=True), mock.call(email='from')]) + [mock.call(email='arg', confirmed=True), mock.call(email='from')]) @mock.patch('allura.model.User') @mock.patch('allura.model.EmailAddress') @@ -305,7 +305,7 @@ class TestIdentifySender: anon = User.anonymous() EA.canonical = lambda e: e EA.get.side_effect = [ - None, mock.Mock(claimed_by_user_id=True, claimed_by_user=lambda:'user')] + None, mock.Mock(claimed_by_user_id=True, claimed_by_user=lambda: 'user')] assert identify_sender(None, 'arg', {}, None) == anon assert EA.get.call_args_list == [mock.call(email='arg', confirmed=True)] @@ -318,7 +318,7 @@ class TestIdentifySender: assert ( identify_sender(None, 'arg', {'From': 'from'}, None) == anon) assert (EA.get.call_args_list == - [mock.call(email='arg', confirmed=True), mock.call(email='from')]) + [mock.call(email='arg', confirmed=True), mock.call(email='from')]) def test_parse_message_id(): diff --git a/Allura/allura/tests/test_middlewares.py b/Allura/allura/tests/test_middlewares.py index 5a2e5c1b2..191e00377 100644 --- a/Allura/allura/tests/test_middlewares.py +++ b/Allura/allura/tests/test_middlewares.py @@ -77,9 +77,9 @@ class TestCORSMiddleware: def test_get_response_headers_simple(self): # Allow-Origin: * is crucial for security, since that prevents browsers from exposing results fetched withCredentials: true (aka cookies) assert (self.cors.get_response_headers() == - [('Access-Control-Allow-Origin', '*')]) + [('Access-Control-Allow-Origin', '*')]) assert (self.cors.get_response_headers(preflight=False) == - [('Access-Control-Allow-Origin', '*')]) + [('Access-Control-Allow-Origin', '*')]) def test_get_response_headers_preflight(self): assert ( @@ -91,10 +91,10 @@ class TestCORSMiddleware: def test_get_response_headers_preflight_with_cache(self): cors = CORSMiddleware(self.app, ['GET', 'PUT'], ['Accept'], 86400) assert (cors.get_response_headers(preflight=True) == - [('Access-Control-Allow-Origin', '*'), - ('Access-Control-Allow-Methods', 'GET, PUT'), - ('Access-Control-Allow-Headers', 'accept'), - ('Access-Control-Max-Age', '86400')]) + [('Access-Control-Allow-Origin', '*'), + ('Access-Control-Allow-Methods', 'GET, PUT'), + ('Access-Control-Allow-Headers', 'accept'), + ('Access-Control-Max-Age', '86400')]) def test_get_access_control_request_headers(self): key = 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' @@ -102,4 +102,4 @@ class TestCORSMiddleware: assert f({}) == set() assert f({key: ''}) == set() assert (f({key: 'Authorization, Accept'}) == - {'authorization', 'accept'}) + {'authorization', 'accept'}) diff --git a/Allura/allura/tests/test_security.py b/Allura/allura/tests/test_security.py index 12c9df089..a1413583f 100644 --- a/Allura/allura/tests/test_security.py +++ b/Allura/allura/tests/test_security.py @@ -150,7 +150,7 @@ class TestSecurity(TestController): assert has_access(page, 'post', test_user) assert has_access(page, 'unmoderated_post', test_user) # FIXME: all_allowed doesn't respect blocked user feature - #assert_equal(all_allowed(page, test_user), set(['post', 'unmoderated_post'])) + # assert_equal(all_allowed(page, test_user), set(['post', 'unmoderated_post'])) assert has_access(wiki, 'read', test_user) assert has_access(wiki, 'post', test_user) @@ -167,7 +167,7 @@ class TestSecurity(TestController): assert has_access(wiki, 'post', test_user) assert has_access(wiki, 'unmoderated_post', test_user) # FIXME: all_allowed doesn't respect blocked user feature - #assert_equal(all_allowed(wiki, test_user), set(['post', 'unmoderated_post'])) + # assert_equal(all_allowed(wiki, test_user), set(['post', 'unmoderated_post'])) @td.with_wiki def test_implicit_project(self): diff --git a/Allura/allura/tests/test_webhooks.py b/Allura/allura/tests/test_webhooks.py index e8432415d..76b78a076 100644 --- a/Allura/allura/tests/test_webhooks.py +++ b/Allura/allura/tests/test_webhooks.py @@ -232,8 +232,8 @@ class TestWebhookController(TestController): extra_environ={'username': '*anonymous'}, status=302) assert (r.location == - 'http://localhost/auth/' - '?return_to=%2Fadobe%2Fadobe-1%2Fadmin%2Fsrc%2Fwebhooks%2Frepo-push%2F') + 'http://localhost/auth/' + '?return_to=%2Fadobe%2Fadobe-1%2Fadmin%2Fsrc%2Fwebhooks%2Frepo-push%2F') def test_invalid_hook_type(self): self.app.get(self.url + '/invalid-hook-type/', status=404) @@ -482,7 +482,7 @@ class TestSendWebhookHelper(TestWebhookBase): self.h.send() assert requests.post.call_count == 4 # initial call + 3 retries assert (time.sleep.call_args_list == - [call(60), call(120), call(240)]) + [call(60), call(120), call(240)]) assert log.info.call_args_list == [ call('Retrying webhook in: %s', [60, 120, 240]), call('Retrying webhook in %s seconds', 60), @@ -537,7 +537,7 @@ class TestRepoPushWebhookSender(TestWebhookBase): sender.send([dict(arg1=1, arg2=2), dict(arg1=3, arg2=4)]) assert send_webhook.post.call_count == 2 assert (send_webhook.post.call_args_list == - [call(self.wh._id, 1), call(self.wh._id, 2)]) + [call(self.wh._id, 1), call(self.wh._id, 2)]) assert self.wh.enforce_limit.call_count == 1 @patch('allura.webhooks.log', autospec=True) @@ -563,7 +563,7 @@ class TestRepoPushWebhookSender(TestWebhookBase): def test_get_payload(self): sender = RepoPushWebhookSender() - _ci = lambda x: MagicMock(webhook_info={'id': str(x)}, parent_ids=['0']) + def _ci(x): return MagicMock(webhook_info={'id': str(x)}, parent_ids=['0']) 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 = { @@ -625,7 +625,7 @@ class TestRepoPushWebhookSender(TestWebhookBase): class TestModels(TestWebhookBase): def test_webhook_url(self): assert (self.wh.url() == - f'/adobe/adobe-1/admin/src/webhooks/repo-push/{self.wh._id}') + f'/adobe/adobe-1/admin/src/webhooks/repo-push/{self.wh._id}') def test_webhook_enforce_limit(self): self.wh.last_sent = None diff --git a/Allura/allura/tests/unit/test_ldap_auth_provider.py b/Allura/allura/tests/unit/test_ldap_auth_provider.py index f1fff6e28..818b09e17 100644 --- a/Allura/allura/tests/unit/test_ldap_auth_provider.py +++ b/Allura/allura/tests/unit/test_ldap_auth_provider.py @@ -73,7 +73,7 @@ class TestLdapAuthenticationProvider: 'password': 'test-password', } self.provider.request.method = 'POST' - self.provider.request.body = '&'.join([f'{k}={v}' for k,v in params.items()]).encode('utf-8') + self.provider.request.body = '&'.join([f'{k}={v}' for k, v in params.items()]).encode('utf-8') ldap.dn.escape_dn_chars = lambda x: x self.provider._login() @@ -92,7 +92,7 @@ class TestLdapAuthenticationProvider: 'password': 'test-password', } self.provider.request.method = 'POST' - self.provider.request.body = '&'.join([f'{k}={v}' for k,v in params.items()]).encode('utf-8') + self.provider.request.body = '&'.join([f'{k}={v}' for k, v in params.items()]).encode('utf-8') ldap.dn.escape_dn_chars = lambda x: x dn = 'uid=%s,ou=people,dc=localdomain' % params['username'] conn = ldap.initialize.return_value diff --git a/Allura/allura/tests/unit/test_project.py b/Allura/allura/tests/unit/test_project.py index 37af31d18..0dc9081b0 100644 --- a/Allura/allura/tests/unit/test_project.py +++ b/Allura/allura/tests/unit/test_project.py @@ -106,7 +106,7 @@ class TestProject(unittest.TestCase): def test_icon_url(self): p = M.Project( shortname='myproj', - neighborhood = M.Neighborhood(url_prefix='/nbhd/'), + neighborhood=M.Neighborhood(url_prefix='/nbhd/'), ) self.assertEqual(p.icon_url(), '/nbhd/myproj/icon') diff --git a/Allura/allura/webhooks.py b/Allura/allura/webhooks.py index 246f481ff..54f0354e7 100644 --- a/Allura/allura/webhooks.py +++ b/Allura/allura/webhooks.py @@ -131,7 +131,7 @@ class WebhookController(BaseController, AdminControllerMixin, metaclass=WebhookC if not request.validation.values and kw: # Executes if update_webhook raises an error request.validation.values = {'url': kw.get('url'), - 'secret': kw.get('secret')} + 'secret': kw.get('secret')} return {'sender': self.sender, 'action': 'create', 'form': self.create_form()} @@ -200,8 +200,8 @@ class WebhookController(BaseController, AdminControllerMixin, metaclass=WebhookC except Invalid: raise exc.HTTPNotFound() request.validation.values = {'url': kw.get('url') or wh.hook_url, - 'secret': kw.get('secret') or wh.secret, - 'webhook': str(wh._id)} + 'secret': kw.get('secret') or wh.secret, + 'webhook': str(wh._id)} return {'sender': self.sender, 'action': 'edit', 'form': form} diff --git a/AlluraTest/alluratest/controller.py b/AlluraTest/alluratest/controller.py index a7f7b3d81..782fcc44a 100644 --- a/AlluraTest/alluratest/controller.py +++ b/AlluraTest/alluratest/controller.py @@ -48,7 +48,7 @@ import allura.lib.security from allura.lib.app_globals import Globals from allura.lib import helpers as h from allura.websetup.schema import REGISTRY -#from allura.lib.custom_middleware import environ as ENV, MagicalC +# from allura.lib.custom_middleware import environ as ENV, MagicalC from .validation import ValidatingTestApp import six @@ -162,8 +162,8 @@ def setup_global_objects(): def setup_trove_categories(): create_trove_categories = CreateTroveCategoriesCommand('create_trove_categories') - with mock.patch.object(M.project.TroveCategoryMapperExtension, 'after_insert'),\ - mock.patch.object(M.project.TroveCategoryMapperExtension, 'after_update'),\ + with mock.patch.object(M.project.TroveCategoryMapperExtension, 'after_insert'), \ + mock.patch.object(M.project.TroveCategoryMapperExtension, 'after_update'), \ mock.patch.object(M.project.TroveCategoryMapperExtension, 'after_delete'): create_trove_categories.run(['']) diff --git a/ForgeActivity/forgeactivity/tests/functional/test_rest.py b/ForgeActivity/forgeactivity/tests/functional/test_rest.py index 453fd2e7d..5e5ced02b 100644 --- a/ForgeActivity/forgeactivity/tests/functional/test_rest.py +++ b/ForgeActivity/forgeactivity/tests/functional/test_rest.py @@ -70,7 +70,6 @@ class TestActivityHasAccessAPI(TestRestApiBase): assert r.status_int == 200 assert r.json['result'] is False - def test_user_api(self): r = self.api_get('/rest/u/test-user/activity') - assert r.status_int == 200 \ No newline at end of file + assert r.status_int == 200 diff --git a/ForgeBlog/forgeblog/tests/functional/test_feeds.py b/ForgeBlog/forgeblog/tests/functional/test_feeds.py index 34b6ea228..b65c93e1d 100644 --- a/ForgeBlog/forgeblog/tests/functional/test_feeds.py +++ b/ForgeBlog/forgeblog/tests/functional/test_feeds.py @@ -70,7 +70,7 @@ class TestFeeds(TestController): assert '<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">' in r # ...and atom:link points to feed url assert ('<atom:link href="http://localhost/blog/feed.rss" ' - 'rel="self" type="application/rss+xml"></atom:link>' in r) + 'rel="self" type="application/rss+xml"></atom:link>' in r) def test_post_feeds(self): self._post() @@ -82,7 +82,7 @@ class TestFeeds(TestController): self._post(title='test', text='*sometext*') response = self.app.get('/blog/feed') assert ('<div class="markdown_content"><p><em>sometext</em></p></div>' in - response) + response) def test_related_artifacts(self): self._post(title='one') @@ -136,7 +136,7 @@ class TestFeeds(TestController): self._post() blog_post = BM.BlogPost.query.get() with h.push_config(c, user=M.User.query.get(username='test-admin')), \ - h.push_context(blog_post.project._id, app_config_id=blog_post.app_config_id): + h.push_context(blog_post.project._id, app_config_id=blog_post.app_config_id): blog_post.discussion_thread.add_post(text='You are a good blogger, I am a boring commentor.') ThreadLocalODMSession.flush_all() @@ -144,4 +144,4 @@ class TestFeeds(TestController): assert 'boring comment' in resp resp = self.app.get("/blog/feed.rss") - assert 'boring comment' not in resp \ No newline at end of file + assert 'boring comment' not in resp diff --git a/ForgeBlog/forgeblog/tests/test_app.py b/ForgeBlog/forgeblog/tests/test_app.py index 3f25dcd34..4e37e9028 100644 --- a/ForgeBlog/forgeblog/tests/test_app.py +++ b/ForgeBlog/forgeblog/tests/test_app.py @@ -111,9 +111,9 @@ class TestBulkExport: assert blog['posts'][1]['title'] == 'Test title' assert blog['posts'][1]['text'] == 'test post' assert (blog['posts'][1]['labels'] == - ['the firstlabel', 'the second label']) + ['the firstlabel', 'the second label']) assert (blog['posts'][1]['discussion_thread'] - ['posts'][0]['text'] == 'test comment') + ['posts'][0]['text'] == 'test comment') @td.with_tool('test', 'Blog', 'blog') def test_export_with_attachments(self): @@ -148,5 +148,5 @@ class TestBulkExport: list(post.discussion_thread.post_class().query.find())[0].slug ) assert (blog['posts'][0]['discussion_thread']['posts'][0] - ['attachments'][0]['path'] == file_path) - assert os.path.exists(os.path.join(temp_dir, file_path)) \ No newline at end of file + ['attachments'][0]['path'] == file_path) + assert os.path.exists(os.path.join(temp_dir, file_path)) diff --git a/ForgeBlog/forgeblog/tests/test_commands.py b/ForgeBlog/forgeblog/tests/test_commands.py index 4ab680f16..1420ce8b8 100644 --- a/ForgeBlog/forgeblog/tests/test_commands.py +++ b/ForgeBlog/forgeblog/tests/test_commands.py @@ -65,6 +65,8 @@ def _mock_feed(*entries): feed.entries.append(entry) return feed + + _mock_feed.i = 0 @@ -130,4 +132,3 @@ def test_pull_rss_feeds(parsefeed): assert posts[2].text == rendered_html_content assert posts[3].title == 'Default Title 4' assert posts[3].text == rendered_html_content - diff --git a/ForgeDiscussion/forgediscussion/tests/functional/test_forum.py b/ForgeDiscussion/forgediscussion/tests/functional/test_forum.py index b362c9d73..78cf7d8ff 100644 --- a/ForgeDiscussion/forgediscussion/tests/functional/test_forum.py +++ b/ForgeDiscussion/forgediscussion/tests/functional/test_forum.py @@ -231,7 +231,7 @@ class TestForumMessageHandling(TestController): url = '/discussion/testforum/thread/%s/' % thd._id self.app.get(url) resp = self.app.get('/discussion/testforum/thread/foobar/', status=301) - assert('/discussion/testforum/' in resp.location) + assert ('/discussion/testforum/' in resp.location) def test_posts(self): # not sure why this fails when set to root (to match self.user_id) @@ -620,8 +620,6 @@ class TestForum(TestController): btn_edit = post_container.find('a', {'title': 'Edit'}) assert not btn_edit - - @td.with_tool('test2', 'Discussion', 'discussion') @mock.patch('allura.model.discuss.g.spam_checker') def test_is_spam(self, spam_checker): @@ -911,8 +909,8 @@ class TestForum(TestController): assert 'first subject' in resp - f = resp.html.find('div', {'id':'mod_thread_form'}).find('form') - params=dict( + f = resp.html.find('div', {'id': 'mod_thread_form'}).find('form') + params = dict( flags='', discussion='general', subject='changed subject') diff --git a/ForgeDiscussion/forgediscussion/tests/functional/test_forum_admin.py b/ForgeDiscussion/forgediscussion/tests/functional/test_forum_admin.py index 9be5d9c4b..8366e4dd8 100644 --- a/ForgeDiscussion/forgediscussion/tests/functional/test_forum_admin.py +++ b/ForgeDiscussion/forgediscussion/tests/functional/test_forum_admin.py @@ -284,7 +284,6 @@ class TestForumAdmin(TestController): extra_environ=dict(username='test-user'), status=403) - def test_footer_monitoring_email(self): r = self.app.get('/admin/discussion/forums') form = r.forms['add-forum'] @@ -318,6 +317,6 @@ class TestForumAdmin(TestController): dict(task_name='allura.tasks.mail_tasks.sendsimplemail')).all() assert 'Sent from localhost because em...@monitoring.com is subscribed '\ 'to http://localhost/p/test/discussion/testforum/' in email_tasks[ - 0].kwargs['text'], email_tasks[0].kwargs['text'] + 0].kwargs['text'], email_tasks[0].kwargs['text'] assert 'a project admin can change settings at http://localhost/p/test/admin/discussion/forums' in email_tasks[ 0].kwargs['text'] diff --git a/ForgeDiscussion/forgediscussion/tests/functional/test_import.py b/ForgeDiscussion/forgediscussion/tests/functional/test_import.py index bf4cf6db8..633775360 100644 --- a/ForgeDiscussion/forgediscussion/tests/functional/test_import.py +++ b/ForgeDiscussion/forgediscussion/tests/functional/test_import.py @@ -109,10 +109,10 @@ class TestImportController(TestRestApiBase): # TestController): assert from_api['summary'] == org['summary'] assert from_api['ticket_num'] == org['id'] assert (from_api['created_date'] == - self.time_normalize(org['date'])) + self.time_normalize(org['date'])) assert (from_api['mod_date'] == - self.time_normalize(org['date_updated'])) + self.time_normalize(org['date_updated'])) assert (from_api['custom_fields'] - ['_resolution'] == org['resolution']) + ['_resolution'] == org['resolution']) assert from_api['custom_fields']['_cc'] == org['cc'] assert from_api['custom_fields']['_private'] == org['private'] diff --git a/ForgeGit/forgegit/model/git_repo.py b/ForgeGit/forgegit/model/git_repo.py index b0aa83e90..fffd9457e 100644 --- a/ForgeGit/forgegit/model/git_repo.py +++ b/ForgeGit/forgegit/model/git_repo.py @@ -457,7 +457,7 @@ class GitImplementation(M.RepositoryImplementation): commit_lines = [] while True: line = six.ensure_text(stream.readline()) - if '\x00' in line or not(len(line)): + if '\x00' in line or not (len(line)): # hash line read, need to yield previous commit # first, cleaning lines a bit commit_lines = [ @@ -484,7 +484,7 @@ class GitImplementation(M.RepositoryImplementation): renamed['from'] = name_stat_parts[1] renamed['to'] = name_stat_parts[2] yield (git.Commit(self._git, gitdb.util.hex_to_bin(hexsha)), refs, renamed) - if not(len(line)): + if not (len(line)): # if all lines have been read break commit_lines = [line] @@ -596,7 +596,7 @@ class GitImplementation(M.RepositoryImplementation): except ValueError: threshold = None log.warning('Skipping reference caching - The value for config param ' - '"repo_refs_cache_threshold" must be a float.') + '"repo_refs_cache_threshold" must be a float.') if threshold is not None and time_taken > threshold: setattr(self._repo, cache_name, refs) @@ -815,4 +815,5 @@ class _OpenedGitBlob: def close(self): pass + Mapper.compile_all() diff --git a/ForgeGit/forgegit/tests/functional/test_controllers.py b/ForgeGit/forgegit/tests/functional/test_controllers.py index 3d994ca4f..b071af922 100644 --- a/ForgeGit/forgegit/tests/functional/test_controllers.py +++ b/ForgeGit/forgegit/tests/functional/test_controllers.py @@ -527,7 +527,7 @@ class TestRootController(_TestCase): def test_index_branch_unicode(self): # more realistic case is the default branch having unicode, but passing the branch name is easier - resp = self.app.get('/p/test/src-git/', params={'branch':'ƒ∂ß'}) + resp = self.app.get('/p/test/src-git/', params={'branch': 'ƒ∂ß'}) assert resp.location == 'http://localhost/p/test/src-git/ref/%C6%92%E2%88%82%C3%9F/' # further testing needs a real branch in our test repo diff --git a/ForgeGit/forgegit/tests/model/test_repository.py b/ForgeGit/forgegit/tests/model/test_repository.py index b8d58ae01..3a61c6869 100644 --- a/ForgeGit/forgegit/tests/model/test_repository.py +++ b/ForgeGit/forgegit/tests/model/test_repository.py @@ -618,14 +618,14 @@ By Dave Brondsema''' in text_body assert impl._git.head.reference.name == 'master' def test_default_branch_non_standard_unset(self): - with mock.patch.object(self.repo, 'get_branches') as gb,\ + with mock.patch.object(self.repo, 'get_branches') as gb, \ mock.patch.object(self.repo, 'set_default_branch') as set_db: gb.return_value = [Object(name='foo')] assert self.repo.get_default_branch(('main', 'master')) == 'foo' set_db.assert_called_once_with('foo') def test_default_branch_non_standard_invalid(self): - with mock.patch.object(self.repo, 'get_branches') as gb,\ + with mock.patch.object(self.repo, 'get_branches') as gb, \ mock.patch.object(self.repo, 'set_default_branch') as set_db: self.repo.default_branch_name = 'zz' gb.return_value = [Object(name='foo')] @@ -633,7 +633,7 @@ By Dave Brondsema''' in text_body set_db.assert_called_once_with('foo') def test_default_branch_invalid(self): - with mock.patch.object(self.repo, 'get_branches') as gb,\ + with mock.patch.object(self.repo, 'get_branches') as gb, \ mock.patch.object(self.repo, 'set_default_branch') as set_db: self.repo.default_branch_name = 'zz' gb.return_value = [Object(name='foo'), Object(name='master')] @@ -653,7 +653,7 @@ By Dave Brondsema''' in text_body assert self.repo.get_default_branch(('main', 'master')) == 'main' def test_default_branch_main_before_master(self): - with mock.patch.object(self.repo, 'get_branches') as gb,\ + with mock.patch.object(self.repo, 'get_branches') as gb, \ mock.patch.object(self.repo, 'set_default_branch') as set_db: self.repo.default_branch_name = None gb.return_value = [Object(name='master'), Object(name='main')] diff --git a/ForgeImporters/forgeimporters/base.py b/ForgeImporters/forgeimporters/base.py index 79984d011..1087bdc40 100644 --- a/ForgeImporters/forgeimporters/base.py +++ b/ForgeImporters/forgeimporters/base.py @@ -121,7 +121,7 @@ def object_from_path(path): def import_tool(importer_path, project_name=None, mount_point=None, mount_label=None, **kw): importer = object_from_path(importer_path)() - with ImportErrorHandler(importer, project_name, c.project) as handler,\ + with ImportErrorHandler(importer, project_name, c.project) as handler, \ M.session.substitute_extensions(M.artifact_orm_session, [M.session.BatchIndexer]): try: @@ -579,7 +579,7 @@ class ProjectToolsImportController: importer_matrix = defaultdict(dict) tools_with_importers = set() hidden = set(aslist(config.get('hidden_importers'), sep=',')) - visible = lambda ep: ep.name not in hidden + def visible(ep): return ep.name not in hidden for ep in filter(visible, h.iter_entry_points('allura.importers')): # must instantiate to ensure importer.target_app is populated # (see ToolImporterMeta.__call__) diff --git a/ForgeImporters/forgeimporters/github/__init__.py b/ForgeImporters/forgeimporters/github/__init__.py index 57deee4c4..6e2019e5d 100644 --- a/ForgeImporters/forgeimporters/github/__init__.py +++ b/ForgeImporters/forgeimporters/github/__init__.py @@ -40,6 +40,7 @@ log = logging.getLogger(__name__) class GitHubURLValidator(fev.FancyValidator): regex = r'https?:\/\/github\.com' + def _convert_to_python(self, value, state): valid_url = urlparse(value.strip()) if not bool(valid_url.scheme): @@ -48,6 +49,7 @@ class GitHubURLValidator(fev.FancyValidator): raise fev.Invalid('Invalid Github URL', value, state) return value + class GitHubProjectNameValidator(fev.FancyValidator): not_empty = True messages = { @@ -99,7 +101,7 @@ class GitHubProjectExtractor(base.ProjectExtractor): now = datetime.utcnow() # 60/hour is for GitHub unauthenticated users. If you get that, check your auth tokens log.warning('Rate limit exceeded (%s requests/hour). ' - 'Sleeping until %s UTC' % (limit, reset)) + 'Sleeping until %s UTC' % (limit, reset)) time.sleep((reset - now).total_seconds() + 2) def urlopen(self, url, headers=None, use_auth_headers_on_redirects=True, **kw): diff --git a/ForgeImporters/forgeimporters/github/tests/test_wiki.py b/ForgeImporters/forgeimporters/github/tests/test_wiki.py index 7f4972f4a..4a440ad07 100644 --- a/ForgeImporters/forgeimporters/github/tests/test_wiki.py +++ b/ForgeImporters/forgeimporters/github/tests/test_wiki.py @@ -48,8 +48,8 @@ class TestGitHubWikiImporter(TestCase): @patch('forgeimporters.github.wiki.g') @patch('forgeimporters.github.wiki.GitHubProjectExtractor') def test_import_tool_happy_path(self, ghpe, g, tlorms, M): - with patch('forgeimporters.github.wiki.GitHubWikiImporter.import_pages'),\ - patch('forgeimporters.github.wiki.GitHubWikiImporter.has_wiki_repo', return_value=True),\ + with patch('forgeimporters.github.wiki.GitHubWikiImporter.import_pages'), \ + patch('forgeimporters.github.wiki.GitHubWikiImporter.has_wiki_repo', return_value=True), \ patch('forgeimporters.github.wiki.c'): ghpe.return_value.has_wiki.return_value = True p = self._make_project(gh_proj_name='myproject') diff --git a/ForgeImporters/forgeimporters/tests/github/test_extractor.py b/ForgeImporters/forgeimporters/tests/github/test_extractor.py index e33faf357..9baa6bcbf 100644 --- a/ForgeImporters/forgeimporters/tests/github/test_extractor.py +++ b/ForgeImporters/forgeimporters/tests/github/test_extractor.py @@ -27,7 +27,6 @@ from mock import patch, Mock from ... import github - class TestGitHubProjectExtractor(TestCase): PROJECT_INFO = { 'description': 'project description', diff --git a/ForgeImporters/forgeimporters/tests/test_base.py b/ForgeImporters/forgeimporters/tests/test_base.py index 07672023c..ac9e0071d 100644 --- a/ForgeImporters/forgeimporters/tests/test_base.py +++ b/ForgeImporters/forgeimporters/tests/test_base.py @@ -378,11 +378,11 @@ def test_get_importer_upload_path(): project.is_nbhd_project = False project.is_user_project = True assert (base.get_importer_upload_path(project) == - 'path/p/shortname') + 'path/p/shortname') project.is_user_project = False project.is_root = True assert (base.get_importer_upload_path(project) == - 'path/p/prefix/shortname') + 'path/p/prefix/shortname') @mock.patch.object(base, 'os') diff --git a/ForgeLink/forgelink/link_main.py b/ForgeLink/forgelink/link_main.py index 487bf572d..a6b79673b 100644 --- a/ForgeLink/forgelink/link_main.py +++ b/ForgeLink/forgelink/link_main.py @@ -59,7 +59,7 @@ class ForgeLinkApp(Application): label='External Url', help_text='URL to which you wish to link', validator=fev.URL(not_empty=True, add_http=True), - extra_attrs={'type': 'url', 'required' : '', 'placeholder' : 'https://example.com'}), + extra_attrs={'type': 'url', 'required': '', 'placeholder': 'https://example.com'}), ] config_on_install = ['url'] searchable = True diff --git a/ForgeLink/forgelink/tests/functional/test_root.py b/ForgeLink/forgelink/tests/functional/test_root.py index 4748225f5..6eb41d952 100644 --- a/ForgeLink/forgelink/tests/functional/test_root.py +++ b/ForgeLink/forgelink/tests/functional/test_root.py @@ -130,9 +130,9 @@ class TestConfigOptions(TestController): for menu_item in admin_nav_data['menu']: if menu_item['tool_name'] == 'link': assert ({'className': 'admin_modal', - 'text': 'Options', - 'href': '/p/test/admin/link/options'} in - menu_item['admin_options']) + 'text': 'Options', + 'href': '/p/test/admin/link/options'} in + menu_item['admin_options']) break else: raise AssertionError("Didn't find 'link' tool in {}".format(admin_nav_data['menu'])) diff --git a/ForgeSVN/forgesvn/model/svn.py b/ForgeSVN/forgesvn/model/svn.py index 06279d06b..e85624d8a 100644 --- a/ForgeSVN/forgesvn/model/svn.py +++ b/ForgeSVN/forgesvn/model/svn.py @@ -304,13 +304,13 @@ class SVNImplementation(M.RepositoryImplementation): """ opts = self._repo.app.config.options if not svn_path_exists('file://{}{}/{}'.format(self._repo.fs_path, - self._repo.name, opts['checkout_url'])): + self._repo.name, opts['checkout_url'])): opts['checkout_url'] = '' if (not opts['checkout_url'] and svn_path_exists( 'file://{}{}/trunk'.format(self._repo.fs_path, - self._repo.name))): + self._repo.name))): opts['checkout_url'] = 'trunk' def commit(self, rev): @@ -535,9 +535,9 @@ class SVNImplementation(M.RepositoryImplementation): path and (len(changed_path['path']) < len(path)) and path.startswith(changed_path['path'])): - changed_path['copyfrom_path'] = changed_path['copyfrom_path'] + \ - path[len(changed_path['path']):] - changed_path['path'] = path + changed_path['copyfrom_path'] = changed_path['copyfrom_path'] + \ + path[len(changed_path['path']):] + changed_path['path'] = path return changed_path def _map_log(self, ci, url, path=None): @@ -812,4 +812,5 @@ class SVNImplementation(M.RepositoryImplementation): return result + Mapper.compile_all() diff --git a/ForgeSVN/forgesvn/tests/model/test_svnimplementation.py b/ForgeSVN/forgesvn/tests/model/test_svnimplementation.py index bb60f1324..2a284a75a 100644 --- a/ForgeSVN/forgesvn/tests/model/test_svnimplementation.py +++ b/ForgeSVN/forgesvn/tests/model/test_svnimplementation.py @@ -51,7 +51,7 @@ class TestSVNImplementation: tree_id = impl.compute_tree_new(commit, path) assert (impl._svn.info2.call_args[0] - [0] == 'file://' + g.tmpdir + '/code/trunk/foo') + [0] == 'file://' + g.tmpdir + '/code/trunk/foo') assert lcd_partial.called def test_last_commit_ids(self): @@ -74,7 +74,7 @@ class TestSVNImplementation: assert entries == {path.strip('/'): '5057636b9c1040636b81e4b1:1'} assert (impl._svn.info2.call_args[0] - [0] == 'file://' + g.tmpdir + '/code/trunk') + [0] == 'file://' + g.tmpdir + '/code/trunk') @patch('forgesvn.model.svn.svn_path_exists') def test__tarball_path_clean(self, path_exists): diff --git a/ForgeTracker/forgetracker/tests/functional/test_rest.py b/ForgeTracker/forgetracker/tests/functional/test_rest.py index 0606d3e41..6353284f0 100644 --- a/ForgeTracker/forgetracker/tests/functional/test_rest.py +++ b/ForgeTracker/forgetracker/tests/functional/test_rest.py @@ -150,7 +150,7 @@ class TestRestIndex(TestTrackerApiBase): ticket_config = M.AppConfig.query.get( project_id=c.project._id, tool_name='tickets') assert (ticket_config.options.get('TicketMonitoringEmail') == - 'test@localhost') + 'test@localhost') @td.with_tool('test', 'Tickets', 'dummy') def test_move_ticket_redirect(self): @@ -182,7 +182,7 @@ class TestRestDiscussion(TestTrackerApiBase): assert post.json['post']['text'] == 'This is a comment', post.json reply = self.api_post( '/rest/p/test/bugs/_discuss/thread/{}/{}/reply'.format(thread.json['thread'] - ['_id'], post.json['post']['slug']), + ['_id'], post.json['post']['slug']), text='This is a reply') assert reply.json['post']['text'] == 'This is a reply', reply.json thread = self.api_get('/rest/p/test/bugs/_discuss/thread/%s/' % thread_id) diff --git a/ForgeTracker/forgetracker/tests/functional/test_root.py b/ForgeTracker/forgetracker/tests/functional/test_root.py index 7926b5d15..2e1ffb229 100644 --- a/ForgeTracker/forgetracker/tests/functional/test_root.py +++ b/ForgeTracker/forgetracker/tests/functional/test_root.py @@ -2380,14 +2380,14 @@ class TestFunctionalController(TrackerTestController): project_id=p2._id, app_config_id=features.config._id, artifact_title='Ticket #1: another test ticket', - artifact_url='/p/test2/features/1/'),\ + artifact_url='/p/test2/features/1/'), \ "Could not find moved subscription. User's record is %s" % M.Mailbox.query.get(user_id=user._id) # test-admin (who had a tool-level subscription) should be too assert M.Mailbox.query.get(user_id=admin._id, project_id=p2._id, app_config_id=features.config._id, artifact_title='Ticket #1: another test ticket', - artifact_url='/p/test2/features/1/'),\ + artifact_url='/p/test2/features/1/'), \ "Could not find moved subscription. Admin's record is %s" % M.Mailbox.query.get(user_id=admin._id) @td.with_tool('test2', 'Tickets', 'bugs2') diff --git a/ForgeTracker/forgetracker/tests/unit/test_search.py b/ForgeTracker/forgetracker/tests/unit/test_search.py index 4c3548b2c..d360372dd 100644 --- a/ForgeTracker/forgetracker/tests/unit/test_search.py +++ b/ForgeTracker/forgetracker/tests/unit/test_search.py @@ -26,14 +26,14 @@ def hit_mock(): 'reported_by_s': ['admin1', 5], 'status_s': ['closed', 1, 'open', 3, 'unread', 1]}} reformated = {'_milestone': [('1.0', 3), ('2.0', 2)], - 'assigned_to': [('admin1', 1)], - 'reported_by': [('admin1', 5)], - 'status': [('closed', 1), ('open', 3), ('unread', 1)]} + 'assigned_to': [('admin1', 1)], + 'reported_by': [('admin1', 5)], + 'status': [('closed', 1), ('open', 3), ('unread', 1)]} return hit, reformated def test_get_facets(): - hit,expected = hit_mock() + hit, expected = hit_mock() assert get_facets(hit) == expected diff --git a/ForgeTracker/forgetracker/tracker_main.py b/ForgeTracker/forgetracker/tracker_main.py index 31f3bed10..708345038 100644 --- a/ForgeTracker/forgetracker/tracker_main.py +++ b/ForgeTracker/forgetracker/tracker_main.py @@ -1111,7 +1111,7 @@ class RootController(BaseController, FeedController): if dates is None: today = datetime.utcnow() dates = "{} to {}".format((today - timedelta(days=61)) - .strftime('%Y-%m-%d'), today.strftime('%Y-%m-%d')) + .strftime('%Y-%m-%d'), today.strftime('%Y-%m-%d')) return dict( now=str(now), week_ago=str(week_ago), @@ -1691,7 +1691,7 @@ class TrackerAdminController(DefaultAdminController): def fields(self, **kw): c.form = W.field_admin columns = {column: get_label(column) - for column in self.app.globals['show_in_search'].keys()} + for column in self.app.globals['show_in_search'].keys()} return dict(app=self.app, globals=self.app.globals, columns=columns) @expose('jinja:forgetracker:templates/tracker/admin_options.html') diff --git a/ForgeTracker/forgetracker/widgets/ticket_form.py b/ForgeTracker/forgetracker/widgets/ticket_form.py index 7b960c1f9..aa45ee83d 100644 --- a/ForgeTracker/forgetracker/widgets/ticket_form.py +++ b/ForgeTracker/forgetracker/widgets/ticket_form.py @@ -102,7 +102,7 @@ class GenericTicketForm(ew.SimpleForm): def fields(self): fields = [ ew.TextField(name='summary', label='Title', - attrs={'style': 'width: 425px', 'class':'memorable', + attrs={'style': 'width: 425px', 'class': 'memorable', 'placeholder': 'Title'}, validator=v.UnicodeString( not_empty=True, messages={ @@ -257,7 +257,7 @@ class MilestoneField(ew.SingleSelectField): opt for opt in self.options if opt.complete] # filter closed milestones entirely - #value = context['value'] - #context['options'] = [opt for opt in self.options if not opt.complete or value == opt.py_value] + # value = context['value'] + # context['options'] = [opt for opt in self.options if not opt.complete or value == opt.py_value] return context diff --git a/ForgeUserStats/forgeuserstats/model/stats.py b/ForgeUserStats/forgeuserstats/model/stats.py index fc410c11a..b81aa0d18 100644 --- a/ForgeUserStats/forgeuserstats/model/stats.py +++ b/ForgeUserStats/forgeuserstats/model/stats.py @@ -73,4 +73,5 @@ class UserStats(Stats): self.lastmonthlogins.append(login_datetime) self.checkOldArtifacts() + Mapper.compile_all() diff --git a/ForgeWiki/forgewiki/tests/functional/test_rest.py b/ForgeWiki/forgewiki/tests/functional/test_rest.py index e75a911a5..c9d1b8b25 100644 --- a/ForgeWiki/forgewiki/tests/functional/test_rest.py +++ b/ForgeWiki/forgewiki/tests/functional/test_rest.py @@ -49,11 +49,11 @@ class TestWikiApi(TestRestApiBase): r = self.app.get('/rest/p/test/wiki/Home/') r = json.loads(r.text) assert (r['attachments'][0]['url'] == - 'http://localhost/p/test/wiki/Home/attachment/test_root.py') + 'http://localhost/p/test/wiki/Home/attachment/test_root.py') assert (r['discussion_thread_url'] == 'http://localhost/rest%s' % - discussion_url) + discussion_url) assert (r['discussion_thread']['_id'] == - discussion_url.split('/')[-2]) + discussion_url.split('/')[-2]) self.app.post('/wiki/Home/attach', upload_files=[('file_info', '__init__.py', content), ]) r = self.app.get('/rest/p/test/wiki/Home/') diff --git a/ForgeWiki/forgewiki/tests/test_app.py b/ForgeWiki/forgewiki/tests/test_app.py index 797a2d4fd..d247437dc 100644 --- a/ForgeWiki/forgewiki/tests/test_app.py +++ b/ForgeWiki/forgewiki/tests/test_app.py @@ -80,12 +80,12 @@ class TestBulkExport: assert pages[1]['title'] == 'Return of the Jedi' assert (pages[1]['text'] == - 'Star Wars Episode VI: Return of the Jedi') + 'Star Wars Episode VI: Return of the Jedi') assert len(pages[1]['discussion_thread']['posts']) == 0 assert pages[2]['title'] == 'The Empire Strikes Back' assert (pages[2]['text'] == - 'Star Wars Episode V: The Empire Strikes Back') + 'Star Wars Episode V: The Empire Strikes Back') assert len(pages[2]['discussion_thread']['posts']) == 0 def add_page_with_attachmetns(self): diff --git a/ForgeWiki/forgewiki/wiki_main.py b/ForgeWiki/forgewiki/wiki_main.py index f1e8a4a3b..1f66a7212 100644 --- a/ForgeWiki/forgewiki/wiki_main.py +++ b/ForgeWiki/forgewiki/wiki_main.py @@ -912,7 +912,7 @@ class PageRestController(BaseController): require_access(c.app, 'create') if WM.Page.is_limit_exceeded(c.app.config, user=c.user): log.warning('Page create/edit rate limit exceeded. %s', - c.app.config.url()) + c.app.config.url()) raise forge_exc.HTTPTooManyRequests() self.page = WM.Page.upsert(title) self.page.viewable_by = ['all'] diff --git a/scripts/migrations/033-change-comment-anon-permissions.py b/scripts/migrations/033-change-comment-anon-permissions.py index d3189c23a..7285c479f 100644 --- a/scripts/migrations/033-change-comment-anon-permissions.py +++ b/scripts/migrations/033-change-comment-anon-permissions.py @@ -41,11 +41,11 @@ def arguments(): def main(): args = arguments() - c.project = None # to avoid error in Artifact.__mongometa__.before_save + c.project = None # to avoid error in Artifact.__mongometa__.before_save project = M.Project.query.get(shortname=args.shortname) tool = project.app_config_by_tool_type(args.toolname) - for chunk in utils.chunked_find(ForumPost, {'app_config_id':tool._id}): + for chunk in utils.chunked_find(ForumPost, {'app_config_id': tool._id}): for p in chunk: has_access = bool(security.has_access(p, 'moderate', M.User.anonymous())) @@ -53,7 +53,7 @@ def main(): anon_role_id = None for acl in p.acl: # find the anon moderate acl - if acl.permission == 'moderate' and acl.access=='ALLOW': + if acl.permission == 'moderate' and acl.access == 'ALLOW': anon_role_id = acl.role_id if anon_role_id: diff --git a/scripts/perf/generate-projects.py b/scripts/perf/generate-projects.py index dc59db9a3..503ed255c 100644 --- a/scripts/perf/generate-projects.py +++ b/scripts/perf/generate-projects.py @@ -19,11 +19,12 @@ import re from ming.odm import ThreadLocalODMSession from allura import model as M + def main(start, cnt): n = M.Neighborhood.query.get(url_prefix='/p/') admin = M.User.by_username('admin1') - #M.Project.query.remove({'shortname': re.compile('gen-proj-.*')}) - #ThreadLocalODMSession.flush_all() + # M.Project.query.remove({'shortname': re.compile('gen-proj-.*')}) + # ThreadLocalODMSession.flush_all() for i in range(start, cnt): name = f'gen-proj-{i}' project = n.register_project(name, admin) @@ -33,6 +34,7 @@ def main(start, cnt): ThreadLocalODMSession.flush_all() print('Done') + if __name__ == '__main__': import sys start = int(sys.argv[1]) diff --git a/scripts/perf/parse_timings.py b/scripts/perf/parse_timings.py index 18408d90f..e55dd833a 100644 --- a/scripts/perf/parse_timings.py +++ b/scripts/perf/parse_timings.py @@ -38,7 +38,7 @@ for line in args.input_file: try: typ = data['message']['request_category'] except KeyError: - #print 'No category', data['message']['url'] + # print 'No category', data['message']['url'] pass if args.filter_category and typ not in args.filter_category: continue diff --git a/scripts/scrub-allura-data.py b/scripts/scrub-allura-data.py index 2211fc56b..744fba148 100644 --- a/scripts/scrub-allura-data.py +++ b/scripts/scrub-allura-data.py @@ -116,11 +116,11 @@ def main(options): ThreadLocalODMSession.close_all() log.info('%s %s EmailAddress documents' % - (preamble, M.EmailAddress.find().count())) + (preamble, M.EmailAddress.find().count())) log.info('%s email addresses from %s User documents' % - (preamble, M.User.query.find().count())) + (preamble, M.User.query.find().count())) log.info('%s monitoring_email addresses from %s Forum documents' % - (preamble, DM.Forum.query.find({"monitoring_email": + (preamble, DM.Forum.query.find({"monitoring_email": {"$nin": [None, ""]}}).count())) if not options.dry_run: diff --git a/scripts/trac_import.py b/scripts/trac_import.py index 5e574be14..dc61bf04b 100644 --- a/scripts/trac_import.py +++ b/scripts/trac_import.py @@ -62,14 +62,13 @@ def main(): import_wiki(cli, options.project, options.wiki, options, doc_txt) - def import_forum(cli, project, tool, user_map, doc_txt, validate=True, - neighborhood='p'): + neighborhood='p'): url = '/rest/{neighborhood}/{project}/{tool}'.format( - neighborhood=neighborhood, - project=project, - tool=tool, - ) + neighborhood=neighborhood, + project=project, + tool=tool, + ) if validate: url += '/validate_import' print(cli.call(url, doc=doc_txt, user_map=json.dumps(user_map)))