You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@allura.apache.org by di...@apache.org on 2022/09/15 13:46:38 UTC

[allura] 03/05: fixup! [#8455] allura pytest - fix misc test failures that popped up during pytest conversion

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

dill0wn pushed a commit to branch dw/8455
in repository https://gitbox.apache.org/repos/asf/allura.git

commit 47ec7df62614ae02e7731b5470c63c5bf5ccd8a0
Author: Dillon Walls <di...@slashdotmedia.com>
AuthorDate: Wed Sep 14 14:37:01 2022 +0000

    fixup! [#8455] allura pytest - fix misc test failures that popped up during pytest conversion
---
 Allura/allura/tests/exclude_from_rewrite_hook.py   |  31 +++++++
 .../allura/tests/functional/test_neighborhood.py   |   8 +-
 Allura/allura/tests/test_plugin.py                 |  35 ++++---
 Allura/allura/tests/test_tasks.py                  |  38 +++-----
 Allura/allura/tests/test_webhooks.py               | 101 +++++++++++----------
 5 files changed, 117 insertions(+), 96 deletions(-)

diff --git a/Allura/allura/tests/exclude_from_rewrite_hook.py b/Allura/allura/tests/exclude_from_rewrite_hook.py
new file mode 100644
index 000000000..509841776
--- /dev/null
+++ b/Allura/allura/tests/exclude_from_rewrite_hook.py
@@ -0,0 +1,31 @@
+import sys
+
+from allura.app import Application
+from allura.lib.decorators import task
+from allura.lib.exceptions import CompoundError
+
+
+class ThemeProviderTestApp(Application):
+    """
+    If this test class is added directly to a test module, pkg_resources internals
+    will throw this error:
+        NotImplementedError: Can't perform this operation for unregistered loader type
+    This is because pytest adds a hook to override the default assert behavior and this
+    conflicts/messes-with pkg_resources. Theoretically on python > py37, importlib.resources
+    can do the same things as pkg_resources and faster, but those solutions don't currently
+    work on py37.
+    """
+    icons = {
+        24: 'images/testapp_24.png',
+    }
+
+
+@task
+def raise_compound_exception():
+    errs = []
+    for x in range(10):
+        try:
+            assert False, 'assert %d' % x
+        except Exception:
+            errs.append(sys.exc_info())
+    raise CompoundError(*errs)
\ No newline at end of file
diff --git a/Allura/allura/tests/functional/test_neighborhood.py b/Allura/allura/tests/functional/test_neighborhood.py
index 5076ef049..3268a3b51 100644
--- a/Allura/allura/tests/functional/test_neighborhood.py
+++ b/Allura/allura/tests/functional/test_neighborhood.py
@@ -43,12 +43,12 @@ from allura.tests.pytest_helpers import with_nose_compatibility
 @with_nose_compatibility
 class TestNeighborhood(TestController):
 
-    def setUp(self):
-        super().setUp()
+    def setup_method(self, method):
+        super().setup_method(method)
         self._cleanup_audit_log()
 
-    def tearDown(self):
-        super().tearDown()
+    def teardown_method(self, method):
+        super().teardown_method(method)
         self._cleanup_audit_log()
 
     def _cleanup_audit_log(self):
diff --git a/Allura/allura/tests/test_plugin.py b/Allura/allura/tests/test_plugin.py
index 22a7ed8bf..56b358a79 100644
--- a/Allura/allura/tests/test_plugin.py
+++ b/Allura/allura/tests/test_plugin.py
@@ -35,7 +35,6 @@ from alluratest.tools import (
 from mock import Mock, MagicMock, patch
 
 from allura import model as M
-from allura.app import Application
 from allura.lib import plugin
 from allura.lib import phone
 from allura.lib import helpers as h
@@ -44,15 +43,19 @@ from allura.lib.plugin import ProjectRegistrationProvider
 from allura.lib.plugin import ThemeProvider
 from allura.lib.exceptions import ProjectConflict, ProjectShortnameInvalid
 from allura.tests.decorators import audits
+from allura.tests.exclude_from_rewrite_hook import ThemeProviderTestApp
 from alluratest.controller import setup_basic_test, setup_global_objects
 from allura.tests.pytest_helpers import with_nose_compatibility
 
 
+def setup_module(module):
+    setup_basic_test()
+
+
 @with_nose_compatibility
 class TestProjectRegistrationProvider:
 
     def setup_method(self, method):
-        setup_basic_test()
         self.provider = ProjectRegistrationProvider()
 
     @patch('allura.lib.security.has_access')
@@ -170,7 +173,6 @@ class TestProjectRegistrationProviderPhoneVerification:
         self.user = UserMock()
         self.nbhd = MagicMock()
 
-
     def test_phone_verified_disabled(self):
         with h.push_config(tg.config, **{'project.verify_phone': 'false'}):
             assert self.p.phone_verified(self.user, self.nbhd)
@@ -280,36 +282,31 @@ class TestProjectRegistrationProviderPhoneVerification:
                     assert result == g.phone_service.verify.return_value
             assert 5 == g.phone_service.verify.call_count
 
+
 @with_nose_compatibility
 class TestThemeProvider:
 
     @patch('allura.app.g')
     @patch('allura.lib.plugin.g')
+    # FIXME: check with dave.
     def test_app_icon_str(self, plugin_g, app_g):
-        class TestApp(Application):
-            icons = {
-                24: 'images/testapp_24.png',
-            }
-        plugin_g.entry_points = {'tool': {'testapp': TestApp}}
-        assert (ThemeProvider().app_icon_url('testapp', 24) ==
-                      app_g.theme_href.return_value)
+        plugin_g.entry_points = {'tool': {'testapp': ThemeProviderTestApp}}
+        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')
     def test_app_icon_str_invalid(self, g):
         g.entry_points = {'tool': {'testapp': Mock()}}
-        assert (ThemeProvider().app_icon_url('invalid', 24) ==
-                      None)
+        assert ThemeProvider().app_icon_url('invalid', 24) == None
 
     @patch('allura.app.g')
     def test_app_icon_app(self, g):
-        class TestApp(Application):
-            icons = {
-                24: 'images/testapp_24.png',
-            }
-        app = TestApp(None, None)
-        assert (ThemeProvider().app_icon_url(app, 24) ==
-                      g.theme_href.return_value)
+        app = ThemeProviderTestApp(None, None)
+        assert ThemeProvider().app_icon_url(app, 24) == \
+            g.theme_href.return_value
         g.theme_href.assert_called_with('images/testapp_24.png')
 
 
diff --git a/Allura/allura/tests/test_tasks.py b/Allura/allura/tests/test_tasks.py
index 735b3294b..429effd80 100644
--- a/Allura/allura/tests/test_tasks.py
+++ b/Allura/allura/tests/test_tasks.py
@@ -18,6 +18,7 @@
 import operator
 import shutil
 import sys
+from textwrap import dedent
 import unittest
 
 import six
@@ -52,6 +53,7 @@ from allura.tasks import export_tasks
 from allura.tasks import admin_tasks
 from allura.tests import decorators as td
 from allura.tests.pytest_helpers import with_nose_compatibility
+from allura.tests.exclude_from_rewrite_hook import raise_compound_exception
 from allura.lib.decorators import event_handler, task
 
 
@@ -148,7 +150,7 @@ class TestEventTasks(unittest.TestCase):
         assert M.MonQTask.query.get(task_name='allura.tasks.event_tasks.event', args=['my_event4'])
 
     def test_compound_error(self):
-        t = raise_exc.post()
+        t = raise_compound_exception.post()
         with LogCapture(level=logging.ERROR) as l, \
                 mock.patch.dict(tg.config, {'monq.raise_errors': False}):  # match normal non-test behavior
             t()
@@ -158,7 +160,7 @@ class TestEventTasks(unittest.TestCase):
         assert "AssertionError('assert 0'" in msg
         assert "AssertionError('assert 5'" in msg
         assert ' on job <MonQTask ' in msg
-        assert ' (error) P:10 allura.tests.test_tasks.raise_exc ' in msg
+        assert ' (error) P:10 allura.tests.exclude_from_rewrite_hook.raise_compound_exception ' in msg
         for x in range(10):
             assert ('assert %d' % x) in t.result
 
@@ -510,16 +512,17 @@ class TestMailTasks(unittest.TestCase):
 
     @td.with_tool('test', 'Tickets', 'bugs')
     def test_receive_autoresponse(self):
-        message = '''Date: Wed, 30 Oct 2013 01:38:40 -0700
-From: <te...@domain.net>
-To: <1...@bugs.test.p.in.localhost>
-Message-ID: <super-unique-id>
-Subject: Not here Re: Message notification
-Precedence: bulk
-X-Autoreply: yes
-Auto-Submitted: auto-replied
-
-I'm not here'''
+        message = dedent('''\
+            Date: Wed, 30 Oct 2013 01:38:40 -0700
+            From: <te...@domain.net>
+            To: <1...@bugs.test.p.in.localhost>
+            Message-ID: <super-unique-id>
+            Subject: Not here Re: Message notification
+            Precedence: bulk
+            X-Autoreply: yes
+            Auto-Submitted: auto-replied
+
+            I'm not here''')
         import forgetracker
         c.user = M.User.by_username('test-admin')
         with mock.patch.object(forgetracker.tracker_main.ForgeTrackerApp, 'handle_message') as hm:
@@ -597,17 +600,6 @@ def _my_event(event_type, testcase, *args, **kwargs):
     testcase.called_with.append((args, kwargs))
 
 
-@task
-def raise_exc():
-    errs = []
-    for x in range(10):
-        try:
-            assert False, 'assert %d' % x
-        except Exception:
-            errs.append(sys.exc_info())
-    raise CompoundError(*errs)
-
-
 class _TestArtifact(M.Artifact):
     _shorthand_id = FieldProperty(str)
     text = FieldProperty(str)
diff --git a/Allura/allura/tests/test_webhooks.py b/Allura/allura/tests/test_webhooks.py
index 5b9d5b1f2..8237847d6 100644
--- a/Allura/allura/tests/test_webhooks.py
+++ b/Allura/allura/tests/test_webhooks.py
@@ -132,6 +132,7 @@ class TestValidators(TestWebhookBase):
 
 @with_nose_compatibility
 class TestWebhookController(TestController):
+
     def setup_method(self, method):
         super().setup_method(method)
         self.patches = self.monkey_patch()
@@ -182,6 +183,56 @@ class TestWebhookController(TestController):
         else:
             assert False, 'Validation error not found'
 
+    def test_AAAA_WORKAROUND__edit(self):
+        """
+        This must run first in this test class for unknown reasons ever since
+            https://github.com/TurboGears/tg2/commit/02fb49b14e70fdd8ac16973488fb3637e5e59114
+
+        If any test runs the self.app.post from create_webhook before this one, then this test will fail on:
+            with td.audits(msg):
+                r = form.submit()
+        because WebhookValidator's `value` will be "create" instead of an objectid str
+
+        Maybe something to do with WebhookControllerMeta setup of `validate` decorators?
+        """
+        data1 = {'url': 'http://httpbin.org/post',
+                 'secret': 'secret'}
+        data2 = {'url': 'http://example.com/hook',
+                 'secret': 'secret2'}
+        self.create_webhook(data1).follow()
+        self.create_webhook(data2).follow()
+        assert M.Webhook.query.find().count() == 2
+        wh1 = M.Webhook.query.get(hook_url=data1['url'])
+        r = self.app.get(self.url + '/repo-push/%s' % wh1._id)
+        form = r.forms[0]
+        assert form['url'].value == data1['url']
+        assert form['secret'].value == data1['secret']
+        assert form['webhook'].value == str(wh1._id)
+        form['url'] = 'http://host.org/hook'
+        form['secret'] = 'new secret'
+        msg = 'edit webhook repo-push\n{} => {}\n{}'.format(
+            data1['url'], form['url'].value, 'secret changed')
+        with td.audits(msg):
+            r = form.submit()
+        wf = json.loads(self.webflash(r))
+        assert wf['status'] == 'ok'
+        assert wf['message'] == 'Edited successfully'
+        assert M.Webhook.query.find().count() == 2
+        wh1 = M.Webhook.query.get(_id=wh1._id)
+        assert wh1.hook_url == 'http://host.org/hook'
+        assert wh1.app_config_id == self.git.config._id
+        assert wh1.secret == 'new secret'
+        assert wh1.type == 'repo-push'
+
+        # Duplicates
+        r = self.app.get(self.url + '/repo-push/%s' % wh1._id)
+        form = r.forms[0]
+        form['url'] = data2['url']
+        r = form.submit()
+        self.find_error(r, '_the_form',
+                        '"repo-push" webhook already exists for Git http://example.com/hook',
+                        form_type='edit')
+
     def test_access(self):
         self.app.get(self.url + '/repo-push/')
         self.app.get(self.url + '/repo-push/',
@@ -256,56 +307,6 @@ class TestWebhookController(TestController):
         self.find_error(r, 'url',
                         'You must provide a full domain name (like qwer.com)')
 
-    def test_AAAA_WORKAROUND__edit(self):
-        """
-        This must run first in this test class for unknown reasons ever since
-            https://github.com/TurboGears/tg2/commit/02fb49b14e70fdd8ac16973488fb3637e5e59114
-
-        If any test runs the self.app.post from create_webhook before this one, then this test will fail on:
-            with td.audits(msg):
-                r = form.submit()
-        because WebhookValidator's `value` will be "create" instead of an objectid str
-
-        Maybe something to do with WebhookControllerMeta setup of `validate` decorators?
-        """
-        data1 = {'url': 'http://httpbin.org/post',
-                 'secret': 'secret'}
-        data2 = {'url': 'http://example.com/hook',
-                 'secret': 'secret2'}
-        self.create_webhook(data1).follow()
-        self.create_webhook(data2).follow()
-        assert M.Webhook.query.find().count() == 2
-        wh1 = M.Webhook.query.get(hook_url=data1['url'])
-        r = self.app.get(self.url + '/repo-push/%s' % wh1._id)
-        form = r.forms[0]
-        assert form['url'].value == data1['url']
-        assert form['secret'].value == data1['secret']
-        assert form['webhook'].value == str(wh1._id)
-        form['url'] = 'http://host.org/hook'
-        form['secret'] = 'new secret'
-        msg = 'edit webhook repo-push\n{} => {}\n{}'.format(
-            data1['url'], form['url'].value, 'secret changed')
-        with td.audits(msg):
-            r = form.submit()
-        wf = json.loads(self.webflash(r))
-        assert wf['status'] == 'ok'
-        assert wf['message'] == 'Edited successfully'
-        assert M.Webhook.query.find().count() == 2
-        wh1 = M.Webhook.query.get(_id=wh1._id)
-        assert wh1.hook_url == 'http://host.org/hook'
-        assert wh1.app_config_id == self.git.config._id
-        assert wh1.secret == 'new secret'
-        assert wh1.type == 'repo-push'
-
-        # Duplicates
-        r = self.app.get(self.url + '/repo-push/%s' % wh1._id)
-        form = r.forms[0]
-        form['url'] = data2['url']
-        r = form.submit()
-        self.find_error(r, '_the_form',
-                        '"repo-push" webhook already exists for Git http://example.com/hook',
-                        form_type='edit')
-
     def test_edit_validation(self):
         invalid = M.Webhook(
             type='invalid type',