This is an automated email from the ASF dual-hosted git repository. brondsem pushed a commit to branch db/pep8_nov2022 in repository https://gitbox.apache.org/repos/asf/allura.git
commit b5a3bcba5f027bf80e8938af21df305f4090d8a7 Author: Dave Brondsema <[email protected]> AuthorDate: Wed Nov 9 16:29:12 2022 -0500 autopep8 -i --max-line-length 9999 on many files --- Allura/allura/controllers/repository.py | 15 +++--- Allura/allura/lib/helpers.py | 14 +++-- Allura/allura/lib/widgets/forms.py | 18 +++---- Allura/allura/tests/functional/test_admin.py | 26 ++++----- Allura/allura/tests/functional/test_home.py | 34 ++++++------ Allura/allura/tests/test_globals.py | 62 +++++++++++----------- Allura/allura/tests/test_helpers.py | 36 ++++++------- Allura/allura/tests/test_plugin.py | 12 ++--- Allura/allura/tests/test_security.py | 16 +++--- Allura/allura/tests/test_utils.py | 11 ++-- AlluraTest/alluratest/controller.py | 12 +++-- .../forgeactivity/tests/functional/test_root.py | 20 +++---- .../forgegit/tests/functional/test_controllers.py | 36 ++++++------- .../forgeimporters/github/tests/test_wiki.py | 20 +++---- .../forgesvn/tests/functional/test_controllers.py | 14 ++--- ForgeSVN/forgesvn/tests/model/test_repository.py | 26 ++++----- ForgeTracker/forgetracker/model/ticket.py | 18 +++---- .../forgetracker/tests/functional/test_root.py | 48 ++++++++--------- ...34-update_subscriptions_ticket_and_mr_titles.py | 6 +-- 19 files changed, 229 insertions(+), 215 deletions(-) diff --git a/Allura/allura/controllers/repository.py b/Allura/allura/controllers/repository.py index 0dae4b49f..cb9cad866 100644 --- a/Allura/allura/controllers/repository.py +++ b/Allura/allura/controllers/repository.py @@ -104,7 +104,7 @@ class RepoRootController(BaseController, FeedController): links.append(dict( repo_url=f.url(), repo='{} / {}'.format(repo_path_parts[1], - repo_path_parts[-1]), + repo_path_parts[-1]), )) return dict(links=links) @@ -130,7 +130,7 @@ class RepoRootController(BaseController, FeedController): from_project = c.project to_project = M.Project.query.get(_id=ObjectId(project_id)) mount_label = mount_label or '{} - {}'.format(c.project.name, - c.app.config.options.mount_label) + c.app.config.options.mount_label) mount_point = (mount_point or from_project.shortname) if request.method != 'POST' or not mount_point: return dict(from_repo=from_repo, @@ -361,12 +361,13 @@ class RepoRestController(RepoRootController, AppRestControllerMixin): } for commit in revisions ]} + @expose('json:') def commit_status(self, rev=None, **kwargs): if not g.commit_statuses_enabled: return {'status': 'disabled', 'message': 'check your config file'} - params = {x : kwargs.get(x, '').strip() for x in - ['state', 'target_url', 'description', 'context']} + params = {x: kwargs.get(x, '').strip() for x in + ['state', 'target_url', 'description', 'context']} params['commit_id'] = rev status = M.CommitStatus.upsert(**params) response = {'status': 'error'} @@ -375,7 +376,6 @@ class RepoRestController(RepoRootController, AppRestControllerMixin): return response - class MergeRequestsController: @with_trailing_slash @@ -949,7 +949,7 @@ class FileBrowser(BaseController): if not self._blob.has_html_view: diff = "Cannot display: file marked as a binary type." return dict(a=a, b=b, diff=diff) - + if max(a.size, b.size) > asint(tg.config.get('scm.view.max_diff_bytes', 2000000)): # have to check the original file size, not diff size, because difflib._mdiff inside HtmlSideBySideDiff # can take an extremely long time on large files (and its even a generator) @@ -967,7 +967,7 @@ class FileBrowser(BaseController): else: web_session['diformat'] = fmt web_session.save() - + if fmt == 'sidebyside': hd = HtmlSideBySideDiff() diff = hd.make_table(la, lb, adesc, bdesc) @@ -999,4 +999,5 @@ def topo_sort(children, parents, dates, head_ids): else: to_visit.append(p) + on_import() diff --git a/Allura/allura/lib/helpers.py b/Allura/allura/lib/helpers.py index da5f3e954..51d867ebc 100644 --- a/Allura/allura/lib/helpers.py +++ b/Allura/allura/lib/helpers.py @@ -178,9 +178,11 @@ def querystring(request, url_params): url = url_parts._replace(query=urlencode(params)).geturl() return url + def ceil(number): return math.ceil(number) + def strip_bad_unicode(s): """ xml doesn't like some control characters: https://www.w3.org/TR/REC-xml/#charsets @@ -251,6 +253,7 @@ def really_unicode(s): # default case. Also lets Markup() instances be preserved return s # Try to guess the encoding + def encodings(): yield None yield 'utf-8' @@ -656,6 +659,7 @@ class fixed_attrs_proxy(proxy): provided during object construction, returns it's value. Otherwise proxies to obj. """ + def __init__(self, obj, **kw): self._obj = obj for k, v in kw.items(): @@ -695,7 +699,7 @@ def config_with_prefix(d, prefix): ''' plen = len(prefix) return {k[plen:]: v for k, v in d.items() - if k.startswith(prefix)} + if k.startswith(prefix)} def paging_sanitizer(limit, page, total_count=sys.maxsize, zero_based_pages=True): @@ -781,12 +785,14 @@ def render_any_markup(name, txt, code_mode=False, linenumbers_style=TABLE): txt = '<pre>%s</pre>' % txt return Markup(txt) + @pass_context def subrender_jinja_filter(context, value): _template = context.eval_ctx.environment.from_string(value) result = _template.render(**context) return result + def nl2br_jinja_filter(value): result = '<br>\n'.join(escape(line) for line in value.split('\n')) return Markup(result) @@ -1267,8 +1273,8 @@ def slugify(name, allow_periods=False): """ RE_NON_ALPHA_ETC = re.compile(r'[^.\w]+' if allow_periods else r'[^\w]+') slug = RE_NON_ALPHA_ETC.sub('-', # replace non ". alphanum_" sequences into single - - unicodedata.normalize('NFKD', name).encode('ascii', 'ignore').decode().replace("'", '') # asciify & strip apostophes. https://stackoverflow.com/a/53261200 - ).strip('-') # leading - or trailing - gets removed + unicodedata.normalize('NFKD', name).encode('ascii', 'ignore').decode().replace("'", '') # asciify & strip apostophes. https://stackoverflow.com/a/53261200 + ).strip('-') # leading - or trailing - gets removed return slug, slug.lower() @@ -1323,7 +1329,7 @@ def username_project_url(user_or_username): return f'{url}profile/' -def pluralize_tool_name(tool_name:string, count:int): +def pluralize_tool_name(tool_name: string, count: int): pluralize_tools = ['Wiki', 'Discussion', 'Blog'] if tool_name is not None and tool_name in pluralize_tools: return f"{tool_name}{'s'[:count^1]}" diff --git a/Allura/allura/lib/widgets/forms.py b/Allura/allura/lib/widgets/forms.py index bd1ab5e0e..69bf853cd 100644 --- a/Allura/allura/lib/widgets/forms.py +++ b/Allura/allura/lib/widgets/forms.py @@ -119,7 +119,7 @@ class ForgeForm(ew.SimpleForm): display = field.display(**ctx) if ctx['errors'] and field.show_errors and not ignore_errors: display = "{}<div class='error'>{}</div>".format(display, - ctx['errors']) + ctx['errors']) return Markup(display) @@ -498,9 +498,9 @@ class AddInactivePeriodForm(ForgeForm): def to_python(self, kw, state): d = super().to_python(kw, state) if d['startdate'] > d['enddate']: - raise formencode.Invalid( - 'Invalid period: start date greater than end date.', - kw, state) + raise formencode.Invalid( + 'Invalid period: start date greater than end date.', + kw, state) return d @@ -557,9 +557,9 @@ class AddTimeSlotForm(ForgeForm): d = super().to_python(kw, state) if (d['starttime']['h'], d['starttime']['m']) > \ (d['endtime']['h'], d['endtime']['m']): - raise formencode.Invalid( - 'Invalid period: start time greater than end time.', - kw, state) + raise formencode.Invalid( + 'Invalid period: start time greater than end time.', + kw, state) return d @@ -618,7 +618,7 @@ class RemoveTroveCategoryForm(ForgeForm): href="/categories/%s" % cat.trove_cat_id), ew.HTMLField( text=cat.shortname, - attrs={'disabled':True, 'value':cat.shortname}), + attrs={'disabled': True, 'value': cat.shortname}), ew.SubmitButton( show_errors=False, attrs={'value': 'Remove'})], @@ -874,7 +874,7 @@ class NeighborhoodOverviewForm(ForgeForm): if ctx['errors'] and field.show_errors and not ignore_errors: display = "{}<div class='error'>{}</div>".format(display, - ctx['errors']) + ctx['errors']) return Markup(display) else: diff --git a/Allura/allura/tests/functional/test_admin.py b/Allura/allura/tests/functional/test_admin.py index c0a879c3f..c1d71bd72 100644 --- a/Allura/allura/tests/functional/test_admin.py +++ b/Allura/allura/tests/functional/test_admin.py @@ -453,7 +453,7 @@ class TestProjectAdmin(TestController): assert screenshots[0].filename == 'admin_24.png' # reverse order params = {str(ss._id): str(len(screenshots) - 1 - i) - for i, ss in enumerate(screenshots)} + for i, ss in enumerate(screenshots)} self.app.post('/admin/sort_screenshots', params) assert project.get_screenshots()[0].filename == 'admin_32.png' @@ -979,7 +979,7 @@ class TestExport(TestController): r = self.app.get('/admin/export', extra_environ={'username': '*anonymous'}).follow() assert (r.request.url == - 'http://localhost/auth/?return_to=%2Fadmin%2Fexport') + 'http://localhost/auth/?return_to=%2Fadmin%2Fexport') self.app.get('/admin/export', extra_environ={'username': 'test-user'}, status=403) @@ -1017,7 +1017,7 @@ class TestExport(TestController): exportable_mount_points = [ t.options.mount_point for t in exportable_tools] assert (exportable_mount_points == - ['admin', 'search', 'wiki', 'wiki2']) + ['admin', 'search', 'wiki', 'wiki2']) def test_tools_not_selected(self): r = self.app.post('/admin/export') @@ -1055,7 +1055,7 @@ class TestExport(TestController): def test_bulk_export_path_for_user_project(self): project = M.Project.query.get(shortname='u/test-user') assert (project.bulk_export_path(tg.config['bulk_export_path']) == - '/tmp/bulk_export/u/test-user') + '/tmp/bulk_export/u/test-user') @td.with_user_project('test-user') def test_bulk_export_filename_for_user_project(self): @@ -1177,7 +1177,7 @@ class TestRestInstallTool(TestRestApiBase): r = self.api_post('/rest/p/test/admin/install_tool/', **data) assert r.json['success'] is False assert (r.json['info'] == - 'Incorrect tool name, or limit is reached.') + 'Incorrect tool name, or limit is reached.') def test_bad_mount(self): r = self.api_get('/rest/p/test/') @@ -1192,7 +1192,7 @@ class TestRestInstallTool(TestRestApiBase): r = self.api_post('/rest/p/test/admin/install_tool/', **data) assert r.json['success'] is False assert (r.json['info'] == - 'Mount point "tickets_mount1" is invalid') + 'Mount point "tickets_mount1" is invalid') def test_install_tool_ok(self): r = self.api_get('/rest/p/test/') @@ -1207,12 +1207,12 @@ class TestRestInstallTool(TestRestApiBase): r = self.api_post('/rest/p/test/admin/install_tool/', **data) assert r.json['success'] is True assert (r.json['info'] == - 'Tool %s with mount_point %s and mount_label %s was created.' - % ('tickets', 'ticketsmount1', 'tickets_label1')) + 'Tool %s with mount_point %s and mount_label %s was created.' + % ('tickets', 'ticketsmount1', 'tickets_label1')) project = M.Project.query.get(shortname='test') assert (project.ordered_mounts() - [-1]['ac'].options.mount_point == 'ticketsmount1') + [-1]['ac'].options.mount_point == 'ticketsmount1') audit_log = M.AuditLog.query.find( {'project_id': project._id}).sort('_id', -1).first() assert audit_log.message == 'install tool ticketsmount1' @@ -1256,7 +1256,7 @@ class TestRestInstallTool(TestRestApiBase): r = self.api_post('/rest/p/test/admin/install_tool/', **data) assert r.json['success'] is False assert (r.json['info'] == - 'Incorrect tool name, or limit is reached.') + 'Incorrect tool name, or limit is reached.') def test_unauthorized(self): r = self.api_get('/rest/p/test/') @@ -1285,7 +1285,7 @@ class TestRestInstallTool(TestRestApiBase): labels.append(mount['sub'].name) return labels assert (get_labels() == - ['Admin', 'Search', 'Activity', 'A Subproject']) + ['Admin', 'Search', 'Activity', 'A Subproject']) data = [ { @@ -1316,8 +1316,8 @@ class TestRestInstallTool(TestRestApiBase): r = self.api_post('/rest/p/test/admin/install_tool/', **datum) assert r.json['success'] is True assert (r.json['info'] == - 'Tool %s with mount_point %s and mount_label %s was created.' - % (datum['tool'], datum['mount_point'], datum['mount_label'])) + 'Tool %s with mount_point %s and mount_label %s was created.' + % (datum['tool'], datum['mount_point'], datum['mount_label'])) assert ( get_labels() == ['t1', 'Admin', 'Search', 'Activity', 'A Subproject', 'ta', 'tb', 'tc']) diff --git a/Allura/allura/tests/functional/test_home.py b/Allura/allura/tests/functional/test_home.py index 6b62fe97b..0479fc1fb 100644 --- a/Allura/allura/tests/functional/test_home.py +++ b/Allura/allura/tests/functional/test_home.py @@ -54,27 +54,27 @@ class TestProjectHome(TestController): for m in r.json['menu']: if m['mount_point'] == 'sub1': assert (m['admin_options'] == - [{'className': None, - 'text': 'Subproject Admin', - 'href': '/p/test/sub1/admin', - }]) + [{'className': None, + 'text': 'Subproject Admin', + 'href': '/p/test/sub1/admin', + }]) break else: raise AssertionError('Did not find sub1 subproject in menu results: {}'.format(r.json['menu'])) for m in r.json['menu']: if m['mount_point'] == 'wiki': assert {'className': 'admin_modal', - 'text': 'Set Home', - 'href': '/p/test/admin/wiki/home', - } in m['admin_options'] + 'text': 'Set Home', + 'href': '/p/test/admin/wiki/home', + } in m['admin_options'] assert {'className': None, - 'text': 'Permissions', - 'href': '/p/test/admin/wiki/permissions', - } in m['admin_options'] + 'text': 'Permissions', + 'href': '/p/test/admin/wiki/permissions', + } in m['admin_options'] assert {'className': 'admin_modal', - 'text': 'Delete Everything', - 'href': '/p/test/admin/wiki/delete', - } in m['admin_options'] + 'text': 'Delete Everything', + 'href': '/p/test/admin/wiki/delete', + } in m['admin_options'] break else: raise AssertionError('Did not find wiki in menu results: {}'.format(r.json['menu'])) @@ -92,12 +92,12 @@ class TestProjectHome(TestController): wiki_group = menu[-2] wikis = wiki_group.pop('children') assert {'url': '/p/test/_list/wiki', 'name': 'Wiki \u25be', 'mount_point': None, - 'icon': 'tool-wiki', 'tool_name': 'wiki', 'is_anchored': False} == wiki_group + 'icon': 'tool-wiki', 'tool_name': 'wiki', 'is_anchored': False} == wiki_group assert len(wikis) == 2 assert {'url': '/p/test/wiki/', 'name': 'Wiki', 'mount_point': 'wiki', - 'icon': 'tool-wiki', 'tool_name': 'wiki', 'is_anchored': False} in wikis + 'icon': 'tool-wiki', 'tool_name': 'wiki', 'is_anchored': False} in wikis assert {'url': '/p/test/wiki2/', 'name': 'wiki2', 'mount_point': 'wiki2', - 'icon': 'tool-wiki', 'tool_name': 'wiki', 'is_anchored': False} in wikis + 'icon': 'tool-wiki', 'tool_name': 'wiki', 'is_anchored': False} in wikis def test_sitemap_limit_per_tool(self): """Test that sitemap is limited to max of 10 items per tool type.""" @@ -127,7 +127,7 @@ class TestProjectHome(TestController): wiki_menu = [m for m in menu if m['tool_name'] == 'wiki'][0] assert len(wiki_menu['children']) == 10 assert {'url': '/p/test/_list/wiki', 'name': 'More...', 'mount_point': None, - 'icon': 'tool-wiki', 'tool_name': 'wiki', 'is_anchored': False} in wiki_menu['children'] + 'icon': 'tool-wiki', 'tool_name': 'wiki', 'is_anchored': False} in wiki_menu['children'] @td.with_wiki def test_neighborhood_home(self): diff --git a/Allura/allura/tests/test_globals.py b/Allura/allura/tests/test_globals.py index 9b16328bc..2ed823368 100644 --- a/Allura/allura/tests/test_globals.py +++ b/Allura/allura/tests/test_globals.py @@ -159,8 +159,8 @@ class Test(): ThreadLocalORMSession.flush_all() with h.push_config(c, - project=p_nbhd.neighborhood_project, - user=M.User.by_username('test-admin')): + project=p_nbhd.neighborhood_project, + user=M.User.by_username('test-admin')): r = g.markdown_wiki.convert('[[projects]]') assert 'alt="Test Project Logo"' in r, r assert 'alt="A Subproject Logo"' in r, r @@ -243,23 +243,23 @@ class Test(): ThreadLocalORMSession.flush_all() r = g.markdown_wiki.convert('[[members limit=2]]').replace('\t', '').replace('\n', '') assert (r == - '<div class="markdown_content"><h6>Project Members:</h6>' - '<ul class="md-users-list">' - '<li><a href="/u/test-admin/">Test Admin</a> (admin)</li>' - '<li><a href="/u/test-user/">Test User</a></li>' - '<li class="md-users-list-more"><a href="/p/test/_members">All Members</a></li>' - '</ul>' - '</div>') + '<div class="markdown_content"><h6>Project Members:</h6>' + '<ul class="md-users-list">' + '<li><a href="/u/test-admin/">Test Admin</a> (admin)</li>' + '<li><a href="/u/test-user/">Test User</a></li>' + '<li class="md-users-list-more"><a href="/p/test/_members">All Members</a></li>' + '</ul>' + '</div>') def test_macro_members_escaping(self): user = M.User.by_username('test-admin') user.display_name = 'Test Admin <script>' r = g.markdown_wiki.convert('[[members]]') assert (r.replace('\n', '').replace('\t', '') == - '<div class="markdown_content"><h6>Project Members:</h6>' - '<ul class="md-users-list">' - '<li><a href="/u/test-admin/">Test Admin <script></a> (admin)</li>' - '</ul></div>') + '<div class="markdown_content"><h6>Project Members:</h6>' + '<ul class="md-users-list">' + '<li><a href="/u/test-admin/">Test Admin <script></a> (admin)</li>' + '</ul></div>') def test_macro_project_admins(self): user = M.User.by_username('test-admin') @@ -267,10 +267,10 @@ class Test(): with h.push_context('test', neighborhood='Projects'): r = g.markdown_wiki.convert('[[project_admins]]') assert (r.replace('\n', '') == - '<div class="markdown_content"><h6>Project Admins:</h6>' - '<ul class="md-users-list">' - ' <li><a href="/u/test-admin/">Test \xc5dmin <script></a></li>' - '</ul></div>') + '<div class="markdown_content"><h6>Project Admins:</h6>' + '<ul class="md-users-list">' + ' <li><a href="/u/test-admin/">Test \xc5dmin <script></a></li>' + '</ul></div>') def test_macro_project_admins_one_br(self): p_nbhd = M.Neighborhood.query.get(name='Projects') @@ -371,7 +371,7 @@ class Test(): oembed_fetch.side_effect = OEmbedError('Invalid mime-type in response...') r = g.markdown_wiki.convert('[[embed url=http://www.youtube.com/watch?v=6YbBmqUnoQM]]') assert (r == '<div class="markdown_content"><p>Could not embed: ' - 'http://www.youtube.com/watch?v=6YbBmqUnoQM</p></div>') + 'http://www.youtube.com/watch?v=6YbBmqUnoQM</p></div>') def test_macro_embed_notsupported(self): r = g.markdown_wiki.convert('[[embed url=http://vimeo.com/46163090]]') @@ -447,12 +447,12 @@ class Test(): with h.push_context('test', 'wiki', neighborhood='Projects'): text = g.markdown.convert('# Foo!\n[Home]') assert (text == - '<div class="markdown_content"><h1 id="foo">Foo!</h1>\n' - '<p><a class="alink" href="/p/test/wiki/Home/">[Home]</a></p></div>') + '<div class="markdown_content"><h1 id="foo">Foo!</h1>\n' + '<p><a class="alink" href="/p/test/wiki/Home/">[Home]</a></p></div>') text = g.markdown.convert('# Foo!\n[Rooted]') assert (text == - '<div class="markdown_content"><h1 id="foo">Foo!</h1>\n' - '<p><span>[Rooted]</span></p></div>') + '<div class="markdown_content"><h1 id="foo">Foo!</h1>\n' + '<p><span>[Rooted]</span></p></div>') assert ( g.markdown.convert('Multi\nLine') == @@ -554,7 +554,7 @@ class Test(): g.markdown.convert('literal `http://domain.net` literal')) assert ('<pre><span></span><code>preformatted http://domain.net\n</code></pre>' in g.markdown.convert(' :::text\n' - ' preformatted http://domain.net')) + ' preformatted http://domain.net')) def test_markdown_autolink_with_escape(self): # \_ is unnecessary but valid markdown escaping and should be considered as a regular underscore @@ -577,14 +577,14 @@ class Test(): def test_markdown_invalid_script_in_link(self): r = g.markdown.convert('[xss](http://"><a onmouseover=prompt(document.domain)>xss</a>)') assert ('<div class="markdown_content"><p><a class="" ' - '''href='http://"><a%20onmouseover=prompt(document.domain)>xss</a>' ''' - 'rel="nofollow">xss</a></p></div>' == r) + '''href='http://"><a%20onmouseover=prompt(document.domain)>xss</a>' ''' + 'rel="nofollow">xss</a></p></div>' == r) def test_markdown_invalid_script_in_link2(self): r = g.markdown.convert('[xss](http://"><img src=x onerror=alert(document.cookie)>)') assert ('<div class="markdown_content"><p><a class="" ' - '''href='http://"><img%20src=x%20onerror=alert(document.cookie)>' ''' - 'rel="nofollow">xss</a></p></div>' == r) + '''href='http://"><img%20src=x%20onerror=alert(document.cookie)>' ''' + 'rel="nofollow">xss</a></p></div>' == r) def test_markdown_extremely_slow(self): r = g.markdown.convert('''bonjour, voila ce que j'obtient en voulant ajouter un utilisateur a un groupe de sécurite, que ce soit sur un groupe pre-existant, ou sur un groupe crée. @@ -686,8 +686,8 @@ class Test(): p_nbhd = M.Neighborhood.query.get(name='Projects') with h.push_config(c, - project=p_nbhd.neighborhood_project, - user=M.User.by_username('test-admin')): + project=p_nbhd.neighborhood_project, + user=M.User.by_username('test-admin')): r = g.markdown_wiki.convert( '[[projects category="%s"]]' % random_trove.fullpath) project_names = get_project_names(r) @@ -698,8 +698,8 @@ class Test(): p_nbhd = M.Neighborhood.query.get(name='Projects') with h.push_config(c, - project=p_nbhd.neighborhood_project, - user=M.User.anonymous()): + project=p_nbhd.neighborhood_project, + user=M.User.anonymous()): # test columns r = g.markdown_wiki.convert('[[projects display_mode=list columns=2]]') assert two_column_style in r diff --git a/Allura/allura/tests/test_helpers.py b/Allura/allura/tests/test_helpers.py index 9e2ef3f88..045d9a4e0 100644 --- a/Allura/allura/tests/test_helpers.py +++ b/Allura/allura/tests/test_helpers.py @@ -265,17 +265,17 @@ def test_render_any_markup_plain(): def test_render_any_markup_formatting(): assert (str(h.render_any_markup('README.md', '### foo\n' - ' <script>alert(1)</script> bar')) == - '<div class="markdown_content"><h3 id="foo">foo</h3>\n' - '<div class="codehilite"><pre><span></span><code><span class="nt">' - '<script></span>alert(1)<span class="nt">' - '</script></span> bar\n</code></pre></div>\n</div>') + ' <script>alert(1)</script> bar')) == + '<div class="markdown_content"><h3 id="foo">foo</h3>\n' + '<div class="codehilite"><pre><span></span><code><span class="nt">' + '<script></span>alert(1)<span class="nt">' + '</script></span> bar\n</code></pre></div>\n</div>') def test_render_any_markdown_encoding(): # send encoded content in, make sure it converts it to actual unicode object which Markdown lib needs assert (h.render_any_markup('README.md', 'Müller'.encode()) == - '<div class="markdown_content"><p>Müller</p></div>') + '<div class="markdown_content"><p>Müller</p></div>') class AuditLogMock(Mock): @@ -342,16 +342,16 @@ def test_datetimeformat(): def test_nl2br_jinja_filter(): assert (h.nl2br_jinja_filter('foo<script>alert(1)</script>\nbar\nbaz') == - Markup('foo<script>alert(1)</script><br>\nbar<br>\nbaz')) + Markup('foo<script>alert(1)</script><br>\nbar<br>\nbaz')) def test_split_select_field_options(): assert (h.split_select_field_options('"test message" test2') == - ['test message', 'test2']) + ['test message', 'test2']) assert (h.split_select_field_options('"test message test2') == - ['test', 'message', 'test2']) + ['test', 'message', 'test2']) assert (h.split_select_field_options('abc ƒå∂ ººº') == - ['abc', 'ƒå∂', 'ººº']) + ['abc', 'ƒå∂', 'ººº']) def test_notifications_disabled(): @@ -575,9 +575,9 @@ class TestIterEntryPoints(TestCase): self._make_ep('myapp', BestApp)] self.assertRaisesRegex(ImportError, - r'Ambiguous \[allura\] entry points detected. ' - 'Multiple entry points with name "myapp".', - list, h.iter_entry_points('allura')) + r'Ambiguous \[allura\] entry points detected. ' + 'Multiple entry points with name "myapp".', + list, h.iter_entry_points('allura')) def test_get_user_status(): @@ -596,11 +596,11 @@ def test_get_user_status(): def test_convert_bools(): assert (h.convert_bools({'foo': 'bar', 'baz': 'false', 'abc': 0, 'def': 1, 'ghi': True}) == - {'foo': 'bar', 'baz': False, 'abc': 0, 'def': 1, 'ghi': True}) + {'foo': 'bar', 'baz': False, 'abc': 0, 'def': 1, 'ghi': True}) assert (h.convert_bools({'foo': 'true', 'baz': ' TRUE '}) == - {'foo': True, 'baz': True}) + {'foo': True, 'baz': True}) assert (h.convert_bools({'foo': 'true', 'baz': ' TRUE '}, prefix='ba') == - {'foo': 'true', 'baz': True}) + {'foo': 'true', 'baz': True}) def test_base64uri_img(): @@ -684,6 +684,6 @@ def test_querystring(): req = Request.blank('/p/test/foobar?page=1&limit=10&count=100', remote_addr='127.0.0.1', base_url='https://mysite.com/p/test/foobar') assert (h.querystring(req, dict(page=2, limit=5)) == - 'https://mysite.com/p/test/foobar/p/test/foobar?page=2&limit=5&count=100') + 'https://mysite.com/p/test/foobar/p/test/foobar?page=2&limit=5&count=100') assert (h.querystring(req, dict(page=5, limit=2, count=None)) == - 'https://mysite.com/p/test/foobar/p/test/foobar?page=5&limit=2') + 'https://mysite.com/p/test/foobar/p/test/foobar?page=5&limit=2') diff --git a/Allura/allura/tests/test_plugin.py b/Allura/allura/tests/test_plugin.py index f1dfaf53e..e440a60d8 100644 --- a/Allura/allura/tests/test_plugin.py +++ b/Allura/allura/tests/test_plugin.py @@ -280,7 +280,7 @@ class TestThemeProvider: app_icon = ThemeProvider().app_icon_url('testapp', 24) other = app_g.theme_href.return_value assert app_icon == other - + app_g.theme_href.assert_called_with('images/testapp_24.png') @patch('allura.lib.plugin.g') @@ -690,7 +690,7 @@ class TestLocalAuthenticationProvider: user = M.User(username='asfdasdf') assert (self.provider.login_details_from_auditlog(M.AuditLog(message='')) == - None) + None) detail = self.provider.login_details_from_auditlog(M.AuditLog(message='IP Address: 1.2.3.4\nFoo', user=user)) assert detail.user_id == user._id @@ -702,16 +702,16 @@ class TestLocalAuthenticationProvider: assert detail.ua is None assert (self.provider.login_details_from_auditlog(M.AuditLog( - message='blah blah IP Address: 1.2.3.4\nFoo', user=user)) == - None) + message='blah blah IP Address: 1.2.3.4\nFoo', user=user)) == + None) detail = self.provider.login_details_from_auditlog(M.AuditLog( - message='User-Agent: Mozilla/Firefox\nFoo', user=user)) + message='User-Agent: Mozilla/Firefox\nFoo', user=user)) assert detail.ip is None assert detail.ua == 'Mozilla/Firefox' detail = self.provider.login_details_from_auditlog(M.AuditLog( - message='IP Address: 1.2.3.4\nUser-Agent: Mozilla/Firefox\nFoo', user=user)) + message='IP Address: 1.2.3.4\nUser-Agent: Mozilla/Firefox\nFoo', user=user)) assert detail.ip == '1.2.3.4' assert detail.ua == 'Mozilla/Firefox' diff --git a/Allura/allura/tests/test_security.py b/Allura/allura/tests/test_security.py index 7a27b9302..b99cfe3ba 100644 --- a/Allura/allura/tests/test_security.py +++ b/Allura/allura/tests/test_security.py @@ -100,24 +100,24 @@ class TestSecurity(TestController): assert all_allowed(wiki, dev_role) == { 'read', 'create', 'edit', 'unmoderated_post', 'post', 'moderate', 'delete'} assert (all_allowed(wiki, member_role) == - {'read', 'create', 'edit', 'unmoderated_post', 'post'}) + {'read', 'create', 'edit', 'unmoderated_post', 'post'}) assert (all_allowed(wiki, auth_role) == - {'read', 'post', 'unmoderated_post'}) + {'read', 'post', 'unmoderated_post'}) assert all_allowed(wiki, anon_role) == {'read'} assert (all_allowed(wiki, test_user) == - {'read', 'post', 'unmoderated_post'}) + {'read', 'post', 'unmoderated_post'}) _add_to_group(test_user, member_role) assert (all_allowed(wiki, test_user) == - {'read', 'create', 'edit', 'unmoderated_post', 'post'}) + {'read', 'create', 'edit', 'unmoderated_post', 'post'}) _deny(wiki, auth_role, 'unmoderated_post') assert (all_allowed(wiki, member_role) == - {'read', 'create', 'edit', 'post'}) + {'read', 'create', 'edit', 'post'}) assert (all_allowed(wiki, test_user) == - {'read', 'create', 'edit', 'post'}) + {'read', 'create', 'edit', 'post'}) @td.with_wiki def test_deny_vs_allow(self): @@ -140,7 +140,7 @@ class TestSecurity(TestController): assert has_access(page, 'post', test_user)() assert has_access(page, 'unmoderated_post', test_user)() assert (all_allowed(page, test_user) == - {'read', 'post', 'unmoderated_post'}) + {'read', 'post', 'unmoderated_post'}) _deny(page, auth_role, 'read') @@ -156,7 +156,7 @@ class TestSecurity(TestController): assert has_access(wiki, 'post', test_user)() assert has_access(wiki, 'unmoderated_post', test_user)() assert (all_allowed(wiki, test_user) == - {'read', 'post', 'unmoderated_post'}) + {'read', 'post', 'unmoderated_post'}) _deny(wiki, anon_role, 'read') _allow(wiki, auth_role, 'read') diff --git a/Allura/allura/tests/test_utils.py b/Allura/allura/tests/test_utils.py index 5165082a3..131e9bf95 100644 --- a/Allura/allura/tests/test_utils.py +++ b/Allura/allura/tests/test_utils.py @@ -314,7 +314,7 @@ def test_ip_address(): req.remote_addr = '1.2.3.4' req.headers = {} assert (utils.ip_address(req) == - '1.2.3.4') + '1.2.3.4') def test_ip_address_header(): @@ -323,7 +323,7 @@ def test_ip_address_header(): req.headers = {'X_FORWARDED_FOR': '5.6.7.8'} with h.push_config(config, **{'ip_address_header': 'X_FORWARDED_FOR'}): assert (utils.ip_address(req) == - '5.6.7.8') + '5.6.7.8') def test_ip_address_header_not_set(): @@ -332,7 +332,7 @@ def test_ip_address_header_not_set(): req.headers = {} with h.push_config(config, **{'ip_address_header': 'X_FORWARDED_FOR'}): assert (utils.ip_address(req) == - '1.2.3.4') + '1.2.3.4') def test_empty_cursor(): @@ -384,6 +384,7 @@ class FakeAttachment: def __init__(self, filename): self._id = ObjectId() self.filename = filename + def __repr__(self): return f'{self._id} {self.filename}' @@ -428,7 +429,7 @@ def test_close_ipv4_addrs(): def test_urlencode(): # dict - a simple one so arbitrary ordering doesn't cause problems on py2 assert (utils.urlencode({'a': 'hello'}) == - 'a=hello') + 'a=hello') # list of pairs - including unicode and bytes assert (utils.urlencode([('a', 1), ('b', 'ƒ'), ('c', 'ƒ'.encode())]) == - 'a=1&b=%C6%92&c=%C6%92') + 'a=1&b=%C6%92&c=%C6%92') diff --git a/AlluraTest/alluratest/controller.py b/AlluraTest/alluratest/controller.py index f110c7a57..885bfbff9 100644 --- a/AlluraTest/alluratest/controller.py +++ b/AlluraTest/alluratest/controller.py @@ -108,6 +108,8 @@ def setup_basic_test(config=None, app_name=DFL_APP_NAME): # remove unnecessary bootstrap tasks, e.g. search indexing M.MonQTask.query.remove({'state': 'ready'}) + + setup_basic_test.__test__ = False # sometimes __test__ above isn't sufficient @@ -119,6 +121,8 @@ def setup_functional_test(config=None, app_name=DFL_APP_NAME, current_pkg=None): wsgiapp = loadapp(f'config:{config}#{app_name}', relative_to=conf_dir) return wsgiapp + + # sometimes __test__ above isn't sufficient setup_functional_test.__test__ = False @@ -145,6 +149,8 @@ def setup_unit_test(): c.model_cache = None ThreadLocalORMSession.close_all() + + setup_unit_test.__test__ = False # sometimes __test__ above isn't sufficient @@ -157,8 +163,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'),\ - mock.patch.object(M.project.TroveCategoryMapperExtension, 'after_delete'): + mock.patch.object(M.project.TroveCategoryMapperExtension, 'after_update'),\ + mock.patch.object(M.project.TroveCategoryMapperExtension, 'after_delete'): create_trove_categories.run(['']) @@ -299,5 +305,5 @@ def oauth1_webtest(url: str, oauth_kwargs: dict, method='GET') -> tuple[str, dic def request2webtest(req: requests.PreparedRequest) -> tuple[str, dict, dict]: url = req.url params = {} - headers = {k: v.decode() for k,v in req.headers.items()} + headers = {k: v.decode() for k, v in req.headers.items()} return url, params, headers diff --git a/ForgeActivity/forgeactivity/tests/functional/test_root.py b/ForgeActivity/forgeactivity/tests/functional/test_root.py index 5860ac7e2..41d5256f6 100644 --- a/ForgeActivity/forgeactivity/tests/functional/test_root.py +++ b/ForgeActivity/forgeactivity/tests/functional/test_root.py @@ -53,7 +53,7 @@ class TestActivityController(TestController): @td.with_user_project('test-user-1') def test_anon_read(self): r = self.app.get('/u/test-user-1', - extra_environ={'username': '*anonymous'}).follow() + extra_environ={'username': '*anonymous'}).follow() assert r.html.select('div.profile-section.tools a[href="/u/test-user-1/activity/"]'),\ 'No Activity tool in top nav' @@ -215,15 +215,15 @@ class TestActivityController(TestController): assert 1 == len(timeline.findall('item')) activity = timeline.find('item') assert (activity.find('pubDate').text == - 'Wed, 04 Dec 2013 21:48:19 -0000') + 'Wed, 04 Dec 2013 21:48:19 -0000') assert (activity.find('title').text == - 'Administrator 1 posted a comment on ticket #34') + 'Administrator 1 posted a comment on ticket #34') assert (activity.find('description').text == - 'Just wanted to leave a comment on this...') + 'Just wanted to leave a comment on this...') assert (activity.find('guid').text == - 'http://localhost/p/test/unicode•º/?limit=25#ed7c') + 'http://localhost/p/test/unicode•º/?limit=25#ed7c') assert (activity.find('link').text == - 'http://localhost/p/test/unicode%E2%80%A2%C2%BA/?limit=25#ed7c') + 'http://localhost/p/test/unicode%E2%80%A2%C2%BA/?limit=25#ed7c') @td.with_tool('test', 'activity') @patch('forgeactivity.main.g.director') @@ -289,13 +289,13 @@ class TestActivityController(TestController): assert 1 == len(timeline.findall('item')) activity = timeline.find('item') assert (activity.find('pubDate').text == - 'Wed, 04 Dec 2013 21:48:19 -0000') + 'Wed, 04 Dec 2013 21:48:19 -0000') assert (activity.find('title').text == - 'Administrator 1 posted a comment on ticket #34') + 'Administrator 1 posted a comment on ticket #34') assert (activity.find('description').text == - 'Just wanted to leave a comment on this...') + 'Just wanted to leave a comment on this...') assert (activity.find('link').text == - 'http://localhost/p/test/tickets/34/?limit=25#ed7c') + 'http://localhost/p/test/tickets/34/?limit=25#ed7c') @td.with_tool('test', 'activity') @patch('forgeactivity.main.g.director') diff --git a/ForgeGit/forgegit/tests/functional/test_controllers.py b/ForgeGit/forgegit/tests/functional/test_controllers.py index 2d6b333df..d42d91239 100644 --- a/ForgeGit/forgegit/tests/functional/test_controllers.py +++ b/ForgeGit/forgegit/tests/functional/test_controllers.py @@ -231,7 +231,7 @@ class TestRootController(_TestCase): assert title == 'test Git changes' description = channel.find('description').text assert (description == - 'Recent changes to Git repository in test project') + 'Recent changes to Git repository in test project') link = channel.find('link').text assert link == 'http://localhost/p/test/src-git/' earliest_commit = channel.findall('item')[-1] @@ -288,25 +288,25 @@ class TestRootController(_TestCase): resp = self.app.get(url) assert 'Привіт!\nWhich means Hello!' in resp.text assert (six.ensure_text(resp.headers.get('Content-Disposition')) == - 'attachment;filename="%D0%BF%D1%80%D0%B8%D0%B2%D1%96%D1%82.txt"') + 'attachment;filename="%D0%BF%D1%80%D0%B8%D0%B2%D1%96%D1%82.txt"') url = ci + 'tree/' + h.urlquote('with space.txt') + '?format=raw' resp = self.app.get(url) assert 'with space' in resp.text assert (six.ensure_text(resp.headers.get('Content-Disposition')) == - 'attachment;filename="with%20space.txt"') + 'attachment;filename="with%20space.txt"') url = ci + 'tree/' + h.urlquote('with%2Furlquote-literal.txt') + '?format=raw' resp = self.app.get(url) assert '%2F means /' in resp.body.decode('utf-8') assert (resp.headers.get('Content-Disposition') == - 'attachment;filename="with%252Furlquote-literal.txt"') + 'attachment;filename="with%252Furlquote-literal.txt"') url = ci + 'tree/' + h.urlquote('with"&:specials.txt') + '?format=raw' resp = self.app.get(url) assert '"&: encodes as %22%26%3A' in resp.body.decode('utf-8') assert (resp.headers.get('Content-Disposition') == - 'attachment;filename="with%22%26%3Aspecials.txt"') + 'attachment;filename="with%22%26%3Aspecials.txt"') def test_file_too_large(self): ci = self._get_ci() @@ -340,7 +340,7 @@ class TestRootController(_TestCase): <span class="gu">@@ -1 +1,2 @@</span><span class="w"></span> <span class="w"> </span>Привіт!<span class="w"></span> <span class="gi">+Which means Hello!</span><span class="w"></span>''') in - diffhtml) + diffhtml) resp = self.app.get(h.urlquote(ci + 'tree/привіт.txt') + '?diff=407950e8fba4dbc108ffbce0128ed1085c52cfd7&diformat=sidebyside') diffhtml = str(resp.html.select_one('.diffbrowser')) @@ -366,7 +366,7 @@ class TestRootController(_TestCase): <td class="lineno">2</td> <td class="diff-add"><pre>Which means Hello! </pre></td>''') in - diffhtml) + diffhtml) def test_diff_view_mode(self): ci = self._get_ci() @@ -533,7 +533,7 @@ class TestRootController(_TestCase): r.form['merge_disabled'].checked = True r = r.form.submit() assert (json.loads(self.webflash(r))['message'] == - "External checkout URL successfully changed. One-click merge disabled.") + "External checkout URL successfully changed. One-click merge disabled.") # for some reason c.app.config.options has old values still app_config = M.AppConfig.query.get(_id=c.app.config._id) assert app_config.options['external_checkout_url'] == 'http://foo.bar/baz' @@ -752,7 +752,7 @@ class TestFork(_TestCase): assert rev_links[0].get('href') == '/p/test2/code/ci/%s/' % c_id assert rev_links[0].getText() == '[%s]' % c_id[:6] assert (browse_links[0].get('href') == - '/p/test2/code/ci/%s/tree' % c_id) + '/p/test2/code/ci/%s/tree' % c_id) assert browse_links[0].getText().strip() == 'Tree' r = self.app.get('/p/test/src-git/merge-requests/1/commits_html', status=200) @@ -807,7 +807,7 @@ class TestFork(_TestCase): assert 'Merge Request #%s: (rejected)' % mr_num in r, r def test_merge_request_default_branches(self): - _select_val = lambda r, n: r.html.find('select', {'name': n}).find(selected=True).string + def _select_val(r, n): return r.html.find('select', {'name': n}).find(selected=True).string r = self.app.get('/p/test2/code/request_merge') assert _select_val(r, 'source_branch') == 'master' assert _select_val(r, 'target_branch') == 'master' @@ -1041,8 +1041,8 @@ class TestGitRename(TestController): # the diff portion of the output resp_no_ws = re.sub(r'\s+', '', str(resp)) assert ('<a href="/p/test/src-git/ci/fbb0644603bb6ecee3ebb62efe8c86efc9b84ee6/tree/f.txt" rel="nofollow">f.txt</a>' - 'to<a href="/p/test/src-git/ci/b120505a61225e6c14bee3e5b5862db81628c35c/tree/f2.txt" rel="nofollow">f2.txt</a>' - .replace(' ', '') in resp_no_ws) + 'to<a href="/p/test/src-git/ci/b120505a61225e6c14bee3e5b5862db81628c35c/tree/f2.txt" rel="nofollow">f2.txt</a>' + .replace(' ', '') in resp_no_ws) assert '<span class="empty-diff">File was renamed.</span>' in resp def test_directory_changed_type(self): @@ -1051,10 +1051,10 @@ class TestGitRename(TestController): resp_no_ws = re.sub(r'\s+', '', str(resp)) assert ('<a href="/p/test/src-git/ci/7b1c9ef214eb0ef8c06bada0966dd941f442beec/tree/b_dir" rel="nofollow">b_dir</a>' - '</h6>' - '<div id="diff-3" class="inline-diff-body">' - '<span class="empty-diff">Symlink.</span>' - .replace(' ', '') in resp_no_ws) + '</h6>' + '<div id="diff-3" class="inline-diff-body">' + '<span class="empty-diff">Symlink.</span>' + .replace(' ', '') in resp_no_ws) def test_symlink_in_tree(self): # change a_dir to a file; b_dir to a symlink @@ -1152,9 +1152,9 @@ class TestIncludeMacro(_TestCase): def test_include_file_cant_find_file(self): expected = "[[include can't find file %s in revision %s]]" assert (macro.include_file('src-git', 'a.txt') == - expected % ('a.txt', '1e146e67985dcd71c74de79613719bef7bddca4a')) + expected % ('a.txt', '1e146e67985dcd71c74de79613719bef7bddca4a')) assert (macro.include_file('src-git', 'a.txt', '6a45885ae7347f1cac5103b0050cc1be6a1496c8') == - expected % ('a.txt', '6a45885ae7347f1cac5103b0050cc1be6a1496c8')) + expected % ('a.txt', '6a45885ae7347f1cac5103b0050cc1be6a1496c8')) @patch('allura.model.repo.Blob.has_pypeline_view', new_callable=PropertyMock) @patch('allura.model.repo.Blob.has_html_view', new_callable=PropertyMock) diff --git a/ForgeImporters/forgeimporters/github/tests/test_wiki.py b/ForgeImporters/forgeimporters/github/tests/test_wiki.py index 3b7a7a05d..3d83b5742 100644 --- a/ForgeImporters/forgeimporters/github/tests/test_wiki.py +++ b/ForgeImporters/forgeimporters/github/tests/test_wiki.py @@ -49,8 +49,8 @@ class TestGitHubWikiImporter(TestCase): @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),\ - patch('forgeimporters.github.wiki.c'): + 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') u = Mock(name='c.user') @@ -179,7 +179,7 @@ class TestGitHubWikiImporter(TestCase): importer._with_history(self.commit2) assert upsert.call_args_list == [call('Home')] assert (render.call_args_list == - [call('Home.rst', '# test message')]) + [call('Home.rst', '# test message')]) @skipIf(module_not_available('html2text'), 'html2text required') @patch('forgeimporters.github.wiki.WM.Page.upsert') @@ -237,9 +237,9 @@ class TestGitHubWikiImporter(TestCase): assert f('[[Page-With-Spaces]]') == '[Page With Spaces]' assert f('[[Page / 1]]') == '[Page 1]' assert (f('[[Title|Page With Spaces]]') == - '[Title](Page With Spaces)') + '[Title](Page With Spaces)') assert (f('[[Title|Page-With-Spaces]]') == - '[Title](Page With Spaces)') + '[Title](Page With Spaces)') assert f('[[go here|Page / 1]]') == '[go here](Page 1)' def test_convert_gollum_page_links_escaped(self): @@ -250,9 +250,9 @@ class TestGitHubWikiImporter(TestCase): assert f("'[[Page-With-Spaces]]") == '[[Page-With-Spaces]]' assert f("'[[Page / 1]]") == '[[Page / 1]]' assert (f("'[[Title|Page With Spaces]]") == - '[[Title|Page With Spaces]]') + '[[Title|Page With Spaces]]') assert (f("'[[Title|Page-With-Spaces]]") == - '[[Title|Page-With-Spaces]]') + '[[Title|Page-With-Spaces]]') assert f("'[[go here|Page / 1]]") == '[[go here|Page / 1]]' def test_convert_gollum_external_links(self): @@ -260,14 +260,14 @@ class TestGitHubWikiImporter(TestCase): assert f('[[http://domain.net]]') == '<http://domain.net>' assert f('[[https://domain.net]]') == '<https://domain.net>' assert (f('[[Site|http://domain.net]]') == - '[Site](http://domain.net)') + '[Site](http://domain.net)') def test_convert_gollum_external_links_escaped(self): f = GitHubWikiImporter().convert_gollum_tags assert f("'[[http://domain.net]]") == '[[http://domain.net]]' assert f("'[[https://domain.net]]") == '[[https://domain.net]]' assert (f("'[[Site|http://domain.net]]") == - '[[Site|http://domain.net]]') + '[[Site|http://domain.net]]') def test_convert_gollum_toc(self): f = GitHubWikiImporter().convert_gollum_tags @@ -516,7 +516,7 @@ some text and **[Tips n\u2019 Tricks]** f = importer.convert_markup source = '*[[this checklist|Troubleshooting]]*' assert (f(source, 't.textile').strip() == - '**[this checklist](Troubleshooting)**') + '**[this checklist](Troubleshooting)**') @without_module('html2text') def test_convert_textile_special_tag_without_html2text(self): diff --git a/ForgeSVN/forgesvn/tests/functional/test_controllers.py b/ForgeSVN/forgesvn/tests/functional/test_controllers.py index a337014c6..6b0bea243 100644 --- a/ForgeSVN/forgesvn/tests/functional/test_controllers.py +++ b/ForgeSVN/forgesvn/tests/functional/test_controllers.py @@ -115,7 +115,7 @@ class TestRootController(SVNTestController): assert title == 'test SVN changes' description = channel.find('description').text assert (description == - 'Recent changes to SVN repository in test project') + 'Recent changes to SVN repository in test project') link = channel.find('link').text assert link == 'http://localhost/p/test/src/' earliest_commit = channel.findall('item')[-1] @@ -144,7 +144,7 @@ class TestRootController(SVNTestController): file_url = resp.html.find("a", string="/ЗРЯЧИЙ_ТА_ПОБАЧИТЬ")['href'] resp = self.app.get(file_url) assert ('This is readme' in # same content as the README file actually - resp.html.select_one('.codebrowser').text) + resp.html.select_one('.codebrowser').text) resp = self.app.get('/src/7/') print('file links on /src/7/ are:\n\t{}'.format( @@ -152,22 +152,22 @@ class TestRootController(SVNTestController): file_url = resp.html.find("a", string="/with%2Furlquote-literal.txt")['href'] file_resp = self.app.get(file_url) assert ('%2F means /' in - file_resp.html.select_one('.codebrowser').text) + file_resp.html.select_one('.codebrowser').text) file_url = resp.html.find("a", string='/with-percent%.txt')['href'] file_resp = self.app.get(file_url) assert ('%%%' in - file_resp.html.select_one('.codebrowser').text) + file_resp.html.select_one('.codebrowser').text) file_url = resp.html.find("a", string="/with space.txt")['href'] file_resp = self.app.get(file_url) assert ('spaces' in - file_resp.html.select_one('.codebrowser').text) + file_resp.html.select_one('.codebrowser').text) file_url = resp.html.find("a", string='/with"&:specials.txt')['href'] file_resp = self.app.get(file_url) assert ('"&: encodes as %22%26%3A' in - file_resp.html.select_one('.codebrowser').text) + file_resp.html.select_one('.codebrowser').text) def test_tree(self): resp = self.app.get('/src/1/tree/') @@ -324,7 +324,7 @@ class TestImportController(SVNTestController): r = self.app.post('/p/test/admin/empty/importer/do_import', {'checkout_url': 'http://10.0.0.0/trac/url'}) assert 'Invalid URL' in r - + r = self.app.post('/p/test/admin/empty/importer/do_import', {'checkout_url': 'http://fake.svn/'}) assert 'That is not a valid URL' not in r diff --git a/ForgeSVN/forgesvn/tests/model/test_repository.py b/ForgeSVN/forgesvn/tests/model/test_repository.py index fcd1f6656..4716bff9f 100644 --- a/ForgeSVN/forgesvn/tests/model/test_repository.py +++ b/ForgeSVN/forgesvn/tests/model/test_repository.py @@ -237,7 +237,7 @@ class TestSVNRepo(unittest.TestCase, RepoImplTestBase): def test_log(self): entries = list(self.repo.log(id_only=False, limit=25)) assert (entries[len(entries)-6:] == # only 6, so this test doesn't have to change when commits added - [ + [ {'parents': [5], 'refs': [], 'committed': { @@ -250,7 +250,7 @@ class TestSVNRepo(unittest.TestCase, RepoImplTestBase): 'date': datetime(2013, 11, 8, 13, 38, 11, 152821), 'name': 'coldmind', 'email': '' - }, 'size': None}, + }, 'size': None}, {'parents': [4], 'refs': [], 'committed': { @@ -405,8 +405,8 @@ class TestSVNRepo(unittest.TestCase, RepoImplTestBase): def test_diff_copy(self): entry = self.repo.commit(next(self.repo.log(5, id_only=True, limit=1))) assert dict(entry.diffs) == dict( - copied=[{'new': '/b', 'old': '/a', 'ratio': 1}], renamed=[], - changed=[], removed=[], added=[], total=1) + copied=[{'new': '/b', 'old': '/a', 'ratio': 1}], renamed=[], + changed=[], removed=[], added=[], total=1) def test_commit(self): entry = self.repo.commit(1) @@ -430,16 +430,16 @@ class TestSVNRepo(unittest.TestCase, RepoImplTestBase): def test_tarball(self): tmpdir = tg.config['scm.repos.tarball.root'] assert (self.repo.tarball_path == - os.path.join(tmpdir, 'svn/t/te/test/testsvn')) + os.path.join(tmpdir, 'svn/t/te/test/testsvn')) assert (self.repo.tarball_url('1') == - 'file:///svn/t/te/test/testsvn/test-src-r1.zip') + 'file:///svn/t/te/test/testsvn/test-src-r1.zip') self.repo.tarball('1') assert os.path.isfile( os.path.join(tmpdir, "svn/t/te/test/testsvn/test-src-r1.zip")) tarball_zip = ZipFile( os.path.join(tmpdir, 'svn/t/te/test/testsvn/test-src-r1.zip'), 'r') assert (tarball_zip.namelist() == - ['test-src-r1/', 'test-src-r1/README']) + ['test-src-r1/', 'test-src-r1/README']) shutil.rmtree(self.repo.tarball_path.encode('utf-8'), ignore_errors=True) @@ -768,12 +768,12 @@ class TestRepo(_TestWithRepo): def test_scm_host_url(self): assert (self.repo.clone_url('rw', 'nobody') == - 'svn+ssh://nobody@localhost:8022/scm-repo/p/test/test1/') + 'svn+ssh://nobody@localhost:8022/scm-repo/p/test/test1/') assert (self.repo.clone_url('https', 'nobody') == - 'https://nobody@localhost:8022/scm-repo/p/test/test1/') + 'https://nobody@localhost:8022/scm-repo/p/test/test1/') with h.push_config(self.repo.app.config.options, external_checkout_url='https://[email protected]/'): assert (self.repo.clone_url('https', 'user') == - 'https://[email protected]/') + 'https://[email protected]/') def test_guess_type(self): assert self.repo.guess_type('foo.txt') == ('text/plain', None) @@ -810,7 +810,7 @@ class TestRepo(_TestWithRepo): email=committer_email), _id=oid)).m.insert() self.repo._impl.refresh_commit_info = refresh_commit_info - _id = lambda oid: getattr(oid, '_id', str(oid)) + def _id(oid): return getattr(oid, '_id', str(oid)) self.repo.shorthand_for_commit = lambda oid: '[' + _id(oid) + ']' self.repo.url_for_commit = lambda oid: '/ci/' + _id(oid) + '/' self.repo.refresh() @@ -943,7 +943,7 @@ class TestCommit(_TestWithRepo): 'total': 5, } assert (self.ci.diffs.added == - ['a', 'a/a', 'a/a/a', 'a/a/b', 'a/b']) + ['a', 'a/a', 'a/a/a', 'a/a/b', 'a/b']) assert (self.ci.diffs.copied == self.ci.diffs.changed == self.ci.diffs.removed @@ -1050,7 +1050,7 @@ class TestRename(unittest.TestCase): result = self.repo._impl._check_changed_path( changed_path, '/test/path2/file.txt') assert {'path': '/test/path2/file.txt', - 'copyfrom_path': '/test/path/file.txt'} == result + 'copyfrom_path': '/test/path/file.txt'} == result class TestDirectRepoAccess: diff --git a/ForgeTracker/forgetracker/model/ticket.py b/ForgeTracker/forgetracker/model/ticket.py index 34aa72e94..562a30fd0 100644 --- a/ForgeTracker/forgetracker/model/ticket.py +++ b/ForgeTracker/forgetracker/model/ticket.py @@ -301,16 +301,16 @@ class Globals(MappedClass): fromaddr=str(c.user.email_address_header()), reply_to=str(c.user.email_address_header()), subject='[{}:{}] Mass ticket moving by {}'.format(c.project.shortname, - self.app_config.options.mount_point, - c.user.display_name)) + self.app_config.options.mount_point, + c.user.display_name)) tmpl = g.jinja2_env.get_template( 'forgetracker:data/mass_move_report.html') tmpl_context = { 'original_tracker': '{}:{}'.format(c.project.shortname, - self.app_config.options.mount_point), + self.app_config.options.mount_point), 'destination_tracker': '{}:{}'.format(tracker.project.shortname, - tracker.options.mount_point), + tracker.options.mount_point), 'tickets': [], } for user in users: @@ -345,9 +345,9 @@ class Globals(MappedClass): mail_tasks.sendmail.post(**mail) moved_from = '{}/{}'.format(c.project.shortname, - self.app_config.options.mount_point) + self.app_config.options.mount_point) moved_to = '{}/{}'.format(tracker.project.shortname, - tracker.options.mount_point) + tracker.options.mount_point) text = f'Tickets moved from {moved_from} to {moved_to}' Notification.post_user(c.user, None, 'flash', text=text) @@ -466,8 +466,8 @@ class Globals(MappedClass): fromaddr=str(c.user._id), reply_to=tg_config['forgemail.return_path'], subject='[{}:{}] Mass edit changes by {}'.format(c.project.shortname, - self.app_config.options.mount_point, - c.user.display_name), + self.app_config.options.mount_point, + c.user.display_name), ) tmpl = g.jinja2_env.get_template('forgetracker:data/mass_report.html') head = [] @@ -514,7 +514,7 @@ class Globals(MappedClass): self.invalidate_bin_counts() ThreadLocalORMSession.flush_all() app = '{}/{}'.format(c.project.shortname, - self.app_config.options.mount_point) + self.app_config.options.mount_point) count = len(tickets) text = 'Updated {} ticket{} in {}'.format( count, 's' if count != 1 else '', app) diff --git a/ForgeTracker/forgetracker/tests/functional/test_root.py b/ForgeTracker/forgetracker/tests/functional/test_root.py index 5c082033e..54a631f96 100644 --- a/ForgeTracker/forgetracker/tests/functional/test_root.py +++ b/ForgeTracker/forgetracker/tests/functional/test_root.py @@ -360,8 +360,8 @@ class TestFunctionalController(TrackerTestController): r = self.app.get('/bugs/bin_counts') assert r.json == {"bin_counts": [{"count": 2, "label": "Changes"}, - {"count": 0, "label": "Closed Tickets"}, - {"count": 2, "label": "Open Tickets"}]} + {"count": 0, "label": "Closed Tickets"}, + {"count": 2, "label": "Open Tickets"}]} """ forgetracker.model.ticket.Globals.bin_count doesn't do a permission check like corresponding milestone_count @@ -1982,7 +1982,7 @@ class TestFunctionalController(TrackerTestController): filtered_changes = c.app.globals.filtered_by_subscription(changes) filtered_users = [uid for uid, data in filtered_changes.items()] assert (sorted(filtered_users) == - sorted(u._id for u in users[:-1] + [admin])) + sorted(u._id for u in users[:-1] + [admin])) ticket_ids = [t._id for t in tickets] assert filtered_changes[users[0]._id] == set(ticket_ids[0:1]) assert filtered_changes[users[1]._id] == set(ticket_ids[:-1]) @@ -2484,12 +2484,12 @@ class TestFunctionalController(TrackerTestController): r = self.app.get('/rest/p/test/bugs/1/') r = json.loads(r.text) assert (r['ticket']['discussion_thread_url'] == - 'http://localhost/rest%s' % discussion_url) + 'http://localhost/rest%s' % discussion_url) slug = r['ticket']['discussion_thread']['posts'][0]['slug'] assert (r['ticket']['discussion_thread']['posts'][0]['attachments'][0]['url'] == - f'http://localhost{discussion_url}{slug}/attachment/test.txt') + f'http://localhost{discussion_url}{slug}/attachment/test.txt') assert (r['ticket']['discussion_thread']['posts'][0]['attachments'][0]['bytes'] == - 11) + 11) file_name = 'test_root.py' file_data = open(__file__, 'rb').read() @@ -2500,7 +2500,7 @@ class TestFunctionalController(TrackerTestController): r = self.app.get('/rest/p/test/bugs/1/') r = json.loads(r.text) assert (r['ticket']['attachments'][0]['url'] == - 'http://localhost/p/test/bugs/1/attachment/test_root.py') + 'http://localhost/p/test/bugs/1/attachment/test_root.py') def test_html_escaping(self): with mock.patch.object(mail_tasks.smtp_client, '_client') as _client: @@ -2512,7 +2512,7 @@ class TestFunctionalController(TrackerTestController): email = M.MonQTask.query.find( dict(task_name='allura.tasks.mail_tasks.sendmail')).first() assert (email.kwargs.subject == - '[test:bugs] #1 test <h2> ticket') + '[test:bugs] #1 test <h2> ticket') text = email.kwargs.text assert '** [bugs:#1] test <h2> ticket**' in text mail_tasks.sendmail( @@ -2529,8 +2529,8 @@ class TestFunctionalController(TrackerTestController): assert 'Subject: [test:bugs] #1 test <h2> ticket' in body # check html, need tags escaped assert ('<p><strong> <a class="alink" href="http://localhost/p/test/bugs/1/">[bugs:#1]</a>' - ' test <h2> ticket</strong></p>' in - body) + ' test <h2> ticket</strong></p>' in + body) # check plaintext (ok to have "html" tags) assert '** [bugs:#1] test <h2> ticket**' in body @@ -2896,7 +2896,7 @@ class TestCustomUserField(TrackerTestController): ticket_view = self.new_ticket(summary='test custom fields', **kw).follow() # summary header shows 'nobody' assert (squish_spaces(ticket_view.html.findAll('label', 'simple', text='Code Review:')[0].parent.text) == - ' Code Review: nobody ') + ' Code Review: nobody ') # form input is blank select = ticket_view.html.find('select', dict(name='ticket_form.custom_fields._code_review')) @@ -2911,7 +2911,7 @@ class TestCustomUserField(TrackerTestController): ticket_view = self.new_ticket(summary='test custom fields', **kw).follow() # summary header shows 'Test Admin' assert (squish_spaces(ticket_view.html.findAll('label', 'simple', text='Code Review:')[0].parent.text) == - ' Code Review: Test Admin ') + ' Code Review: Test Admin ') # form input is blank select = ticket_view.html.find('select', dict(name='ticket_form.custom_fields._code_review')) @@ -3106,7 +3106,7 @@ class TestBulkMove(TrackerTestController): assert len(emails) == 3 for email in emails: assert (email.kwargs.subject == - '[test:bugs] Mass ticket moving by Test Admin') + '[test:bugs] Mass ticket moving by Test Admin') first_user_email = M.MonQTask.query.find({ 'task_name': 'allura.tasks.mail_tasks.sendmail', 'kwargs.destinations': str(first_user._id) @@ -3143,7 +3143,7 @@ class TestBulkMove(TrackerTestController): notification_id = mbox.queue[-1] notification = M.Notification.query.get(_id=notification_id) assert (notification.text == - 'Tickets moved from test/bugs to test2/bugs2') + 'Tickets moved from test/bugs to test2/bugs2') @td.with_tool('test2', 'Tickets', 'bugs2') def test_monitoring_email(self): @@ -3169,7 +3169,7 @@ class TestBulkMove(TrackerTestController): assert len(emails) == 2 for email in emails: assert (email.kwargs.subject == - '[test:bugs] Mass ticket moving by Test Admin') + '[test:bugs] Mass ticket moving by Test Admin') admin_email = M.MonQTask.query.find({ 'task_name': 'allura.tasks.mail_tasks.sendmail', 'kwargs.destinations': str(M.User.by_username('test-admin')._id) @@ -3182,18 +3182,18 @@ class TestBulkMove(TrackerTestController): assert len(monitoring_email) == 1 admin_email_text = admin_email[0].kwargs.text assert ('test:bugs:#1 --> test2:bugs2:#1 A New Hope' in - admin_email_text) + admin_email_text) assert ('test:bugs:#2 --> test2:bugs2:#2 The Empire Strikes Back' in - admin_email_text) + admin_email_text) assert ('test:bugs:#3 --> test2:bugs2:#3 Return Of The Jedi' in - admin_email_text) + admin_email_text) monitoring_email_text = monitoring_email[0].kwargs.text assert ('test:bugs:#1 --> test2:bugs2:#1 A New Hope' in - monitoring_email_text) + monitoring_email_text) assert ('test:bugs:#2 --> test2:bugs2:#2 The Empire Strikes Back' in - monitoring_email_text) + monitoring_email_text) assert ('test:bugs:#3 --> test2:bugs2:#3 Return Of The Jedi' in - monitoring_email_text) + monitoring_email_text) @td.with_tool('test2', 'Tickets', 'bugs2') def test_monitoring_email_public_only(self): @@ -3226,7 +3226,7 @@ class TestBulkMove(TrackerTestController): assert len(emails) == 2 for email in emails: assert (email.kwargs.subject == - '[test:bugs] Mass ticket moving by Test Admin') + '[test:bugs] Mass ticket moving by Test Admin') admin = M.User.by_username('test-admin') admin_email = M.MonQTask.query.find({ 'task_name': 'allura.tasks.mail_tasks.sendmail', @@ -3273,7 +3273,7 @@ class TestBulkMove(TrackerTestController): assert len(emails) == 1 # only admin email sent for email in emails: assert (email.kwargs.subject == - '[test:bugs] Mass ticket moving by Test Admin') + '[test:bugs] Mass ticket moving by Test Admin') admin = M.User.by_username('test-admin') admin_email = M.MonQTask.query.find({ 'task_name': 'allura.tasks.mail_tasks.sendmail', @@ -3350,7 +3350,7 @@ class TestNotificationEmailGrouping(TrackerTestController): assert email.kwargs.message_id == ticket.url() + reply._id assert email.kwargs.in_reply_to == top_level_comment_msg_id assert (email.kwargs.references == - [ticket.message_id(), top_level_comment_msg_id]) + [ticket.message_id(), top_level_comment_msg_id]) def test_status_passthru(): diff --git a/scripts/migrations/034-update_subscriptions_ticket_and_mr_titles.py b/scripts/migrations/034-update_subscriptions_ticket_and_mr_titles.py index 94904c814..cb82382b8 100644 --- a/scripts/migrations/034-update_subscriptions_ticket_and_mr_titles.py +++ b/scripts/migrations/034-update_subscriptions_ticket_and_mr_titles.py @@ -42,7 +42,7 @@ def main(): if not sub.artifact_index_id: log.info('No artifact_index_id on %s', sub) continue - ticket = TM.Ticket.query.get(_id = ObjectId(sub.artifact_index_id.split('#')[1])) + ticket = TM.Ticket.query.get(_id=ObjectId(sub.artifact_index_id.split('#')[1])) if not ticket: log.info('Could not find ticket for %s', sub) continue @@ -60,12 +60,12 @@ def main(): if not sub.artifact_index_id: log.info('No artifact_index_id on %s', sub) continue - merge_request = M.MergeRequest.query.get(_id = ObjectId(sub.artifact_index_id.split('#')[1])) + merge_request = M.MergeRequest.query.get(_id=ObjectId(sub.artifact_index_id.split('#')[1])) if not merge_request: log.info('Could not find merge request for %s', sub) continue new_title = 'Merge Request #%d: %s' % (merge_request.request_number, merge_request.summary) - log.info('"%s" --> "%s"', sub.artifact_title , new_title) + log.info('"%s" --> "%s"', sub.artifact_title, new_title) if task != 'diff': sub.artifact_title = new_title session(sub).flush(sub)
