You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@allura.apache.org by br...@apache.org on 2020/04/13 20:34:11 UTC

[allura] 19/22: [#8356] ordering consistency

This is an automated email from the ASF dual-hosted git repository.

brondsem pushed a commit to branch db/8356
in repository https://gitbox.apache.org/repos/asf/allura.git

commit 889981ee5ea37df03b2815aca7ea21a34acf3f02
Author: Dave Brondsema <da...@brondsema.net>
AuthorDate: Fri Apr 10 12:27:42 2020 -0400

    [#8356] ordering consistency
---
 Allura/allura/lib/custom_middleware.py               |  2 +-
 Allura/allura/lib/helpers.py                         | 15 +++++++++++++--
 Allura/allura/tests/test_commands.py                 | 13 ++++++++++---
 Allura/allura/tests/test_utils.py                    | 11 +++++++++--
 Allura/allura/tests/test_webhooks.py                 |  4 ++--
 Allura/allura/tests/unit/test_package_path_loader.py | 20 +++++++++++---------
 6 files changed, 46 insertions(+), 19 deletions(-)

diff --git a/Allura/allura/lib/custom_middleware.py b/Allura/allura/lib/custom_middleware.py
index 4ae9df1..1350b26 100644
--- a/Allura/allura/lib/custom_middleware.py
+++ b/Allura/allura/lib/custom_middleware.py
@@ -127,7 +127,7 @@ class CORSMiddleware(object):
         headers = [(str('Access-Control-Allow-Origin'), str('*'))]
         if preflight:
             ac_methods = ', '.join(self.allowed_methods)
-            ac_headers = ', '.join(self.allowed_headers)
+            ac_headers = ', '.join(sorted(self.allowed_headers))
             headers.extend([
                 (str('Access-Control-Allow-Methods'), str(ac_methods)),
                 (str('Access-Control-Allow-Headers'), str(ac_headers)),
diff --git a/Allura/allura/lib/helpers.py b/Allura/allura/lib/helpers.py
index 65c9a89..a0b1334 100644
--- a/Allura/allura/lib/helpers.py
+++ b/Allura/allura/lib/helpers.py
@@ -34,7 +34,7 @@ import random
 import six.moves.cPickle as pickle
 from hashlib import sha1
 from datetime import datetime, timedelta
-from collections import defaultdict
+from collections import defaultdict, OrderedDict
 import shlex
 import socket
 from functools import partial
@@ -1067,6 +1067,17 @@ def plain2markdown(txt, preserve_multiple_spaces=False, has_html_entities=False)
     return txt
 
 
+if six.PY2:
+    # https://stackoverflow.com/a/35968897
+    # in python 3.7 this can just be a defaultdict, probably
+    class OrderedDefaultDict(OrderedDict, defaultdict):
+        def __init__(self, default_factory=None, *args, **kwargs):
+            super(OrderedDefaultDict, self).__init__(*args, **kwargs)
+            self.default_factory = default_factory
+else:
+    OrderedDefaultDict = defaultdict  # py3.7 dicts are always ordered
+
+
 def iter_entry_points(group, *a, **kw):
     """Yields entry points that have not been disabled in the config.
 
@@ -1088,7 +1099,7 @@ def iter_entry_points(group, *a, **kw):
                 if ep.name not in disabled]
 
     def unique_eps(entry_points):
-        by_name = defaultdict(list)
+        by_name = OrderedDefaultDict(list)
         for ep in entry_points:
             by_name[ep.name].append(ep)
         for name, eps in six.iteritems(by_name):
diff --git a/Allura/allura/tests/test_commands.py b/Allura/allura/tests/test_commands.py
index e069359..ab077fd 100644
--- a/Allura/allura/tests/test_commands.py
+++ b/Allura/allura/tests/test_commands.py
@@ -17,6 +17,8 @@
 
 from __future__ import unicode_literals
 from __future__ import absolute_import
+
+import six
 from nose.tools import assert_raises, assert_in
 from testfixtures import OutputCapture
 
@@ -399,11 +401,16 @@ class TestShowModels(object):
         cmd = show_models.ShowModelsCommand('models')
         with OutputCapture() as output:
             cmd.run([test_config])
-        assert_in('''allura.model.notification.SiteNotification
+        if six.PY3:
+            assert_in('''allura.model.notification.SiteNotification
+         - <FieldProperty _id>
          - <FieldProperty content>
-         - <FieldProperty page_regex>
         ''', output.captured)
-
+        else:
+            # order of class fields are not preserved
+            assert_in('allura.model.notification.SiteNotification\n', output.captured)
+            assert_in('         - <FieldProperty _id>\n', output.captured)
+            assert_in('         - <FieldProperty content>\n', output.captured)
 
 class TestReindexAsTask(object):
 
diff --git a/Allura/allura/tests/test_utils.py b/Allura/allura/tests/test_utils.py
index f8d0a81..96273cb 100644
--- a/Allura/allura/tests/test_utils.py
+++ b/Allura/allura/tests/test_utils.py
@@ -23,10 +23,12 @@ import json
 import time
 import unittest
 import datetime as dt
-from ming.odm import session
 from os import path
 from io import open
 
+import six
+import ming
+from ming.odm import session
 from bson import ObjectId
 from webob import Request
 from mock import Mock, patch
@@ -75,6 +77,10 @@ class TestChunkedIterator(unittest.TestCase):
 
     def setUp(self):
         setup_unit_test()
+        config = {
+            'ming.main.uri': 'mim://allura_test',
+        }
+        ming.configure(**config)
         for i in range(10):
             M.User.upsert('sample-user-%d' % i)
 
@@ -347,7 +353,8 @@ def test_DateJSONEncoder():
     data = {'message': 'Hi!',
             'date': dt.datetime(2015, 1, 30, 13, 13, 13)}
     result = json.dumps(data, cls=utils.DateJSONEncoder)
-    assert_equal(result, '{"date": "2015-01-30T13:13:13Z", "message": "Hi!"}')
+    assert result in ['{"date": "2015-01-30T13:13:13Z", "message": "Hi!"}',
+                      '{"message": "Hi!", "date": "2015-01-30T13:13:13Z"}'], result
 
 
 def test_clean_phone_number():
diff --git a/Allura/allura/tests/test_webhooks.py b/Allura/allura/tests/test_webhooks.py
index 6430ae6..887141c 100644
--- a/Allura/allura/tests/test_webhooks.py
+++ b/Allura/allura/tests/test_webhooks.py
@@ -385,7 +385,7 @@ class TestWebhookController(TestController):
         assert_in('<h1>repo-push</h1>', r)
         rows = r.html.find('table').findAll('tr')
         assert_equal(len(rows), 2)
-        rows = sorted([self._format_row(row) for row in rows])
+        rows = sorted([self._format_row(row) for row in rows], key=lambda rows: rows[0]['text'])
         expected_rows = sorted([
             [{'text': wh1.hook_url},
              {'text': wh1.secret},
@@ -399,7 +399,7 @@ class TestWebhookController(TestController):
               'text': 'Edit'},
              {'href': self.url + '/repo-push/delete',
               'data-id': str(wh2._id)}],
-        ])
+        ], key=lambda rows: rows[0]['text'])
         assert_equal(rows, expected_rows)
         # make sure webhooks for another app is not visible
         assert_not_in('http://another-app.org/', r)
diff --git a/Allura/allura/tests/unit/test_package_path_loader.py b/Allura/allura/tests/unit/test_package_path_loader.py
index 56edd43..73c3321 100644
--- a/Allura/allura/tests/unit/test_package_path_loader.py
+++ b/Allura/allura/tests/unit/test_package_path_loader.py
@@ -17,6 +17,8 @@
 
 from __future__ import unicode_literals
 from __future__ import absolute_import
+
+from collections import OrderedDict
 from unittest import TestCase
 
 import jinja2
@@ -45,16 +47,16 @@ class TestPackagePathLoader(TestCase):
 
         assert_equal(paths, [
             ['site-theme', None],
-            ['ep2', 'path:eps.ep2'],
             ['ep0', 'path:eps.ep0'],
             ['ep1', 'path:eps.ep1'],
+            ['ep2', 'path:eps.ep2'],
             ['allura', '/'],
         ])
         assert_equal(type(paths[0]), list)
         assert_equal(resource_filename.call_args_list, [
-            mock.call('eps.ep2', ''),
             mock.call('eps.ep0', ''),
             mock.call('eps.ep1', ''),
+            mock.call('eps.ep2', ''),
         ])
 
     @mock.patch('pkg_resources.iter_entry_points')
@@ -70,7 +72,7 @@ class TestPackagePathLoader(TestCase):
 
         order_rules, replacement_rules = PackagePathLoader()._load_rules()
 
-        assert_equal(order_rules, [('allura', 'ep2'), ('ep0', 'allura')])
+        assert_equal(order_rules, [('ep0', 'allura'), ('allura', 'ep2')])
         assert_equal(replacement_rules, {'allura': 'ep1'})
 
         eps = iter_entry_points.return_value.__iter__.return_value = [
@@ -91,12 +93,12 @@ class TestPackagePathLoader(TestCase):
             ['ep2', '/ep2'],
             ['allura', '/'],
         ]
-        rules = {
-            'allura': 'ep2',
-            'site-theme': 'ep1',
-            'foo': 'ep1',
-            'ep0': 'bar',
-        }
+        rules = OrderedDict([
+            ('allura', 'ep2'),
+            ('site-theme', 'ep1'),
+            ('foo', 'ep1'),
+            ('ep0', 'bar'),
+        ])
 
         ppl._replace_signposts(paths, rules)