#344 Improve unit testing
Merged 6 years ago by sayanchowdhury. Opened 6 years ago by abompard.
abompard/fedora-hubs improve-testing  into  develop

file added
+5
@@ -0,0 +1,5 @@ 

+ [run]

+ source = hubs

+ omit =

+     hubs/tests/*

+     hubs/migrations/*

file modified
+1
@@ -21,3 +21,4 @@ 

  # tox

  .tox

  .coverage

+ htmlcov/

file modified
+3
@@ -6,6 +6,9 @@ 

  recursive-include hubs/migrations *.py *.mako *.rst

  include hubs/migrations/versions/.keep

  include hubs/actions.json

+ include hubs/tests/*.cfg

+ include hubs/tests/*.json

+ graft hubs/tests/vcr-request-data

  graft ansible

  graft docs

  prune docs/_build

file modified
+1 -4
@@ -22,12 +22,9 @@ 

  import hubs.widgets.caching

  import hubs.models

  

- import fedmsg.config

- 

- config = fedmsg.config.load_config()

  

  empty, full = 0, 0

- session = hubs.models.init(config['hubs.sqlalchemy.uri'])

+ session = hubs.app.session

  

  # Register widgets

  hubs.widgets.registry.register_list(hubs.app.app.config["WIDGETS"])

file modified
+3 -2
@@ -17,8 +17,9 @@ 

  

  import retask

  

- import fedmsg.config

- config = fedmsg.config.load_config()

+ from hubs.utils import get_fedmsg_config

+ 

+ config = get_fedmsg_config()

  

  for item in ['triage', 'work']:

      queue = retask.queue.Queue(config['hubs.redis.%s-queue-name' % item])

file modified
+2 -3
@@ -6,11 +6,10 @@ 

  

  from __future__ import unicode_literals, print_function

  

- import fedmsg.config

- 

  import hubs.models

+ from hubs.utils import get_fedmsg_config

  

- fedmsg_config = fedmsg.config.load_config()

+ fedmsg_config = get_fedmsg_config()

  

  session = hubs.models.init(fedmsg_config['hubs.sqlalchemy.uri'])

  

file modified
+1 -1
@@ -4,6 +4,6 @@ 

  View utils

  ----------

  

- .. automodule:: hubs.views.utils

+ .. automodule:: hubs.utils.views

     :members:

  

file modified
+5 -8
@@ -5,15 +5,13 @@ 

  import os

  

  import datanommer.models

- import fedmsg.config

- import fedmsg.meta

  import flask

  import flask.json

  import munch

  from flask_oidc import OpenIDConnect

  

  import hubs.models

- from hubs.utils import username2avatar

+ from hubs.utils import get_fedmsg_config, username2avatar

  

  app = flask.Flask(__name__)

  
@@ -32,9 +30,7 @@ 

  if 'HUBS_CONFIG' in os.environ:

      app.config.from_envvar('HUBS_CONFIG')

  

- fedmsg_config = fedmsg.config.load_config()

- fedmsg.meta.make_processors(**fedmsg_config)

- 

+ fedmsg_config = get_fedmsg_config()

  session = hubs.models.init(

      fedmsg_config.get('hubs.sqlalchemy.uri', 'sqlite:///'))

  datanommer.models.init(
@@ -98,12 +94,13 @@ 

      else:

          flask.g.auth = munch.Munch(logged_in=False, user=None)

  

+ 

  # Register widgets

- import hubs.widgets  # noqa

+ import hubs.widgets  # noqa: E402

  hubs.widgets.registry.register_list(app.config["WIDGETS"])

  

  # Register routes

- import hubs.views  # noqa

+ import hubs.views  # noqa: E402

  

  # Add widget-specific routes

  hubs.widgets.registry.register_routes(app)

file modified
+8 -12
@@ -27,8 +27,6 @@ 

  import random

  import sys

  

- import fedmsg.config

- import fedmsg.meta

  import retask.queue

  

  import hubs.app
@@ -37,13 +35,14 @@ 

  

  

  log = logging.getLogger('hubs.backend.triage')

- config = fedmsg.config.load_config()

+ fedmsg_config = hubs.app.fedmsg_config

+ session = hubs.app.session

  

  

- def triage(session, outbound, msg):

+ def triage(outbound, msg):

      topic = msg['topic']

  

-     for suffix in config['hubs.junk_suffixes']:

+     for suffix in fedmsg_config['hubs.junk_suffixes']:

          if topic.endswith(suffix):

              log.debug("  Dropping junk %r", topic)

              return
@@ -75,16 +74,14 @@ 

  

  

  def main(args):

-     logging.config.dictConfig(config['logging'])

+     logging.config.dictConfig(fedmsg_config['logging'])

      logging.basicConfig()

  

-     fedmsg.meta.make_processors(**config)

- 

      # XXX - for flask.url_for to work

      hubs.app.app.config['SERVER_NAME'] = '0.0.0.0:5000'

  

-     inbound_name = config['hubs.redis.triage-queue-name']

-     outbound_name = config['hubs.redis.work-queue-name']

+     inbound_name = fedmsg_config['hubs.redis.triage-queue-name']

+     outbound_name = fedmsg_config['hubs.redis.work-queue-name']

  

      log.info("Triage proc starting. Moving from %r to %r."

               % (inbound_name, outbound_name))
@@ -103,9 +100,8 @@ 

                  "(triage backlog: %r, work backlog: %r)  Working on %r %r",

                  inbound.length, outbound.length, msg['msg_id'], msg['topic'],

              )

-             session = hubs.models.init(config['hubs.sqlalchemy.uri'])

              with hubs.app.app.app_context():  # so url_for works

-                 for task in triage(session, outbound, msg):

+                 for task in triage(outbound, msg):

                      log.debug("  Triage sending %r to workers." % task)

                      outbound.enqueue(task)

              log.debug("  Done with triage of %r.", msg['msg_id'])

file modified
+4 -8
@@ -31,8 +31,6 @@ 

  import logging.config

  import sys

  

- import fedmsg.config

- import fedmsg.meta

  import retask.queue

  

  import hubs.app
@@ -41,7 +39,8 @@ 

  

  

  log = logging.getLogger('hubs.backend.worker')

- config = fedmsg.config.load_config()

+ fedmsg_config = hubs.app.fedmsg_config

+ session = hubs.app.session

  

  

  def work(widget_idx, fn_name):
@@ -55,7 +54,6 @@ 

  

  

  def handle(idx, fn_name):

-     session = hubs.models.init(config['hubs.sqlalchemy.uri'])

  

      try:

          with hubs.app.app.app_context():  # so url_for works
@@ -69,15 +67,13 @@ 

  

  

  def main(args):

-     logging.config.dictConfig(config['logging'])

+     logging.config.dictConfig(fedmsg_config['logging'])

      logging.basicConfig()

  

-     fedmsg.meta.make_processors(**config)

- 

      # XXX - for flask.url_for to work

      hubs.app.app.config['SERVER_NAME'] = '0.0.0.0:5000'

  

-     name = config['hubs.redis.work-queue-name']

+     name = fedmsg_config['hubs.redis.work-queue-name']

      log.info("Worker starting, connecting to retask queue %r." % name)

      queue = retask.queue.Queue(name)

      queue.connect()

file modified
+2 -3
@@ -2,13 +2,12 @@ 

  

  from logging.config import fileConfig

  

- import fedmsg.config

  from alembic import context

  from sqlalchemy import create_engine, pool

  

  

  try:

-     import hubs  # noqa

+     import hubs

  except ImportError:

      import os

      import sys
@@ -27,7 +26,7 @@ 

      # This line sets up loggers basically.

      fileConfig(context.config.config_file_name)

  

- fedmsg_config = fedmsg.config.load_config()

+ fedmsg_config = hubs.app.fedmsg_config

  url = fedmsg_config['hubs.sqlalchemy.uri']

  target_metadata = BASE.metadata

  

file modified
+49 -42
@@ -13,49 +13,52 @@ 

  import vcr

  from flask.signals import template_rendered

  

- import hubs.models

- 

+ here = dirname(__file__)

  cassette_dir = os.path.join(dirname(__file__), 'vcr-request-data')

  

+ if "HUBS_CONFIG" not in os.environ:

+     os.environ["HUBS_CONFIG"] = os.path.join(here, "hubs_test.cfg")

+ if "FEDMSG_CONFIG" not in os.environ:

+     os.environ["FEDMSG_CONFIG"] = os.path.join(here, "fedmsg_test.cfg")

+ 

+ import hubs.app     # noqa: E402

+ import hubs.models  # noqa: E402

+ 

  

  class APPTest(unittest.TestCase):

+ 

      def setUp(self):

-         filename = os.path.join(cassette_dir, self.id())

-         self.vcr = vcr.use_cassette(filename, record_mode='new_episodes')

+         vcr_filename = os.path.join(cassette_dir, self.id())

+         self.vcr = vcr.use_cassette(vcr_filename, record_mode='new_episodes')

          self.vcr.__enter__()

  

-         import hubs.app

-         hubs.app.fedmsg_config = {

-             'hubs.sqlalchemy.uri': 'sqlite://',  # in memory

-         }

          hubs.app.session = hubs.models.init(

              hubs.app.fedmsg_config['hubs.sqlalchemy.uri'],

              create=True,

          )

          hubs.app.app.config['TESTING'] = True

+ 

          self.app = hubs.app.app.test_client()

          self.app.testing = True

          self.session = hubs.app.session

-         from hubs.widgets.caching import cache

-         cache.configure(backend='dogpile.cache.null',

-                         replace_existing_backend=True)

+ 

          self.populate()

  

      def tearDown(self):

-         self.vcr.__exit__()

          self.session.remove()

+         self.vcr.__exit__()

  

      def populate(self):

          for user in ['devyani7', 'dhrish', 'shalini', 'ralph', 'decause']:

              fullname = user.title()

              hubs.models.User.get_or_create(

-                 hubs.app.session, username=user, fullname=fullname)

+                 self.session, username=user, fullname=fullname)

              saved_notif = hubs.models.SavedNotification(

                  username=user, markup='foo', link='bar'

              )

-             hubs.app.session.add(saved_notif)

+             self.session.add(saved_notif)

  

-         hubs.app.session.flush()

+         self.session.flush()

  

          hub = hubs.models.Hub.by_name('ralph')

          widget = hubs.models.Widget(
@@ -71,39 +74,21 @@ 

                  hub.last_refreshed = datetime.utcnow() - timedelta(days=100)

                  hub.last_updated = datetime.utcnow() - timedelta(days=200)

  

-             hubs.app.session.add(hub)

-             hubs.app.session.add(

+             self.session.add(hub)

+             self.session.add(

                  hubs.models.HubConfig(hub=hub, summary="the %s team" % team))

              widget = hubs.models.Widget(plugin='meetings', index=11,

                                          _config=json.dumps({'calendar': team}))

              hub.widgets.append(widget)

-         hubs.app.session.commit()

+         self.session.commit()

  

      # TODO - test that it is in the registry

      # TODO - test that it has all the things it needs

  

-     def widget_instance(self, hubname, plugin):

-         hub = hubs.models.Hub.by_name(hubname)

-         if not hub:

-             raise ValueError("No such hub %r" % hubname)

-         for widget in hub.widgets:

-             if widget.plugin == plugin:

-                 return widget

-         raise KeyError("No such widget found for %s/%s" % (hubname, plugin))

- 

-     @staticmethod

-     def get_fedmsg(idx):

-         url = 'https://apps.fedoraproject.org/datagrepper/id'

-         response = requests.get(url, params=dict(id=idx))

-         if not bool(response):

-             raise IOError("Failed to talk to %r %r" % (response.url, response))

-         return response.json()

- 

      def check_url(self, url, user=None, code=200):

          with auth_set(hubs.app.app, user):

-             with hubs.app.app.app_context():

-                 with captured_templates(flask.current_app) as templates:

-                     response = self.app.get(url)

+             with captured_templates(hubs.app.app) as templates:

+                 response = self.app.get(url)

          self.assertEqual(response.status_code, code)

          if templates:

              self.assertEqual(len(templates), 1)
@@ -115,6 +100,24 @@ 

          return response

  

  

+ def get_fedmsg(idx):

+     url = 'https://apps.fedoraproject.org/datagrepper/id'

+     response = requests.get(url, params=dict(id=idx))

+     if not bool(response):

+         raise IOError("Failed to talk to %r %r" % (response.url, response))

+     return response.json()

+ 

+ 

+ def widget_instance(hubname, plugin):

+     hub = hubs.models.Hub.by_name(hubname)

+     if not hub:

+         raise ValueError("No such hub %r" % hubname)

+     for widget in hub.widgets:

+         if widget.plugin == plugin:

+             return widget

+     raise KeyError("No such widget found for %s/%s" % (hubname, plugin))

+ 

+ 

  @contextmanager

  def auth_set(APP, auth):

      """
@@ -137,7 +140,13 @@ 

          if not auth:

              g.auth = munch.Munch(logged_in=False, user=None)

  

-     with appcontext_pushed.connected_to(handler, APP):

+     if flask._app_ctx_stack.top is None:

+         # App context isn't pushed yet

+         with appcontext_pushed.connected_to(handler, APP):

+             yield

+     else:

+         # App context already pushed

+         handler(APP)

          yield

  

  
@@ -179,9 +188,7 @@ 

      usage.

  

      The argument is the signal emitter.  When calling a core Hubs view, this is

-     the Hubs app (``hubs.app.app`` or ``self.app.application`` if you're in an

-     :py:class:`APPTest` subclass).  If you're calling a widget view, the signal

-     emitter is the widget class, as found in the widgets registry.

+     the Hubs app (``hubs.app.app``).

  

      Args:

          app: The signal emitter.

@@ -0,0 +1,53 @@ 

+ # Fedmsg configuration for testing

+ 

+ config = {

+     #'hubs.consumer.enabled': True,

+     'hubs.sqlalchemy.uri': 'sqlite://',  # in memory

+ 

+     ## For communication between fedmsg-hub and the cache worker farm

+     #'hubs.redis.triage-queue-name': 'fedora-hubs-triage-queue',

+     #'hubs.redis.work-queue-name': 'fedora-hubs-work-queue',

+ 

+     ## Junk junk junk.. that we don't care about.  Drop it!

+     #'hubs.junk_suffixes': [

+     #    'buildsys.tag',

+     #    'buildsys.untag',

+     #    'buildsys.rpm.sign',

+     #],

+ 

+     'endpoints': {

+         "fedora-infrastructure": [

+             "tcp://hub.fedoraproject.org:9940",

+         ]

+     },

+ 

+     #'datanommer.sqlalchemy.uri':

+     #    'postgres://postgres:laksjdf@127.0.0.1/datanommer',

+ 

+     #'fmn.url': 'https://apps.fedoraproject.org/notifications',

+ 

+     ## Some configuration for the rule processors

+     #"fmn.rules.utils.use_pkgdb2": False,

+     #"fmn.rules.utils.pkgdb2_api_url": "http://209.132.184.188/api/",

+     #"fmn.rules.cache": {

+     #    "backend": "dogpile.cache.dbm",

+     #    "expiration_time": 300,

+     #    "arguments": {

+     #        "filename": "/var/tmp/fmn-cache.db",

+     #    },

+     #},

+ 

+     # No cache during testing.

+     "fedora-hubs.cache": {

+         "backend": "dogpile.cache.null",

+     },

+ 

+     ## Run datanommer locally, just for development.

+     #'datanommer.enabled': True,

+     #'datanommer.sqlalchemy.url':

+     #    'postgres://postgres:laksjdf@127.0.0.1/datanommer',

+ 

+     ## Only do one of these so we can try to not run out of memory.

+     #'moksha.workers_per_consumer': 1,

+ }

+ 

file modified
+9 -4
@@ -1,5 +1,6 @@ 

  from __future__ import absolute_import, unicode_literals

  

+ from hubs.app import app

  from hubs.authz import ObjectAuthzMixin, AccessLevel, PERMISSIONS

  from hubs.tests import APPTest, FakeAuthorization

  
@@ -18,10 +19,14 @@ 

  

  class AuthzTestCase(APPTest):

  

-     def run(self, *args, **kwargs):

-         import hubs.app

-         with hubs.app.app.app_context():

-             super(AuthzTestCase, self).run(*args, **kwargs)

+     def setUp(self):

+         super(AuthzTestCase, self).setUp()

+         self.app_context = app.app_context()

+         self.app_context.__enter__()

+ 

+     def tearDown(self):

+         self.app_context.__exit__(None, None, None)

+         super(AuthzTestCase, self).tearDown()

  

      def test_mixin_access_level_anonymous(self):

          obj = TestObj()

@@ -1,587 +0,0 @@ 

- from __future__ import unicode_literals

- 

- import unittest

- from six.moves.urllib.parse import urlparse

- 

- from flask import json

- from werkzeug.datastructures import ImmutableMultiDict

- 

- import hubs

- from hubs import tests

- from hubs.app import app

- 

- import hubs.models

- 

- 

- class HubsAPITest(hubs.tests.APPTest):

- 

-     def test_index_logged_out(self):

-         result = self.app.get('/', follow_redirects=False)

-         self.assertEqual(result.status_code, 302)

-         self.assertEqual(urlparse(result.location).path, "/login")

- 

-     def test_index_logged_in(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             result = self.app.get('/', follow_redirects=True)

-             # its trying to redirect to login id.fedoraproject.org/openid

-             # assert the status code of the response

-             self.assertEqual(result.status_code, 200)

-             self.assertNotIn(

-                 'Not logged in.  Click to <a href="/login">login</a>',

-                 result.get_data(as_text=True))

- 

-     def test_hub_logged_out(self):

-         with tests.auth_set(app, None):  # check_auth doesn't load in unittest

-             result = self.app.get('/ralph', follow_redirects=True)

-             self.assertEqual(result.status_code, 200)

-             match_expected = r'<h5[^>]*>Ralph</h5>'

-             self.assertRegexpMatches(

-                 result.get_data(as_text=True), match_expected)

-             str_expected = 'Not logged in.'

-             self.assertIn(str_expected, result.get_data(as_text=True))

- 

-     def test_groups_logged_out(self):

-         result = self.app.get('/groups', follow_redirects=False)

-         # assert the status code of the response

-         self.assertEqual(result.status_code, 302)

-         # this will redirect to fedora.login

-         self.assertEqual(urlparse(result.location).path, "/login")

- 

-     def test_groups_logged_in(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             result = self.app.get('/groups', follow_redirects=True)

-             # assert the status code of the response

-             self.assertEqual(result.status_code, 200)

-             self.assertIn("ZOMG -  is the Hub Of The Month!",

-                           result.get_data(as_text=True))

- 

-     def test_hub_logged_in(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             result = self.app.get('/ralph', follow_redirects=True)

-             self.assertEqual(result.status_code, 200)

-             self.assertNotIn(

-                 'Not logged in.  Click to <a href="/login">login</a>',

-                 result.get_data(as_text=True))

- 

-     def test_hub_preview(self):

-         hub = hubs.models.Hub.by_name('ralph')

-         hub.config.visibility = "preview"

-         # Preview hubs are accessible to anonymous users (but some

-         # widgets may be restricted).

-         with tests.auth_set(app, None):

-             result = self.app.get('/ralph', follow_redirects=True)

-             self.assertEqual(result.status_code, 200)

- 

-     def test_hub_private(self):

-         hub = hubs.models.Hub.by_name('ralph')

-         hub.config.visibility = "private"

-         self.session.commit()

-         # Private hubs are not accessible to anonymous users.

-         with tests.auth_set(app, None):

-             result = self.app.get('/ralph', follow_redirects=True)

-             self.assertEqual(result.status_code, 403)

-         # But they are accessible to members.

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             result = self.app.get('/ralph', follow_redirects=True)

-             self.assertEqual(result.status_code, 200)

- 

-     def test_hub_json(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             result = self.app.get('/ralph/json', follow_redirects=True)

-         # assert the status code of the response

-         self.assertEqual(result.status_code, 200)

-         data = {

-             "config": {

-                 "avatar": "https://seccdn.libravatar.org/avatar/"

-                           "9c9f7784935381befc302fe3c814f9136e7a339"

-                           "53d0318761669b8643f4df55c?s=312&d=retro",

-                 'chat_channel': None,

-                 'chat_domain': None,

-                 "left_width": 8,

-                 "summary": "Ralph",

-                 "visibility": "public",

-             },

-             "members": ["ralph"],

-             "name": "ralph",

-             "owners": ["ralph"],

-             "subscribers": [],

-             "widgets": [37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 61],

-         }

-         self.assertDictEqual(data, json.loads(result.get_data(as_text=True)))

- 

-     def test_hub_private_json(self):

-         hub = hubs.models.Hub.by_name('ralph')

-         hub.config.visibility = "private"

-         self.session.commit()

-         # Private hubs are not accessible to anonymous users.

-         with tests.auth_set(app, None):

-             result = self.app.get('/ralph/json', follow_redirects=True)

-             self.assertEqual(result.status_code, 403)

-         # But they are accessible to members.

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             result = self.app.get('/ralph/json', follow_redirects=True)

-             self.assertEqual(result.status_code, 200)

- 

-     def test_hub_edit_get_logged_out(self):

-         with tests.auth_set(app, None):

-             result = self.app.get('/ralph/edit', follow_redirects=False)

-         self.assertEqual(result.status_code, 302)

-         self.assertEqual(urlparse(result.location).path, "/login")

- 

-     def test_hub_edit_get_logged_in_not_owner(self):

-         user = tests.FakeAuthorization('not_ralph')

-         with tests.auth_set(app, user):

-             result = self.app.get('/ralph/edit', follow_redirects=True)

-             self.assertEqual(result.status_code, 403)

- 

-     def test_hub_edit_get_logged_in_owner(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             result = self.app.get('/ralph/edit', follow_redirects=True)

-             self.assertEqual(result.status_code, 200)

- 

-     def test_hub_edit_post_logged_out(self):

-         with tests.auth_set(app, None):

-             result = self.app.post('/ralph/edit', follow_redirects=False)

-         self.assertEqual(result.status_code, 302)

-         self.assertEqual(urlparse(result.location).path, "/login")

- 

-     def test_hub_edit_post_logged_in_not_owner(self):

-         user = tests.FakeAuthorization('not_ralph')

-         with tests.auth_set(app, user):

-             result = self.app.post('/ralph/edit', follow_redirects=True)

-             self.assertEqual(result.status_code, 403)

- 

-     def test_hub_edit_post_logged_in_owner_empty_data(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             result = self.app.post('/ralph/edit', data={},

-                                    follow_redirects=True)

-             self.assertEqual(result.status_code, 200)

-             self.assertNotIn(

-                 'Not logged in.  Click to <a href="/login">login</a>',

-                 result.get_data(as_text=True))

-             self.assertIn(

-                 '<a href="#" class="dropdown-item">Full Name: '

-                 'fullname: ralph</a>', result.get_data(as_text=True))

- 

-     def test_hub_edit_post_logged_in_owner_valid_data(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             data = ImmutableMultiDict(

-                 [('right_indexes[]', u'0'), ('right_indexes[]', u'1'),

-                  ('right_indexes[]', u'2'), ('right_indexes[]', u'3'),

-                  ('right_indexes[]', u'4'), ('right_indexes[]', u'5'),

-                  ('right_indexes[]', u'6'), ('right_indexes[]', u'7'),

-                  ('right_indexes[]', u'8'), ('right_widgets[]', u'32'),

-                  ('right_widgets[]', u'33'), ('right_widgets[]', u'34'),

-                  ('right_widgets[]', u'35'), ('right_widgets[]', u'36'),

-                  ('right_widgets[]', u'37'), ('right_widgets[]', u'38'),

-                  ('right_widgets[]', u'39'), ('right_widgets[]', u'40'),

-                  ('js', u'true'), ('left_indexes[]', u'0'),

-                  ('left_indexes[]', u'1'), ('left_widgets[]', u'31'),

-                  ('left_widgets[]', u'32')])

-             result = self.app.post('/ralph/edit', data=data,

-                                    follow_redirects=True)

-             self.assertEqual(result.status_code, 200)

-             self.assertEqual(result.get_data(as_text=True), 'ok')

- 

-     def test_hub_edit_post_logged_in_owner_invalid_data_1(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             # some indexes and widgets are not integers

-             data = ImmutableMultiDict(

-                 [('right_indexes[]', u'0a'), ('right_indexes[]', u'1'),

-                  ('right_indexes[]', u'2'), ('right_indexes[]', u'3'),

-                  ('right_indexes[]', u'4'), ('right_indexes[]', u'5'),

-                  ('right_indexes[]', u'6'), ('right_indexes[]', u'7'),

-                  ('right_indexes[]', u'8'), ('right_widgets[]', u'32'),

-                  ('right_widgets[]', u'33a'), ('right_widgets[]', u'34'),

-                  ('right_widgets[]', u'35'), ('right_widgets[]', u'36'),

-                  ('right_widgets[]', u'37'), ('right_widgets[]', u'38'),

-                  ('right_widgets[]', u'39'), ('right_widgets[]', u'40'),

-                  ('js', u'true'), ('left_indexes[]', u'0a'),

-                  ('left_indexes[]', u'1'), ('left_widgets[]', u'31a'),

-                  ('left_widgets[]', u'32')])

-             result = self.app.post('/ralph/edit', data=data,

-                                    follow_redirects=True)

-             self.assertEqual(result.status_code, 400)

- 

-     def test_hub_edit_post_logged_in_owner_invalid_data_2(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             # indexes len don't match widgets len

-             data = ImmutableMultiDict(

-                 [('right_indexes[]', u'1'), ('right_indexes[]', u'2'),

-                  ('right_indexes[]', u'3'), ('right_indexes[]', u'4'),

-                  ('right_indexes[]', u'5'), ('right_indexes[]', u'6'),

-                  ('right_indexes[]', u'7'), ('right_indexes[]', u'8'),

-                  ('right_widgets[]', u'32'), ('right_widgets[]', u'34'),

-                  ('right_widgets[]', u'35'), ('right_widgets[]', u'36'),

-                  ('right_widgets[]', u'37'), ('right_widgets[]', u'38'),

-                  ('right_widgets[]', u'39'), ('right_widgets[]', u'40'),

-                  ('js', u'true'), ('left_indexes[]', u'0'),

-                  ('left_indexes[]', u'1'), ('left_widgets[]', u'32')])

-             result = self.app.post('/ralph/edit', data=data,

-                                    follow_redirects=True)

-             self.assertEqual(result.status_code, 400)

- 

-     def test_login_already_loggedin(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             result = self.app.get('/login', follow_redirects=False)

-             self.assertEqual(result.status_code, 302)

-             self.assertEqual(

-                 urlparse(result.location).path,

-                 "/openidc/Authorization")

- 

-     def test_hub_add_widget_get_no_args(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             result = self.app.get('/ralph/add', follow_redirects=False)

-         self.assertEqual(result.status_code, 400)

-         expected_str = 'Invalid position provided'

-         self.assertIn(expected_str, result.get_data(as_text=True))

- 

-     def test_hub_add_widget_get_with_args(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             result = self.app.get('/ralph/add?position=right',

-                                   follow_redirects=True)

-         self.assertEqual(result.status_code, 200)

-         page_html = result.get_data(as_text=True)

-         self.assertIn('Adding a widget to hub: ralph', page_html)

-         self.assertIn('<form method="post" action="/ralph/add">', page_html)

-         self.assertIn('<input type="hidden" name="position" value="right" />',

-                       page_html)

- 

-     def test_hub_add_widget_post_no_widget_name(self):

-         data = {"position": "left"}

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             result = self.app.post(

-                 '/ralph/add', data=data, follow_redirects=False)

-         self.assertEqual(result.status_code, 400)

-         expected_str = 'Invalid request sent'

-         self.assertIn(expected_str, result.get_data(as_text=True))

- 

-     def test_hub_add_widget_post_invalid_widget_name(self):

-         data = {'widget': 'invalid_widget_name',

-                 'position': 'right'}

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             result = self.app.post(

-                 '/ralph/add', data=data, follow_redirects=False)

-         self.assertEqual(result.status_code, 404)

-         expected_str = 'Unknown widget called'

-         self.assertIn(expected_str, result.get_data(as_text=True))

- 

-     def test_hub_add_widget_post_valid_widget_name_no_args(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             data = {

-                 'widget': 'memberships',

-                 'position': 'right',

-                 }

-             result = self.app.post('/ralph/add', data=data)

-             self.assertEqual(result.status_code, 200)

-             self.assertEqual(

-                 json.loads(result.get_data(as_text=True)),

-                 {"status": "ADDED"})

-             result = self.app.get('/ralph/edit')

-             self.assertEqual(result.status_code, 200)

-             page_html = result.get_data(as_text=True)

-             self.assertIn('data-url="/ralph/w/memberships/', page_html)

- 

-     def test_hub_add_widget_post_valid_widget_name_with_args(self):

-         self.assertEqual(

-             hubs.models.Widget.query.filter(

-                 hubs.models.Hub.name == "ralph",

-                 hubs.models.Widget.plugin == "about",

-             ).count(), 1)

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             data = {

-                 'text': 'text of widget',

-                 'position': 'right',

-                 }

-             result = self.app.post('/ralph/add/about', data=data,

-                                    follow_redirects=False)

-             self.assertEqual(result.status_code, 200)

-             self.assertEqual(

-                 json.loads(result.get_data(as_text=True)),

-                 {"status": "ADDED"})

-             self.assertEqual(

-                 hubs.models.Widget.query.filter(

-                     hubs.models.Hub.name == "ralph",

-                     hubs.models.Widget.plugin == "about",

-                 ).count(), 2)

- 

-     def test_hub_edit_widget_get_logged_in(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             result = self.app.get('/ralph/37/edit', follow_redirects=True)

-             self.assertEqual(result.status_code, 200)

-             expected_str = '/ralph/37/edit'

-             self.assertIn(expected_str, result.get_data(as_text=True))

- 

-     def test_hub_edit_widget_get_logged_out(self):

-         result = self.app.get('/ralph/31/edit', follow_redirects=False)

-         self.assertEqual(result.status_code, 302)

-         self.assertEqual(urlparse(result.location).path, "/login")

- 

-     def test_hub_edit_widget_post_empty_data_logged_in(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             data = {}

-             url = '/ralph/37/edit'

-             result = self.app.post(url, data=data, follow_redirects=False)

-             self.assertEqual(result.status_code, 302)

-             self.assertEqual(urlparse(result.location).path, '/ralph/edit')

- 

-     def test_hub_visit_counter_logged_in(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             url = '/visit/decause'

-             result = self.app.get(url)

-             self.assertEqual(

-                 json.loads(result.get_data(as_text=True)),

-                 {"count": 0})

- 

-             result = self.app.post(url)

-             self.assertEqual(

-                 json.loads(result.get_data(as_text=True)),

-                 {"count": 1})

- 

-             # accessing my hub shouldn't increment the count

-             url = 'visit/ralph'

-             result = self.app.post(url)

-             self.assertEqual(result.status_code, 403)

- 

-             # visiting no hub while logged should throw a 405

-             url = 'visit/'

-             result = self.app.post(url)

-             self.assertEqual(result.status_code, 405)

- 

-             # visiting a hub that doesn't exist should 404

-             url = 'visit/hub-does-not-exist'

-             result = self.app.post(url)

-             self.assertEqual(result.status_code, 404)

- 

-     @unittest.skip("Ajax calls don't seem to work in unittests ")

-     def test_hub_vist_counter_logged_in_2(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             url = '/visit/decause'

-             result = self.app.get(url)

-             self.assertEqual(result.get_data(as_text=True), '0')

- 

-             url = '/decause'

-             result = self.app.get(url, follow_redirects=True)

- 

-             url = '/visit/decause'

-             result = self.app.get(url)

-             self.assertEqual(result.get_data(as_text=True), '1')

- 

-     def test_hub_add_widget_valid_side(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             url = '/ralph/add/about?position=right'

-             result = self.app.get(url)

-             self.assertIn('Adding widget "about" to hub ralph',

-                           result.get_data(as_text=True))

- 

-     def test_hub_add_widget_invalid_side(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             url = '/ralph/add/about?position=invalid'

-             result = self.app.get(url)

-             self.assertEqual(result.status_code, 400)

- 

-     def test_hub_delete(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             url = '/ralph/37/delete'  # 37 is widget fedmsgstats for ralph

-             result = self.app.post(url)

-             self.assertEqual(result.status_code, 302)

-             self.assertIn('/ralph/edit', result.get_data(as_text=True))

- 

-     def test_source_name(self):

-         with tests.auth_set(app, None):

-             url = '/source/about'

-             result = self.app.get(url)

-             self.assertEqual(result.status_code, 302)

-             expected_str = 'https://pagure.io/fedora-hubs/' \

-                            'blob/develop/f/hubs/widgets/about/__init__.py'

-             self.assertIn(expected_str, result.get_data(as_text=True))

- 

-     def test_source_name_not_existent(self):

-         with tests.auth_set(app, None):

-             url = '/source/notexistent'

-             result = self.app.get(url)

-             self.assertEqual(result.status_code, 404)

- 

-     def test_hub_config_get(self):

-         expected = {

-             "hubconfig": {

-                 "summary": "Ralph",

-                 "left_width": 8,

-                 "avatar": (

-                     "https://seccdn.libravatar.org/avatar/9c9f7784935381befc30"

-                     "2fe3c814f9136e7a33953d0318761669b8643f4df55c"

-                     "?s=312&d=retro"

-                     ),

-                 "chat_channel": None,

-                 "chat_domain": None,

-                 "visibility": "public",

-             },

-             "general": {

-                 "chat_networks": app.config["CHAT_NETWORKS"],

-                 "roles": ["owner", "member"],

-                 "hub_visibility": hubs.models.HubConfig.VISIBILITY,

-             },

-             "users": {

-                 "member": [],

-                 "owner": [{

-                     "fullname": "Ralph",

-                     "locked": True,

-                     "role": "owner",

-                     "username": "ralph",

-                 }],

-             },

-         }

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             url = '/ralph/config'

-             result = self.app.get(url)

-         self.assertEqual(result.status_code, 200)

-         result_data = json.loads(result.get_data(as_text=True))

-         self.assertEqual(result_data["status"], "OK")

-         self.assertDictEqual(result_data["result"], expected)

- 

-     def test_hub_config_post(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             url = '/ralph/config?category=config'

-             result = self.app.post(url, data={

-                 "summary": "changed value",

-                 "chat_domain": "",

-             })

-         self.assertEqual(result.status_code, 200)

-         result_data = json.loads(result.get_data(as_text=True))

-         self.assertEqual(result_data["status"], "OK")

-         self.assertEqual(

-             result_data["result"]["hubconfig"]["summary"],

-             "changed value")

-         self.assertEqual(

-             result_data["result"]["hubconfig"]["chat_domain"],

-             app.config["CHAT_NETWORKS"][0]["domain"])

- 

-     def test_hub_config_post_unknown_post_data(self):

-         # Unknown POST data is silently ignored

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             url = '/ralph/config?category=config'

-             result = self.app.post(url, data={"non_existant": "dummy"})

-         self.assertEqual(result.status_code, 200)

-         result_data = json.loads(result.get_data(as_text=True))

-         self.assertEqual(result_data["status"], "ERROR")

-         self.assertEqual(result_data["message"], "Invalid value(s)")

-         self.assertIn("non_existant", result_data["fields"])

-         self.assertEqual(

-             result_data["fields"]["non_existant"],

-             "Unexpected parameter."

-             )

- 

-     def test_hub_config_post_invalid_chat_domain(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             url = '/ralph/config?category=config'

-             result = self.app.post(url, data={"chat_domain": "dummy"})

-         self.assertEqual(result.status_code, 200)

-         result_data = json.loads(result.get_data(as_text=True))

-         self.assertEqual(result_data["status"], "ERROR")

-         self.assertEqual(result_data["message"], "Invalid value(s)")

-         self.assertIn("chat_domain", result_data["fields"])

-         self.assertEqual(

-             result_data["fields"]["chat_domain"],

-             "Unsupported chat domain."

-             )

- 

-     def test_hub_config_get_unauthorized(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             url = '/decause/config'

-             result = self.app.get(url)

-         self.assertEqual(result.status_code, 403)

- 

-     def test_hub_config_post_unauthorized(self):

-         user = tests.FakeAuthorization('ralph')

-         with tests.auth_set(app, user):

-             url = '/decause/config?category=config'

-             result = self.app.post(url, data={"summary": "Defaced!"})

-         self.assertEqual(result.status_code, 403)

- 

-     def test_hub_config_suggest_users_no_filter(self):

-         user = tests.FakeAuthorization('ralph')

-         expected = [

-             u.username for u in

-             hubs.models.User.query.order_by(

-                 hubs.models.User.username

-             ).all()]

-         # Check without filter

-         with tests.auth_set(app, user):

-             url = '/ralph/config/suggest-users'

-             result = self.app.get(url)

-         self.assertEqual(result.status_code, 200)

-         result_data = json.loads(result.get_data(as_text=True))

-         self.assertEqual(result_data["status"], "OK")

-         self.assertListEqual(result_data["results"], expected)

- 

-     def test_hub_config_suggest_users_filter_owners(self):

-         # Filters on owners

-         user = tests.FakeAuthorization('ralph')

-         expected = [

-             u.username for u in

-             hubs.models.User.query.order_by(

-                 hubs.models.User.username

-             ).filter(

-                 hubs.models.User.username != "ralph"

-             ).all()]

-         with tests.auth_set(app, user):

-             url = '/ralph/config/suggest-users?exclude-role=owner'

-             result = self.app.get(url)

-         self.assertEqual(result.status_code, 200)

-         result_data = json.loads(result.get_data(as_text=True))

-         self.assertEqual(result_data["status"], "OK")

-         self.assertListEqual(result_data["results"], expected)

- 

-     def test_hub_config_suggest_users_filter_members(self):

-         # Filters on members

-         user = tests.FakeAuthorization('ralph')

-         hub = hubs.models.Hub.get('ralph')

-         decause = hubs.models.User.query.get("decause")

-         devyani7 = hubs.models.User.query.get("devyani7")

-         hub.subscribe(decause, "member")

-         hub.subscribe(devyani7, "member")

-         expected = [

-             u.username for u in

-             hubs.models.User.query.order_by(

-                 hubs.models.User.username

-             ).filter(

-                 hubs.models.User.username != "decause",

-                 hubs.models.User.username != "devyani7"

-             ).all()]

-         with tests.auth_set(app, user):

-             url = '/ralph/config/suggest-users?exclude-role=member'

-             result = self.app.get(url)

-         self.assertEqual(result.status_code, 200)

-         result_data = json.loads(result.get_data(as_text=True))

-         self.assertEqual(result_data["status"], "OK")

-         self.assertListEqual(result_data["results"], expected)

@@ -1,14 +1,10 @@ 

  from __future__ import unicode_literals

  

- import fedmsg.config

- 

  import hubs

  import hubs.models

  import hubs.tests

  from hubs.authz import AccessLevel

  

- fedmsg_config = fedmsg.config.load_config()

- 

  

  class ModelTest(hubs.tests.APPTest):

      def test_delete_user(self):

file modified
+23 -19
@@ -1,21 +1,30 @@ 

  from __future__ import unicode_literals

  

  import hubs.models

+ from hubs.app import app

  from hubs.tests import APPTest, FakeAuthorization, auth_set

- from hubs.views.utils import get_visible_widgets

+ from hubs.utils.views import get_visible_widgets

  

  

  class ViewUtilsTest(APPTest):

  

+     def setUp(self):

+         super(ViewUtilsTest, self).setUp()

+         self.app_context = app.app_context()

+         self.app_context.__enter__()

+ 

+     def tearDown(self):

+         self.app_context.__exit__(None, None, None)

+         super(ViewUtilsTest, self).tearDown()

+ 

      def test_removed_widget(self):

          hub = hubs.models.Hub.get("ralph")

          widget = hubs.models.Widget(

              hub=hub, plugin="does-not-exist",

              left=True, index=-1, _config="{}")

          self.session.add(widget)

-         with auth_set(self.app.application, FakeAuthorization('ralph')):

-             with self.app.application.app_context():

-                 widgets = get_visible_widgets(hub)

+         with auth_set(app, FakeAuthorization('ralph')):

+             widgets = get_visible_widgets(hub)

          self.assertNotIn(

              "does-not-exist", [w.plugin for w in widgets["left"]])

          widget.left = False
@@ -24,9 +33,8 @@ 

  

      def test_get_visible_widgets(self):

          hub = hubs.models.Hub.get('ralph')

-         with auth_set(self.app.application, None):

-             with self.app.application.app_context():

-                 widgets = get_visible_widgets(hub)

+         with auth_set(app, None):

+             widgets = get_visible_widgets(hub)

          self.assertListEqual(

              [w.plugin for w in widgets["left"]],

              ["feed"])
@@ -48,15 +56,13 @@ 

          meetings.visibility = "restricted"

          # Restricted widgets in preview hubs aren't displayed to

          # anonymous users.

-         with auth_set(self.app.application, None):

-             with self.app.application.app_context():

-                 widgets = get_visible_widgets(hub)

+         with auth_set(app, None):

+             widgets = get_visible_widgets(hub)

          self.assertNotIn(

              "meetings", [w.plugin for w in widgets["right"]])

          # But they are displayed to members.

-         with auth_set(self.app.application, FakeAuthorization('ralph')):

-             with self.app.application.app_context():

-                 widgets = get_visible_widgets(hub)

+         with auth_set(app, FakeAuthorization('ralph')):

+             widgets = get_visible_widgets(hub)

          self.assertIn(

              "meetings", [w.plugin for w in widgets["right"]])

  
@@ -69,14 +75,12 @@ 

          assert meetings.left is False

          # Widgets in private hubs aren't displayed to

          # anonymous users.

-         with auth_set(self.app.application, None):

-             with self.app.application.app_context():

-                 widgets = get_visible_widgets(hub)

+         with auth_set(app, None):

+             widgets = get_visible_widgets(hub)

          self.assertEqual(widgets["left"], [])

          self.assertEqual(widgets["right"], [])

          # But they are displayed to members.

-         with auth_set(self.app.application, FakeAuthorization('ralph')):

-             with self.app.application.app_context():

-                 widgets = get_visible_widgets(hub)

+         with auth_set(app, FakeAuthorization('ralph')):

+             widgets = get_visible_widgets(hub)

          self.assertNotEqual(len(widgets["left"]), 0)

          self.assertNotEqual(len(widgets["right"]), 0)

file modified
+14 -20
@@ -1,14 +1,14 @@ 

  from __future__ import unicode_literals

  

  import six

+ from mock import Mock

  

+ from hubs.app import app

+ from hubs.tests import APPTest

  from hubs.widgets.base import Widget

  from hubs.widgets.caching import CachedFunction

  from hubs.widgets.view import WidgetView

  

- from mock import Mock

- from hubs.tests import APPTest

- 

  

  class TestingWidget(Widget):

      name = "testing"
@@ -28,14 +28,14 @@ 

          super(WidgetTest, self).setUp()

          # Backup the URL map

          self._old_url_map = (

-             self.app.application.url_map._rules[:],

-             self.app.application.url_map._rules_by_endpoint.copy()

+             app.url_map._rules[:],

+             app.url_map._rules_by_endpoint.copy()

              )

  

      def tearDown(self):

          # Restore the URL map

-         self.app.application.url_map._rules = self._old_url_map[0]

-         self.app.application.url_map._rules_by_endpoint = self._old_url_map[1]

+         app.url_map._rules = self._old_url_map[0]

+         app.url_map._rules_by_endpoint = self._old_url_map[1]

          super(WidgetTest, self).tearDown()

  

      def test_validate(self):
@@ -126,23 +126,17 @@ 

              "root": TestView1(testing_widget),

              "test2": TestView2(testing_widget),

          }

-         testing_widget.register_routes(self.app.application)

+         testing_widget.register_routes(app)

          # TestView1

-         self.assertIn("testing_root",

-                       self.app.application.url_map._rules_by_endpoint)

-         self.assertIn("testing_root", self.app.application.view_functions)

-         rules = list(

-             self.app.application.url_map.iter_rules(endpoint="testing_root")

-             )

+         self.assertIn("testing_root", app.url_map._rules_by_endpoint)

+         self.assertIn("testing_root", app.view_functions)

+         rules = list(app.url_map.iter_rules(endpoint="testing_root"))

          self.assertEqual(len(rules), 2)

          self.assertEqual(rules[0].rule, "/<hub>/w/testing/<int:idx>/")

          self.assertEqual(rules[1].rule, "/<hub>/w/testing/<int:idx>/test-1/")

          # TestView2

-         self.assertIn("testing_test2",

-                       self.app.application.url_map._rules_by_endpoint)

-         self.assertIn("testing_test2", self.app.application.view_functions)

-         rules = list(

-             self.app.application.url_map.iter_rules(endpoint="testing_test2")

-             )

+         self.assertIn("testing_test2", app.url_map._rules_by_endpoint)

+         self.assertIn("testing_test2", app.view_functions)

+         rules = list(app.url_map.iter_rules(endpoint="testing_test2"))

          self.assertEqual(len(rules), 1)

          self.assertEqual(rules[0].rule, "/<hub>/w/testing/<int:idx>/test-2")

hubs/tests/vcr-request-data/hubs.tests.widgets.test_about.TestBadges.test_data_simple hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_about.TestBadges.test_data_simple
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_about.TestBadges.test_should_invalidate_good_match hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_about.TestBadges.test_should_invalidate_good_match
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_about.TestBadges.test_should_invalidate_wrong_topic hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_about.TestBadges.test_should_invalidate_wrong_topic
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_about.TestBadges.test_should_invalidate_wrong_user hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_about.TestBadges.test_should_invalidate_wrong_user
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_badges.TestBadges.test_data_simple hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_badges.TestBadges.test_data_simple
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_badges.TestBadges.test_should_invalidate_good_match hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_badges.TestBadges.test_should_invalidate_good_match
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_badges.TestBadges.test_should_invalidate_wrong_topic hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_badges.TestBadges.test_should_invalidate_wrong_topic
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_badges.TestBadges.test_should_invalidate_wrong_user hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_badges.TestBadges.test_should_invalidate_wrong_user
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_badges.TestBadges.test_view_authz hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_badges.TestBadges.test_view_authz
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_fedmsgstats.TestFedmsgStats.test_data_old hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_fedmsgstats.TestFedmsgStats.test_data_old
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_fedmsgstats.TestFedmsgStats.test_data_simple hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_fedmsgstats.TestFedmsgStats.test_data_simple
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_fedmsgstats.TestFedmsgStats.test_view_authz hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_fedmsgstats.TestFedmsgStats.test_view_authz
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_halp.HalpFunctionsTestCase.test_execute hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_halp.HalpFunctionsTestCase.test_execute
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_halp.HalpViewsTestCase.test_data hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_halp.HalpViewsTestCase.test_data
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_halp.HalpViewsTestCase.test_data_wrong_hub hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_halp.HalpViewsTestCase.test_data_wrong_hub
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_halp.HalpViewsTestCase.test_search_all hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_halp.HalpViewsTestCase.test_search_all
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_halp.HalpViewsTestCase.test_search_date hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_halp.HalpViewsTestCase.test_search_date
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_halp.HalpViewsTestCase.test_search_hub hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_halp.HalpViewsTestCase.test_search_hub
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_halp.HalpViewsTestCase.test_search_meetingname hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_halp.HalpViewsTestCase.test_search_meetingname
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_halp.HalpViewsTestCase.test_search_people hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_halp.HalpViewsTestCase.test_search_people
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_halp.HalpViewsTestCase.test_search_requesters hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_halp.HalpViewsTestCase.test_search_requesters
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_meetings.TestMeetings.test_data_simple hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_meetings.TestMeetings.test_data_simple
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_meetings.TestMeetings.test_render_simple hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_meetings.TestMeetings.test_render_simple
file renamed
file was moved with no change to the file
hubs/tests/vcr-request-data/hubs.tests.widgets.test_meetings.TestMeetings.test_view_authz hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_meetings.TestMeetings.test_view_authz
file renamed
file was moved with no change to the file
hubs/tests/views/__init__.py hubs/tests/test_api/__init__.py
file renamed
file was moved with no change to the file
hubs/tests/views/test_api.py hubs/tests/test_api/test_hub.py
file renamed
file was moved with no change to the file
@@ -0,0 +1,166 @@ 

+ from __future__ import unicode_literals

+ 

+ from flask import json

+ 

+ from hubs.app import app

+ from hubs.models import Hub, HubConfig, User

+ from hubs.tests import APPTest, FakeAuthorization, auth_set

+ 

+ 

+ class HubConfigTestCase(APPTest):

+ 

+     def test_hub_config_get(self):

+         expected = {

+             "hubconfig": {

+                 "summary": "Ralph",

+                 "left_width": 8,

+                 "avatar": (

+                     "https://seccdn.libravatar.org/avatar/9c9f7784935381befc30"

+                     "2fe3c814f9136e7a33953d0318761669b8643f4df55c"

+                     "?s=312&d=retro"

+                     ),

+                 "chat_channel": None,

+                 "chat_domain": None,

+                 "visibility": "public",

+             },

+             "general": {

+                 "chat_networks": app.config["CHAT_NETWORKS"],

+                 "roles": ["owner", "member"],

+                 "hub_visibility": HubConfig.VISIBILITY,

+             },

+             "users": {

+                 "member": [],

+                 "owner": [{

+                     "fullname": "Ralph",

+                     "locked": True,

+                     "role": "owner",

+                     "username": "ralph",

+                 }],

+             },

+         }

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             url = '/ralph/config'

+             result = self.app.get(url)

+         self.assertEqual(result.status_code, 200)

+         result_data = json.loads(result.get_data(as_text=True))

+         self.assertEqual(result_data["status"], "OK")

+         self.assertDictEqual(result_data["result"], expected)

+ 

+     def test_hub_config_post(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             url = '/ralph/config?category=config'

+             result = self.app.post(url, data={

+                 "summary": "changed value",

+                 "chat_domain": "",

+             })

+         self.assertEqual(result.status_code, 200)

+         result_data = json.loads(result.get_data(as_text=True))

+         self.assertEqual(result_data["status"], "OK")

+         self.assertEqual(

+             result_data["result"]["hubconfig"]["summary"],

+             "changed value")

+         self.assertEqual(

+             result_data["result"]["hubconfig"]["chat_domain"],

+             app.config["CHAT_NETWORKS"][0]["domain"])

+ 

+     def test_hub_config_post_unknown_post_data(self):

+         # Unknown POST data is silently ignored

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             url = '/ralph/config?category=config'

+             result = self.app.post(url, data={"non_existant": "dummy"})

+         self.assertEqual(result.status_code, 200)

+         result_data = json.loads(result.get_data(as_text=True))

+         self.assertEqual(result_data["status"], "ERROR")

+         self.assertEqual(result_data["message"], "Invalid value(s)")

+         self.assertIn("non_existant", result_data["fields"])

+         self.assertEqual(

+             result_data["fields"]["non_existant"],

+             "Unexpected parameter."

+             )

+ 

+     def test_hub_config_post_invalid_chat_domain(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             url = '/ralph/config?category=config'

+             result = self.app.post(url, data={"chat_domain": "dummy"})

+         self.assertEqual(result.status_code, 200)

+         result_data = json.loads(result.get_data(as_text=True))

+         self.assertEqual(result_data["status"], "ERROR")

+         self.assertEqual(result_data["message"], "Invalid value(s)")

+         self.assertIn("chat_domain", result_data["fields"])

+         self.assertEqual(

+             result_data["fields"]["chat_domain"],

+             "Unsupported chat domain."

+             )

+ 

+     def test_hub_config_get_unauthorized(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             url = '/decause/config'

+             result = self.app.get(url)

+         self.assertEqual(result.status_code, 403)

+ 

+     def test_hub_config_post_unauthorized(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             url = '/decause/config?category=config'

+             result = self.app.post(url, data={"summary": "Defaced!"})

+         self.assertEqual(result.status_code, 403)

+ 

+     def test_hub_config_suggest_users_no_filter(self):

+         user = FakeAuthorization('ralph')

+         expected = [

+             u.username for u in

+             User.query.order_by(User.username).all()

+             ]

+         # Check without filter

+         with auth_set(app, user):

+             url = '/ralph/config/suggest-users'

+             result = self.app.get(url)

+         self.assertEqual(result.status_code, 200)

+         result_data = json.loads(result.get_data(as_text=True))

+         self.assertEqual(result_data["status"], "OK")

+         self.assertListEqual(result_data["results"], expected)

+ 

+     def test_hub_config_suggest_users_filter_owners(self):

+         # Filters on owners

+         user = FakeAuthorization('ralph')

+         expected = [

+             u.username for u in

+             User.query.order_by(User.username).filter(

+                 User.username != "ralph").all()

+             ]

+         with auth_set(app, user):

+             url = '/ralph/config/suggest-users?exclude-role=owner'

+             result = self.app.get(url)

+         self.assertEqual(result.status_code, 200)

+         result_data = json.loads(result.get_data(as_text=True))

+         self.assertEqual(result_data["status"], "OK")

+         self.assertListEqual(result_data["results"], expected)

+ 

+     def test_hub_config_suggest_users_filter_members(self):

+         # Filters on members

+         user = FakeAuthorization('ralph')

+         hub = Hub.get('ralph')

+         decause = User.query.get("decause")

+         devyani7 = User.query.get("devyani7")

+         hub.subscribe(decause, "member")

+         hub.subscribe(devyani7, "member")

+         expected = [

+             u.username for u in

+             User.query.order_by(

+                 User.username

+             ).filter(

+                 User.username != "decause",

+                 User.username != "devyani7"

+             ).all()]

+         with auth_set(app, user):

+             url = '/ralph/config/suggest-users?exclude-role=member'

+             result = self.app.get(url)

+         self.assertEqual(result.status_code, 200)

+         result_data = json.loads(result.get_data(as_text=True))

+         self.assertEqual(result_data["status"], "OK")

+         self.assertListEqual(result_data["results"], expected)

@@ -0,0 +1,114 @@ 

+ from __future__ import unicode_literals

+ 

+ from six.moves.urllib.parse import urlparse

+ from werkzeug.datastructures import ImmutableMultiDict

+ 

+ from hubs.app import app

+ from hubs.tests import APPTest, FakeAuthorization, auth_set

+ 

+ 

+ class HubEditTestCase(APPTest):

+ 

+     def test_hub_edit_get_logged_out(self):

+         with auth_set(app, None):

+             result = self.app.get('/ralph/edit', follow_redirects=False)

+         self.assertEqual(result.status_code, 302)

+         self.assertEqual(urlparse(result.location).path, "/login")

+ 

+     def test_hub_edit_get_logged_in_not_owner(self):

+         user = FakeAuthorization('not_ralph')

+         with auth_set(app, user):

+             result = self.app.get('/ralph/edit', follow_redirects=True)

+             self.assertEqual(result.status_code, 403)

+ 

+     def test_hub_edit_get_logged_in_owner(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             result = self.app.get('/ralph/edit', follow_redirects=True)

+             self.assertEqual(result.status_code, 200)

+ 

+     def test_hub_edit_post_logged_out(self):

+         with auth_set(app, None):

+             result = self.app.post('/ralph/edit', follow_redirects=False)

+         self.assertEqual(result.status_code, 302)

+         self.assertEqual(urlparse(result.location).path, "/login")

+ 

+     def test_hub_edit_post_logged_in_not_owner(self):

+         user = FakeAuthorization('not_ralph')

+         with auth_set(app, user):

+             result = self.app.post('/ralph/edit', follow_redirects=True)

+             self.assertEqual(result.status_code, 403)

+ 

+     def test_hub_edit_post_logged_in_owner_empty_data(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             result = self.app.post('/ralph/edit', data={},

+                                    follow_redirects=True)

+             self.assertEqual(result.status_code, 200)

+             self.assertNotIn(

+                 'Not logged in.  Click to <a href="/login">login</a>',

+                 result.get_data(as_text=True))

+             self.assertIn(

+                 '<a href="#" class="dropdown-item">Full Name: '

+                 'fullname: ralph</a>', result.get_data(as_text=True))

+ 

+     def test_hub_edit_post_logged_in_owner_valid_data(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             data = ImmutableMultiDict(

+                 [('right_indexes[]', u'0'), ('right_indexes[]', u'1'),

+                  ('right_indexes[]', u'2'), ('right_indexes[]', u'3'),

+                  ('right_indexes[]', u'4'), ('right_indexes[]', u'5'),

+                  ('right_indexes[]', u'6'), ('right_indexes[]', u'7'),

+                  ('right_indexes[]', u'8'), ('right_widgets[]', u'32'),

+                  ('right_widgets[]', u'33'), ('right_widgets[]', u'34'),

+                  ('right_widgets[]', u'35'), ('right_widgets[]', u'36'),

+                  ('right_widgets[]', u'37'), ('right_widgets[]', u'38'),

+                  ('right_widgets[]', u'39'), ('right_widgets[]', u'40'),

+                  ('js', u'true'), ('left_indexes[]', u'0'),

+                  ('left_indexes[]', u'1'), ('left_widgets[]', u'31'),

+                  ('left_widgets[]', u'32')])

+             result = self.app.post('/ralph/edit', data=data,

+                                    follow_redirects=True)

+             self.assertEqual(result.status_code, 200)

+             self.assertEqual(result.get_data(as_text=True), 'ok')

+ 

+     def test_hub_edit_post_logged_in_owner_invalid_data_1(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             # some indexes and widgets are not integers

+             data = ImmutableMultiDict(

+                 [('right_indexes[]', u'0a'), ('right_indexes[]', u'1'),

+                  ('right_indexes[]', u'2'), ('right_indexes[]', u'3'),

+                  ('right_indexes[]', u'4'), ('right_indexes[]', u'5'),

+                  ('right_indexes[]', u'6'), ('right_indexes[]', u'7'),

+                  ('right_indexes[]', u'8'), ('right_widgets[]', u'32'),

+                  ('right_widgets[]', u'33a'), ('right_widgets[]', u'34'),

+                  ('right_widgets[]', u'35'), ('right_widgets[]', u'36'),

+                  ('right_widgets[]', u'37'), ('right_widgets[]', u'38'),

+                  ('right_widgets[]', u'39'), ('right_widgets[]', u'40'),

+                  ('js', u'true'), ('left_indexes[]', u'0a'),

+                  ('left_indexes[]', u'1'), ('left_widgets[]', u'31a'),

+                  ('left_widgets[]', u'32')])

+             result = self.app.post('/ralph/edit', data=data,

+                                    follow_redirects=True)

+             self.assertEqual(result.status_code, 400)

+ 

+     def test_hub_edit_post_logged_in_owner_invalid_data_2(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             # indexes len don't match widgets len

+             data = ImmutableMultiDict(

+                 [('right_indexes[]', u'1'), ('right_indexes[]', u'2'),

+                  ('right_indexes[]', u'3'), ('right_indexes[]', u'4'),

+                  ('right_indexes[]', u'5'), ('right_indexes[]', u'6'),

+                  ('right_indexes[]', u'7'), ('right_indexes[]', u'8'),

+                  ('right_widgets[]', u'32'), ('right_widgets[]', u'34'),

+                  ('right_widgets[]', u'35'), ('right_widgets[]', u'36'),

+                  ('right_widgets[]', u'37'), ('right_widgets[]', u'38'),

+                  ('right_widgets[]', u'39'), ('right_widgets[]', u'40'),

+                  ('js', u'true'), ('left_indexes[]', u'0'),

+                  ('left_indexes[]', u'1'), ('left_widgets[]', u'32')])

+             result = self.app.post('/ralph/edit', data=data,

+                                    follow_redirects=True)

+             self.assertEqual(result.status_code, 400)

@@ -0,0 +1,91 @@ 

+ from __future__ import unicode_literals

+ 

+ from flask import json

+ 

+ from hubs.app import app

+ from hubs.models import Hub

+ from hubs.tests import APPTest, FakeAuthorization, auth_set

+ 

+ 

+ class HubViewTestCase(APPTest):

+ 

+     def test_hub_logged_out(self):

+         with auth_set(app, None):  # check_auth doesn't load in unittest

+             result = self.app.get('/ralph', follow_redirects=True)

+             self.assertEqual(result.status_code, 200)

+             match_expected = r'<h5[^>]*>Ralph</h5>'

+             self.assertRegexpMatches(

+                 result.get_data(as_text=True), match_expected)

+             str_expected = 'Not logged in.'

+             self.assertIn(str_expected, result.get_data(as_text=True))

+ 

+     def test_hub_logged_in(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             result = self.app.get('/ralph', follow_redirects=True)

+             self.assertEqual(result.status_code, 200)

+             self.assertNotIn(

+                 'Not logged in.  Click to <a href="/login">login</a>',

+                 result.get_data(as_text=True))

+ 

+     def test_hub_preview(self):

+         hub = Hub.by_name('ralph')

+         hub.config.visibility = "preview"

+         # Preview hubs are accessible to anonymous users (but some

+         # widgets may be restricted).

+         with auth_set(app, None):

+             result = self.app.get('/ralph', follow_redirects=True)

+             self.assertEqual(result.status_code, 200)

+ 

+     def test_hub_private(self):

+         hub = Hub.by_name('ralph')

+         hub.config.visibility = "private"

+         self.session.commit()

+         # Private hubs are not accessible to anonymous users.

+         with auth_set(app, None):

+             result = self.app.get('/ralph', follow_redirects=True)

+             self.assertEqual(result.status_code, 403)

+         # But they are accessible to members.

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             result = self.app.get('/ralph', follow_redirects=True)

+             self.assertEqual(result.status_code, 200)

+ 

+     def test_hub_json(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             result = self.app.get('/ralph/json', follow_redirects=True)

+         # assert the status code of the response

+         self.assertEqual(result.status_code, 200)

+         data = {

+             "config": {

+                 "avatar": "https://seccdn.libravatar.org/avatar/"

+                           "9c9f7784935381befc302fe3c814f9136e7a339"

+                           "53d0318761669b8643f4df55c?s=312&d=retro",

+                 'chat_channel': None,

+                 'chat_domain': None,

+                 "left_width": 8,

+                 "summary": "Ralph",

+                 "visibility": "public",

+             },

+             "members": ["ralph"],

+             "name": "ralph",

+             "owners": ["ralph"],

+             "subscribers": [],

+             "widgets": [37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 61],

+         }

+         self.assertDictEqual(data, json.loads(result.get_data(as_text=True)))

+ 

+     def test_hub_private_json(self):

+         hub = Hub.by_name('ralph')

+         hub.config.visibility = "private"

+         self.session.commit()

+         # Private hubs are not accessible to anonymous users.

+         with auth_set(app, None):

+             result = self.app.get('/ralph/json', follow_redirects=True)

+             self.assertEqual(result.status_code, 403)

+         # But they are accessible to members.

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             result = self.app.get('/ralph/json', follow_redirects=True)

+             self.assertEqual(result.status_code, 200)

@@ -0,0 +1,138 @@ 

+ from __future__ import unicode_literals

+ 

+ from flask import json

+ from six.moves.urllib.parse import urlparse

+ 

+ from hubs.app import app

+ from hubs.models import Hub, Widget

+ from hubs.tests import APPTest, FakeAuthorization, auth_set

+ 

+ 

+ class HubWidgetsTestCase(APPTest):

+ 

+     def test_hub_add_widget_get_no_args(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             result = self.app.get('/ralph/add', follow_redirects=False)

+         self.assertEqual(result.status_code, 400)

+         expected_str = 'Invalid position provided'

+         self.assertIn(expected_str, result.get_data(as_text=True))

+ 

+     def test_hub_add_widget_get_with_args(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             result = self.app.get('/ralph/add?position=right',

+                                   follow_redirects=True)

+         self.assertEqual(result.status_code, 200)

+         page_html = result.get_data(as_text=True)

+         self.assertIn('Adding a widget to hub: ralph', page_html)

+         self.assertIn('<form method="post" action="/ralph/add">', page_html)

+         self.assertIn('<input type="hidden" name="position" value="right" />',

+                       page_html)

+ 

+     def test_hub_add_widget_post_no_widget_name(self):

+         data = {"position": "left"}

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             result = self.app.post(

+                 '/ralph/add', data=data, follow_redirects=False)

+         self.assertEqual(result.status_code, 400)

+         expected_str = 'Invalid request sent'

+         self.assertIn(expected_str, result.get_data(as_text=True))

+ 

+     def test_hub_add_widget_post_invalid_widget_name(self):

+         data = {'widget': 'invalid_widget_name',

+                 'position': 'right'}

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             result = self.app.post(

+                 '/ralph/add', data=data, follow_redirects=False)

+         self.assertEqual(result.status_code, 404)

+         expected_str = 'Unknown widget called'

+         self.assertIn(expected_str, result.get_data(as_text=True))

+ 

+     def test_hub_add_widget_post_valid_widget_name_no_args(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             data = {

+                 'widget': 'memberships',

+                 'position': 'right',

+                 }

+             result = self.app.post('/ralph/add', data=data)

+             self.assertEqual(result.status_code, 200)

+             self.assertEqual(

+                 json.loads(result.get_data(as_text=True)),

+                 {"status": "ADDED"})

+             result = self.app.get('/ralph/edit')

+             self.assertEqual(result.status_code, 200)

+             page_html = result.get_data(as_text=True)

+             self.assertIn('data-url="/ralph/w/memberships/', page_html)

+ 

+     def test_hub_add_widget_post_valid_widget_name_with_args(self):

+         self.assertEqual(

+             Widget.query.filter(

+                 Hub.name == "ralph",

+                 Widget.plugin == "about",

+             ).count(), 1)

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             data = {

+                 'text': 'text of widget',

+                 'position': 'right',

+                 }

+             result = self.app.post('/ralph/add/about', data=data,

+                                    follow_redirects=False)

+             self.assertEqual(result.status_code, 200)

+             self.assertEqual(

+                 json.loads(result.get_data(as_text=True)),

+                 {"status": "ADDED"})

+             self.assertEqual(

+                 Widget.query.filter(

+                     Hub.name == "ralph",

+                     Widget.plugin == "about",

+                 ).count(), 2)

+ 

+     def test_hub_edit_widget_get_logged_in(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             result = self.app.get('/ralph/37/edit', follow_redirects=True)

+             self.assertEqual(result.status_code, 200)

+             expected_str = '/ralph/37/edit'

+             self.assertIn(expected_str, result.get_data(as_text=True))

+ 

+     def test_hub_edit_widget_get_logged_out(self):

+         result = self.app.get('/ralph/31/edit', follow_redirects=False)

+         self.assertEqual(result.status_code, 302)

+         self.assertEqual(urlparse(result.location).path, "/login")

+ 

+     def test_hub_edit_widget_post_empty_data_logged_in(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             data = {}

+             url = '/ralph/37/edit'

+             result = self.app.post(url, data=data, follow_redirects=False)

+             self.assertEqual(result.status_code, 302)

+             self.assertEqual(urlparse(result.location).path, '/ralph/edit')

+ 

+     def test_hub_add_widget_valid_side(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             url = '/ralph/add/about?position=right'

+             result = self.app.get(url)

+             self.assertIn('Adding widget "about" to hub ralph',

+                           result.get_data(as_text=True))

+ 

+     def test_hub_add_widget_invalid_side(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             url = '/ralph/add/about?position=invalid'

+             result = self.app.get(url)

+             self.assertEqual(result.status_code, 400)

+ 

+     def test_hub_delete(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             url = '/ralph/37/delete'  # 37 is widget fedmsgstats for ralph

+             result = self.app.post(url)

+             self.assertEqual(result.status_code, 302)

+             self.assertIn('/ralph/edit', result.get_data(as_text=True))

@@ -0,0 +1,50 @@ 

+ from __future__ import unicode_literals

+ 

+ from six.moves.urllib.parse import urlparse

+ 

+ from hubs.app import app

+ from hubs.tests import APPTest, FakeAuthorization, auth_set

+ 

+ 

+ class RootTestCase(APPTest):

+ 

+     def test_index_logged_out(self):

+         result = self.app.get('/', follow_redirects=False)

+         self.assertEqual(result.status_code, 302)

+         self.assertEqual(urlparse(result.location).path, "/login")

+ 

+     def test_index_logged_in(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             result = self.app.get('/', follow_redirects=True)

+             # its trying to redirect to login id.fedoraproject.org/openid

+             # assert the status code of the response

+             self.assertEqual(result.status_code, 200)

+             self.assertNotIn(

+                 'Not logged in.  Click to <a href="/login">login</a>',

+                 result.get_data(as_text=True))

+ 

+     def test_login_already_loggedin(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             result = self.app.get('/login', follow_redirects=False)

+             self.assertEqual(result.status_code, 302)

+             self.assertEqual(

+                 urlparse(result.location).path,

+                 "/openidc/Authorization")

+ 

+     def test_groups_logged_out(self):

+         result = self.app.get('/groups', follow_redirects=False)

+         # assert the status code of the response

+         self.assertEqual(result.status_code, 302)

+         # this will redirect to fedora.login

+         self.assertEqual(urlparse(result.location).path, "/login")

+ 

+     def test_groups_logged_in(self):

+         user = FakeAuthorization('ralph')

+         with auth_set(app, user):

+             result = self.app.get('/groups', follow_redirects=True)

+             # assert the status code of the response

+             self.assertEqual(result.status_code, 200)

+             self.assertIn("ZOMG -  is the Hub Of The Month!",

+                           result.get_data(as_text=True))

hubs/tests/views/test_user.py hubs/tests/test_api/test_notifications.py
file renamed
+48
@@ -1,6 +1,7 @@ 

  from __future__ import unicode_literals

  

  import json

+ import unittest

  

  import hubs.tests

  import hubs.models
@@ -123,3 +124,50 @@ 

                  '/{}/notifications/{}/'.format(self.user.username, idx)

              )

          self.assertEqual(resp.status_code, 404)

+ 

+ 

+ class TestHubVisits(hubs.tests.APPTest):

+ 

+     def test_hub_visit_counter_logged_in(self):

+         user = hubs.tests.FakeAuthorization('ralph')

+         with hubs.tests.auth_set(app, user):

+             url = '/visit/decause'

+             result = self.app.get(url)

+             self.assertEqual(

+                 json.loads(result.get_data(as_text=True)),

+                 {"count": 0})

+ 

+             result = self.app.post(url)

+             self.assertEqual(

+                 json.loads(result.get_data(as_text=True)),

+                 {"count": 1})

+ 

+             # accessing my hub shouldn't increment the count

+             url = 'visit/ralph'

+             result = self.app.post(url)

+             self.assertEqual(result.status_code, 403)

+ 

+             # visiting no hub while logged should throw a 405

+             url = 'visit/'

+             result = self.app.post(url)

+             self.assertEqual(result.status_code, 405)

+ 

+             # visiting a hub that doesn't exist should 404

+             url = 'visit/hub-does-not-exist'

+             result = self.app.post(url)

+             self.assertEqual(result.status_code, 404)

+ 

+     @unittest.skip("Ajax calls don't seem to work in unittests ")

+     def test_hub_vist_counter_logged_in_2(self):

+         user = hubs.tests.FakeAuthorization('ralph')

+         with hubs.tests.auth_set(app, user):

+             url = '/visit/decause'

+             result = self.app.get(url)

+             self.assertEqual(result.get_data(as_text=True), '0')

+ 

+             url = '/decause'

+             result = self.app.get(url, follow_redirects=True)

+ 

+             url = '/visit/decause'

+             result = self.app.get(url)

+             self.assertEqual(result.get_data(as_text=True), '1')

@@ -0,0 +1,23 @@ 

+ from __future__ import unicode_literals

+ 

+ 

+ from hubs.app import app

+ from hubs.tests import APPTest, auth_set

+ 

+ 

+ class WidgetTestCase(APPTest):

+ 

+     def test_source_name(self):

+         with auth_set(app, None):

+             url = '/source/about'

+             result = self.app.get(url)

+             self.assertEqual(result.status_code, 302)

+             expected_str = 'https://pagure.io/fedora-hubs/' \

+                            'blob/develop/f/hubs/widgets/about/__init__.py'

+             self.assertIn(expected_str, result.get_data(as_text=True))

+ 

+     def test_source_name_not_existent(self):

+         with auth_set(app, None):

+             url = '/source/notexistent'

+             result = self.app.get(url)

+             self.assertEqual(result.status_code, 404)

hubs/tests/widgets/__init__.py hubs/tests/test_widgets/__init__.py
file renamed
+2 -2
@@ -4,7 +4,7 @@ 

  import unittest

  

  import hubs.models

- from hubs.tests import APPTest, FakeAuthorization

+ from hubs.tests import APPTest, FakeAuthorization, widget_instance

  

  

  class WidgetTest(APPTest):
@@ -28,7 +28,7 @@ 

          if not self.plugin:

              raise unittest.SkipTest

          hub = hubs.models.Hub.query.get("ralph")

-         widget = self.widget_instance(hub.name, self.plugin)

+         widget = widget_instance(hub.name, self.plugin)

          url = '/%s/w/%s/%i/' % (hub.name, self.plugin, widget.idx)

          # Public

          self.check_url(url, None, 200)

hubs/tests/widgets/test_about.py hubs/tests/test_widgets/test_about.py
file renamed
+2 -2
@@ -2,7 +2,7 @@ 

  

  import json

  

- from hubs.tests import FakeAuthorization

+ from hubs.tests import FakeAuthorization, widget_instance

  from . import WidgetTest

  

  
@@ -10,7 +10,7 @@ 

      plugin = 'about'  # The name in hubs.widgets.registry

  

      def test_data_simple(self):

-         widget = self.widget_instance('ralph', self.plugin)

+         widget = widget_instance('ralph', self.plugin)

          user = FakeAuthorization('ralph')

          response = self.check_url('/ralph/%i/json' % widget.idx, user)

          data = json.loads(response.get_data(as_text=True))

hubs/tests/widgets/test_badges.py hubs/tests/test_widgets/test_badges.py
file renamed
+14 -10
@@ -3,7 +3,7 @@ 

  import json

  

  import hubs.widgets

- from hubs.tests import FakeAuthorization

+ from hubs.tests import FakeAuthorization, widget_instance

  from . import WidgetTest

  

  
@@ -11,7 +11,7 @@ 

      plugin = 'badges'  # The name in hubs.widgets.registry

  

      def test_data_simple(self):

-         widget = self.widget_instance('ralph', self.plugin)

+         widget = widget_instance('ralph', self.plugin)

          user = FakeAuthorization('ralph')

          response = self.check_url('/ralph/%i/json' % widget.idx, user)

          data = json.loads(response.get_data(as_text=True))
@@ -19,8 +19,9 @@ 

          self.assertIn('assertions', data['data'].keys())

  

      def test_should_invalidate_wrong_topic(self):

-         widget = self.widget_instance('ralph', self.plugin)

-         # msg = self.get_fedmsg('2016-ebb84660-59e9-4e68-af8f-4e6f49348b88')

+         widget = widget_instance('ralph', self.plugin)

+         # from hubs.tests import get_fedmsg

+         # msg = get_fedmsg('2016-ebb84660-59e9-4e68-af8f-4e6f49348b88')

          msg = {'topic': 'hubs.widget.update.WRONG.TOPIC'}

          module = hubs.widgets.registry[widget.plugin]

          func = module.get_cached_functions()['GetBadges']
@@ -28,8 +29,9 @@ 

          self.assertFalse(result)

  

      def test_should_invalidate_wrong_user(self):

-         widget = self.widget_instance('ralph', self.plugin)

-         # msg = self.get_fedmsg('2016-e371c7f6-bc8e-4632-8e33-b9102dc30b5f')

+         widget = widget_instance('ralph', self.plugin)

+         # from hubs.tests import get_fedmsg

+         # msg = get_fedmsg('2016-e371c7f6-bc8e-4632-8e33-b9102dc30b5f')

          msg = {'topic': 'fedbadges.badge.award',

                 'msg': {'user': {'username': 'not_ralph'}}}

          module = hubs.widgets.registry[widget.plugin]
@@ -38,8 +40,9 @@ 

          self.assertFalse(result)

  

      def test_should_invalidate_good_match_fedbadges(self):

-         widget = self.widget_instance('ralph', self.plugin)

-         # msg = self.get_fedmsg('2016-1fbb1135-681b-4d3b-9a40-d0f6ebd313f4')

+         widget = widget_instance('ralph', self.plugin)

+         # from hubs.tests import get_fedmsg

+         # msg = get_fedmsg('2016-1fbb1135-681b-4d3b-9a40-d0f6ebd313f4')

          msg = {'topic': 'fedbadges.badge.award',

                 'msg': {'user': {'username': 'ralph'}}}

          module = hubs.widgets.registry[widget.plugin]
@@ -48,8 +51,9 @@ 

          self.assertTrue(result)

  

      def test_should_invalidate_good_match_hubswidget(self):

-         widget = self.widget_instance('ralph', self.plugin)

-         # msg = self.get_fedmsg('2016-1fbb1135-681b-4d3b-9a40-d0f6ebd313f4')

+         widget = widget_instance('ralph', self.plugin)

+         # from hubs.tests import get_fedmsg

+         # msg = get_fedmsg('2016-1fbb1135-681b-4d3b-9a40-d0f6ebd313f4')

          msg = {'topic': 'hubs.widget.update',

                 'msg': {'widget': {'id': widget.idx + 1}}}

          module = hubs.widgets.registry[widget.plugin]

hubs/tests/widgets/test_contact.py hubs/tests/test_widgets/test_contact.py
file renamed
+6 -11
@@ -2,7 +2,6 @@ 

  

  import json

  

- import flask

  import mock

  

  import hubs
@@ -12,11 +11,12 @@ 

  

  

  def mocked_requests_get(*args, **kwargs):

-     class MockResponse:  # flake8: noqa

+     class MockResponse:

          def __init__(self, json_data, status_code):

              self.json_data = json_data

              self.status_code = status_code

              self.text = str(json_data)

+ 

          def json(self):

              return self.json_data

  
@@ -33,6 +33,7 @@ 

  

      return MockResponse({}, 404)

  

+ 

  def mocked_requests_post(*args, **kwargs):

      class MockResponse:

          def __init__(self, json_data, status_code):
@@ -42,6 +43,7 @@ 

  

          def json(self):

              return self.json_data

+ 

      if '/decause' in kwargs['url']:

          data = {

              "current": 1,
@@ -72,16 +74,15 @@ 

          self.widget_idx = widget.idx

  

      def test_data_simple(self):

-         widget = self.widget_instance('ralph', self.plugin)

          user = FakeAuthorization('ralph')

-         response = self.check_url('/ralph/%i/json' % widget.idx, user)

+         response = self.check_url('/ralph/%i/json' % self.widget_idx, user)

          data = json.loads(response.get_data(as_text=True))

          self.assertDictEqual(data['data'], {

              'account_age': 'Oct 2010',

              'email': 'ralph@fedoraproject.org',

              'ircnick': 'ralph',

              'karma_url': '/ralph/w/contact/%i/plus-plus/ralph/status'

-                          % widget.idx,

+                          % self.widget_idx,

              'location': 'United States',

              'timezone': 'UTC',

              'usergroup': True,
@@ -92,7 +93,6 @@ 

  

      @mock.patch('requests.get', side_effect=mocked_requests_get)

      def test_plus_plus_get_valid(self, mock_get):

-         widget = self.widget_instance("ralph", self.plugin)

          url = "/ralph/w/contact/%d/plus-plus/%s/status" % (

              self.widget_idx, "decause")

          result = self.app.get(url)
@@ -111,7 +111,6 @@ 

  

      @mock.patch('requests.post', side_effect=mocked_requests_post)

      def test_plus_plus_post_increment_valid(self, mock_post):

-         widget = self.widget_instance("ralph", self.plugin)

          url = "/ralph/w/contact/%d/plus-plus/%s/update" % (

              self.widget_idx, "decause")

          user = FakeAuthorization('ralph')
@@ -132,7 +131,6 @@ 

  

      @mock.patch('requests.post', side_effect=mocked_requests_post)

      def test_plus_plus_post_increment_myself_error(self, mock_post):

-         widget = self.widget_instance("ralph", self.plugin)

          url = "/ralph/w/contact/%d/plus-plus/%s/update" % (

              self.widget_idx, "ralph")

          user = FakeAuthorization('ralph')
@@ -145,7 +143,6 @@ 

  

      @mock.patch('requests.post', side_effect=mocked_requests_post)

      def test_plus_plus_post_increment_user_does_not_exist(self, mock_post):

-         widget = self.widget_instance("ralph", self.plugin)

          url = "/ralph/w/contact/%d/plus-plus/%s/update" % (

              self.widget_idx, "doesnotexist")

          user = FakeAuthorization('ralph')
@@ -158,7 +155,6 @@ 

  

      @mock.patch('requests.post', side_effect=mocked_requests_post)

      def test_plus_plus_post_increment_no_data_error(self, mock_post):

-         widget = self.widget_instance("ralph", self.plugin)

          url = "/ralph/w/contact/%d/plus-plus/%s/update" % (

              self.widget_idx, "decause")

          user = FakeAuthorization('ralph')
@@ -170,7 +166,6 @@ 

              self.assertEqual(result.get_data(as_text=True), exp_str)

  

      def test_plus_plus_receiver_does_not_exist(self):

-         widget = self.widget_instance("ralph", self.plugin)

          url = "/ralph/w/contact/%d/plus-plus/%s/status" % (

              self.widget_idx, "doesnotexist")

          result = self.app.get(url)

hubs/tests/widgets/test_fedmsgstats.py hubs/tests/test_widgets/test_fedmsgstats.py
file renamed
+2 -2
@@ -2,7 +2,7 @@ 

  

  import json

  

- from hubs.tests import FakeAuthorization

+ from hubs.tests import FakeAuthorization, widget_instance

  from . import WidgetTest

  

  
@@ -10,7 +10,7 @@ 

      plugin = 'fedmsgstats'  # The name in hubs.widgets.registry

  

      def test_data_simple(self):

-         widget = self.widget_instance('ralph', self.plugin)

+         widget = widget_instance('ralph', self.plugin)

          user = FakeAuthorization('ralph')

          response = self.check_url('/ralph/%i/json' % widget.idx, user)

          data = json.loads(response.get_data(as_text=True))

hubs/tests/widgets/test_halp.py hubs/tests/test_widgets/test_halp.py
file renamed
+12 -11
@@ -2,8 +2,9 @@ 

  

  import json

  

+ from hubs.app import app

  from hubs.models import Hub, User

- from hubs.tests import FakeAuthorization

+ from hubs.tests import FakeAuthorization, widget_instance

  from hubs.widgets import registry

  from . import WidgetTest

  
@@ -83,7 +84,7 @@ 

  

      def setUp(self):

          super(HalpViewsTestCase, self).setUp()

-         self.widget = self.widget_instance('ralph', self.plugin)

+         self.widget = widget_instance('ralph', self.plugin)

          config = self.widget.config

          config["hubs"] = ["fedora-devel"]

          config["per_page"] = 3
@@ -329,7 +330,7 @@ 

          super(HalpFunctionsTestCase, self).setUp()

          module = registry[self.plugin]

          func_class = module.get_cached_functions()['GetRequests']

-         self.widget = self.widget_instance('ralph', self.plugin)

+         self.widget = widget_instance('ralph', self.plugin)

          self.func = func_class(self.widget)

          # The tested widget watches the infra hub.

          config = self.widget.config
@@ -341,7 +342,7 @@ 

          self.session.commit()

  

      def test_execute(self):

-         with self.app.application.test_request_context('/'):

+         with app.test_request_context('/'):

              result = self.func.execute()

          self.assertEqual(result, SAMPLE_DATA)

  
@@ -379,7 +380,7 @@ 

          self.values = ["A", "B", "C", "D"]

  

      def test_base(self):

-         with self.app.application.test_request_context('/'):

+         with app.test_request_context('/'):

              result = self.paginate(self.values, 3)

          self.assertListEqual(result[0], self.values[:3])

          self.assertDictEqual(result[1], {
@@ -391,7 +392,7 @@ 

              })

  

      def test_page_2(self):

-         with self.app.application.test_request_context('/?page=2'):

+         with app.test_request_context('/?page=2'):

              result = self.paginate(self.values, 3)

          self.assertListEqual(result[0], self.values[3:])

          self.assertDictEqual(result[1], {
@@ -403,7 +404,7 @@ 

              })

  

      def test_page_0(self):

-         with self.app.application.test_request_context('/?page=0'):

+         with app.test_request_context('/?page=0'):

              result = self.paginate(self.values, 3)

          self.assertListEqual(result[0], self.values[:3])

          self.assertDictEqual(result[1], {
@@ -415,7 +416,7 @@ 

              })

  

      def test_invalid_page(self):

-         with self.app.application.test_request_context('/?page=blah'):

+         with app.test_request_context('/?page=blah'):

              result = self.paginate(self.values, 3)

          self.assertListEqual(result[0], self.values[:3])

          self.assertDictEqual(result[1], {
@@ -427,7 +428,7 @@ 

              })

  

      def test_page_too_high(self):

-         with self.app.application.test_request_context('/?page=3'):

+         with app.test_request_context('/?page=3'):

              result = self.paginate(self.values, 3)

          self.assertListEqual(result[0], self.values[3:])

          self.assertDictEqual(result[1], {
@@ -440,7 +441,7 @@ 

  

      def test_single_page(self):

          values = self.values[:3]

-         with self.app.application.test_request_context('/'):

+         with app.test_request_context('/'):

              result = self.paginate(values, 3)

          self.assertListEqual(result[0], values)

          self.assertDictEqual(result[1], {
@@ -453,7 +454,7 @@ 

  

      def test_no_value(self):

          values = []

-         with self.app.application.test_request_context('/'):

+         with app.test_request_context('/'):

              result = self.paginate(values, 3)

          self.assertListEqual(result[0], [])

          self.assertDictEqual(result[1], {

hubs/tests/widgets/test_library.py hubs/tests/test_widgets/test_library.py
file renamed
+2 -2
@@ -2,7 +2,7 @@ 

  

  import json

  

- from hubs.tests import FakeAuthorization

+ from hubs.tests import FakeAuthorization, widget_instance

  from . import WidgetTest

  

  
@@ -10,7 +10,7 @@ 

      plugin = 'library'  # The name in hubs.widgets.registry

  

      def test_data_simple(self):

-         widget = self.widget_instance('ralph', self.plugin)

+         widget = widget_instance('ralph', self.plugin)

          user = FakeAuthorization('ralph')

          response = self.check_url('/ralph/%i/json' % widget.idx, user)

          data = json.loads(response.get_data(as_text=True))

hubs/tests/widgets/test_meetings.py hubs/tests/test_widgets/test_meetings.py
file renamed
+3 -3
@@ -2,7 +2,7 @@ 

  

  import json

  

- from hubs.tests import FakeAuthorization

+ from hubs.tests import FakeAuthorization, widget_instance

  from . import WidgetTest

  

  
@@ -11,7 +11,7 @@ 

  

      def test_data_simple(self):

          team = 'i18n'

-         widget = self.widget_instance(team, self.plugin)

+         widget = widget_instance(team, self.plugin)

          user = FakeAuthorization('ralph')

          response = self.check_url('/%s/%i/json' % (team, widget.idx), user)

          data = json.loads(response.get_data(as_text=True))
@@ -20,7 +20,7 @@ 

  

      def test_render_simple(self):

          team = 'i18n'

-         widget = self.widget_instance(team, self.plugin)

+         widget = widget_instance(team, self.plugin)

          user = FakeAuthorization('ralph')

          url = '/%s/w/%s/%i/' % (team, self.plugin, widget.idx)

          response = self.check_url(url, user)

@@ -0,0 +1,26 @@ 

+ from __future__ import unicode_literals

+ 

+ import os

+ from hashlib import sha256

+ 

+ import fedmsg.config

+ import fedmsg.meta

+ from six.moves.urllib_parse import urlencode

+ 

+ 

+ def get_fedmsg_config():

+     try:

+         filenames = [os.environ["FEDMSG_CONFIG"]]

+     except KeyError:

+         filenames = None

+     fedmsg_config = fedmsg.config.load_config(filenames=filenames)

+     fedmsg.meta.make_processors(**fedmsg_config)

+     return fedmsg_config

+ 

+ 

+ def username2avatar(username, s=312):

+     query = urlencode([('s', s), ('d', 'retro')])

+     openid = 'http://%s.id.fedoraproject.org/' % username

+     hash = sha256(openid.encode('utf-8')).hexdigest()

+     avatar = "https://seccdn.libravatar.org/avatar/%s?%s" % (hash, query)

+     return avatar

hubs/utils/github.py hubs/utils.py
file renamed
-22
@@ -1,36 +1,14 @@ 

  from __future__ import unicode_literals

  

  import logging

- from hashlib import sha256

  

  import arrow

- import markdown

  import requests

  

- from six.moves.urllib_parse import urlencode

  

  log = logging.getLogger(__name__)

  

  

- def markup(text):

-     return markdown.markdown(

-         text,

-         safe_mode="replace",

-         html_replacement_text="--RAW HTML NOT ALLOWED--")

- 

- 

- def username2avatar(username, s=312):

-     query = urlencode([('s', s), ('d', 'retro')])

-     openid = 'http://%s.id.fedoraproject.org/' % username

-     hash = sha256(openid.encode('utf-8')).hexdigest()

-     avatar = "https://seccdn.libravatar.org/avatar/%s?%s" % (hash, query)

-     return avatar

- 

- 

- def commas(numeric):

-     return "{:,}".format(numeric)

- 

- 

  def github_repos(token, username):

      log.info("Finding github repos for %r" % username)

      tmpl = "https://api.github.com/users/{username}/repos?per_page=100"

file added
+15
@@ -0,0 +1,15 @@ 

+ from __future__ import unicode_literals

+ 

+ 

+ import markdown

+ 

+ 

+ def markup(text):

+     return markdown.markdown(

+         text,

+         safe_mode="replace",

+         html_replacement_text="--RAW HTML NOT ALLOWED--")

+ 

+ 

+ def commas(numeric):

+     return "{:,}".format(numeric)

hubs/utils/views.py hubs/views/utils.py
file renamed
+5 -6
@@ -1,6 +1,5 @@ 

  """

- The :py:mod:`hubs.views.utils` module contains helper functions and classes

- for the views.

+ This module contains helper functions and classes for the views.

  """

  

  from __future__ import unicode_literals
@@ -53,13 +52,13 @@ 

  def get_visible_widgets(hub):

      from hubs.widgets import registry

      widgets = {"left": [], "right": []}

+     try:

+         user = flask.g.auth.user

+     except AttributeError:

+         user = None

      for widget in hub.widgets:

          if widget.plugin not in registry:

              continue  # disabled widget

-         try:

-             user = flask.g.auth.user

-         except AttributeError:

-             user = None

          if not widget.allows(user, "view"):

              continue

          if widget.left:

file modified
+1 -1
@@ -1,6 +1,6 @@ 

  from __future__ import absolute_import

  

- # flake8:noqa

+ # flake8: noqa

  

  from .root import *

  from .hub import *

file modified
+1 -1
@@ -5,7 +5,7 @@ 

  import hubs.models

  

  from hubs.app import app

- from .utils import get_hub, login_required

+ from hubs.utils.views import get_hub, login_required

  

  

  @app.route('/api/hub/<hub>/subscribe', methods=['POST'])

file modified
+1 -1
@@ -5,7 +5,7 @@ 

  import hubs.models

  

  from hubs.app import app

- from .utils import (

+ from hubs.utils.views import (

      get_hub, get_visible_widgets, login_required, RequestValidator,

      require_hub_access,

      )

file modified
+1 -1
@@ -4,7 +4,7 @@ 

  import hubs.models

  

  from hubs.app import app, OIDC

- from .utils import authenticated, is_safe_url

+ from hubs.utils.views import authenticated, is_safe_url

  

  

  @app.route('/')

file modified
+1 -1
@@ -6,7 +6,7 @@ 

  import hubs.stream

  

  from hubs.app import app

- from .utils import (

+ from hubs.utils.views import (

      login_required, get_hub, get_visible_widgets, require_hub_access,

      )

  

file modified
+1 -1
@@ -5,7 +5,7 @@ 

  from hubs.app import app

  from hubs.widgets import registry

  from pkg_resources import resource_isdir

- from .utils import (

+ from hubs.utils.views import (

      create_widget_instance, configure_widget_instance, get_hub,

      get_widget_instance, login_required, WidgetConfigError,

      get_position, require_hub_access,

file modified
+5 -3
@@ -9,14 +9,15 @@ 

  import datetime

  import dogpile

  import dogpile.cache

- import fedmsg.config

  import logging

  

+ from hubs.utils import get_fedmsg_config

+ 

+ 

  log = logging.getLogger(__name__)

  

  

  def _get_cache():

-     config = fedmsg.config.load_config()

      cache_defaults = {

          "backend": "dogpile.cache.dbm",

          "expiration_time": 1,  # Expire every 1 second, for development
@@ -25,7 +26,8 @@ 

          },

      }

      cache = dogpile.cache.make_region()

-     cache.configure(**config.get('fedora-hubs.cache', cache_defaults))

+     fedmsg_config = get_fedmsg_config()

+     cache.configure(**fedmsg_config.get('fedora-hubs.cache', cache_defaults))

      return cache

  

  

@@ -1,16 +1,12 @@ 

  from __future__ import unicode_literals

  

- import fedmsg.config

- import fedmsg.meta

  import flask

  import hubs.models

  import requests

  import six

  

  from hubs.widgets.base import Widget, WidgetView

- from hubs.views.utils import login_required

- 

- config = fedmsg.config.load_config()

+ from hubs.utils.views import login_required

  

  

  class Contact(Widget):

@@ -5,12 +5,14 @@ 

  import fedmsg.meta

  import requests

  

- from hubs.utils import commas

+ from hubs.utils import get_fedmsg_config

+ from hubs.utils.text import commas

  from hubs.widgets import validators

  from hubs.widgets.base import Widget, WidgetView

  from hubs.widgets.caching import CachedFunction

  

- fedmsg_config = fedmsg.config.load_config()

+ 

+ fedmsg_config = get_fedmsg_config()

  

  

  class FedmsgStats(Widget):

@@ -1,16 +1,16 @@ 

  from __future__ import unicode_literals

  

  import logging

- import hubs.utils

  

+ from hubs.utils import get_fedmsg_config

+ from hubs.utils.github import github_repos, github_pulls

  from hubs.widgets import validators

  from hubs.widgets.base import Widget, WidgetView

  from hubs.widgets.caching import CachedFunction

  

- import fedmsg.config

- fedmsg_config = fedmsg.config.load_config()

  

  log = logging.getLogger(__name__)

+ fedmsg_config = get_fedmsg_config()

  

  

  class GitHubPRs(Widget):
@@ -63,9 +63,9 @@ 

          displayed_number = 0

          more = 0

          if token:

-             repos = hubs.utils.github_repos(token, org)

+             repos = github_repos(token, org)

              pulls = sum([

-                 list(hubs.utils.github_pulls(token, org, repo))

+                 list(github_pulls(token, org, repo))

                  for repo in repos

              ], [])

              # Reverse-sort by time (newest-first)

file modified
+6 -3
@@ -7,7 +7,7 @@ 

  from flask.signals import template_rendered

  

  from hubs.models import Hub

- from hubs.views.utils import get_hub, require_hub_access

+ from hubs.utils.views import get_hub, require_hub_access

  from hubs.widgets import registry

  from hubs.widgets.base import WidgetView

  from .functions import GetRequests
@@ -195,10 +195,13 @@ 

          )

      initial["hubs"] = [hub.name]

      context = dict(mode="add", url=post_url, initial=initial)

+     # Mimic flask.templating._render(). Too bad it's not a public API.

      if before_render_template is not None:

          before_render_template.send(

-             flask.current_app, template=template, context=context)

+             flask._app_ctx_stack.top.app,

+             template=template, context=context)

      output = template.render(**context)

      template_rendered.send(

-         flask.current_app, template=template, context=context)

+         flask._app_ctx_stack.top.app,

+         template=template, context=context)

      return output

@@ -5,7 +5,7 @@ 

  import datetime

  import requests

  

- from hubs import utils

+ from hubs.utils.text import markup

  from hubs.widgets import validators

  from hubs.widgets.base import Widget, WidgetView

  from hubs.widgets.caching import CachedFunction
@@ -65,7 +65,7 @@ 

          tmp = collections.defaultdict(list)

          for meeting in response['meetings']:

              if meeting.get('meeting_information_html'):

-                 meeting['meeting_information_html'] = utils.markup(

+                 meeting['meeting_information_html'] = markup(

                      meeting['meeting_information'])

              tmp[meeting['meeting_name']].append(meeting)

  

@@ -2,7 +2,7 @@ 

  

  import flask

  

- from hubs.utils import commas

+ from hubs.utils.text import commas

  from hubs.widgets.base import Widget, WidgetView

  from hubs.widgets.caching import CachedFunction

  

@@ -1,16 +1,17 @@ 

  from __future__ import unicode_literals

  

  import flask

- import hubs.models

+ from fedmsg.meta import msg2usernames

+ from fedmsg.meta.base import BaseConglomerator as BC

  

+ import hubs.models

+ from hubs.utils import get_fedmsg_config

  from hubs.widgets import validators

  from hubs.widgets.base import Widget, WidgetView

  from hubs.widgets.caching import CachedFunction

  

- from fedmsg.meta.base import BaseConglomerator as BC

  

- import fedmsg.config

- fm_config = fedmsg.config.load_config()

+ fedmsg_config = get_fedmsg_config()

  

  

  class Subscriptions(Widget):
@@ -74,5 +75,5 @@ 

          if not message['topic'].endswith('hubs.associate'):

              return False

          username = self.instance.config['username']

-         users = fedmsg.meta.msg2usernames(message, **fm_config)

+         users = msg2usernames(message, **fedmsg_config)

          return username in users

file modified
+6 -3
@@ -93,7 +93,7 @@ 

          }

  

      def _get_instance(self, *args, **kwargs):

-         from hubs.views.utils import get_widget_instance

+         from hubs.utils.views import get_widget_instance

          hubname = kwargs.pop("hub")

          widgetidx = kwargs.pop("idx")

          return get_widget_instance(hubname, widgetidx)
@@ -125,10 +125,13 @@ 

          else:

              context.update(self.get_extra_context(instance, *args, **kwargs))

              template = self.get_template()

+             # Mimic flask.templating._render(). Too bad it's not a public API.

              if before_render_template is not None:

                  before_render_template.send(

-                     flask.current_app, template=template, context=context)

+                     flask._app_ctx_stack.top.app,

+                     template=template, context=context)

              output = template.render(**context)

              template_rendered.send(

-                 flask.current_app, template=template, context=context)

+                 flask._app_ctx_stack.top.app,

+                 template=template, context=context)

              return output

file modified
+6 -7
@@ -7,11 +7,14 @@ 

  import socket

  import string

  

+ import fedora.client.fas2

+ 

  import hubs.models

+ from hubs.utils import get_fedmsg_config

  

- import fedora.client.fas2

- import fedmsg.config

- fedmsg_config = fedmsg.config.load_config()

+ 

+ fedmsg_config = get_fedmsg_config()

+ session = hubs.models.init(fedmsg_config['hubs.sqlalchemy.uri'], True, True)

  

  fasclient = fedora.client.fas2.AccountSystem(

      username=input('Your FAS username: '),
@@ -37,8 +40,6 @@ 

  

  

  for letter in reversed(sorted(list(set(string.letters.lower())))):

-     session = hubs.models.init(

-         fedmsg_config['hubs.sqlalchemy.uri'], True, True)

      print("Querying FAS for the %r users.. hang on." % letter)

      request = fasclient.send_request(

          '/user/list',
@@ -57,8 +58,6 @@ 

      session.commit()

  

      # Go back now and set up the groups...

-     session = hubs.models.init(

-         fedmsg_config['hubs.sqlalchemy.uri'], True, True)

      for user in users:

          hubs_user = hubs.models.User.by_username(user['username'])

  

file modified
+3 -2
@@ -7,9 +7,10 @@ 

  

  import hubs.models

  import hubs.widgets

+ from hubs.utils import get_fedmsg_config

  

- import fedmsg.config

- fedmsg_config = fedmsg.config.load_config()

+ 

+ fedmsg_config = get_fedmsg_config()

  

  session = hubs.models.init(fedmsg_config['hubs.sqlalchemy.uri'], True, True)

  

file modified
+1 -1
@@ -31,7 +31,7 @@ 

      os.environ['HUBS_CONFIG'] = config

  

  

- from hubs.app import app  # noqa

+ from hubs.app import app  # noqa: E402

  

  app.debug = True

  app.run(debug=True, host=args.host, port=int(args.port))

file modified
+1
@@ -2,3 +2,4 @@ 

  verbosity=2

  nocapture=1

  with-yanc=1

+ cover-package=hubs

file modified
+1 -1
@@ -40,7 +40,7 @@ 

      ],

      entry_points={

          'moksha.consumer': [

-             "cache_invalidator = hubs.backend.consumer:CacheInvalidatorExtraordinaire",  # noqa

+             "cache_invalidator = hubs.backend.consumer:CacheInvalidatorExtraordinaire",  # noqa: E501

          ],

      },

  )

file modified
+1 -8
@@ -12,20 +12,13 @@ 

  

  import argparse

  

- import fedmsg.config

- import fedmsg.meta

- 

- 

  import hubs.app

  import hubs.models

  import hubs.widgets.base

  import hubs.widgets.caching

  

  # get the DB session

- fedmsg_config = fedmsg.config.load_config()

- fedmsg.meta.make_processors(**fedmsg_config)

- 

- session = hubs.models.init(fedmsg_config['hubs.sqlalchemy.uri'])

+ session = hubs.app.session

  

  # Register widgets

  hubs.widgets.registry.register_list(hubs.app.app.config["WIDGETS"])

file modified
+3 -2
@@ -12,12 +12,13 @@ 

      -rtest-requirements.txt

  setenv =

      HUBS_CONFIG={toxinidir}/hubs/tests/hubs_test.cfg

+     FEDMSG_CONFIG={toxinidir}/hubs/tests/fedmsg_test.cfg

      PYTHONPATH={toxinidir}

  whitelist_externals =

      rm

  commands =

-     rm -f /var/tmp/fedora-hubs-cache.db*

-     nosetests --with-coverage --cover-erase --cover-package=hubs {posargs:hubs}

+     nosetests --with-coverage --cover-erase {posargs:hubs.tests}

+     coverage html

  

  [testenv:js]

  skip_install = True

The current situation with unit tests has some shortcomings, this branch brings the following improvements:

  • add a way to override the fedmsg configuration loading process, to avoid connecting to the prod database at the start of the testing phase.
  • improve coverage by excluding the tests themselves from the report and generating the HTML report, which is much more useful (and fast to generate)
  • split the huge test_fedora_hubs_api.py file into smaller files in a subdirectory
  • improve the testing decorators in hubs.tests to handle more cases and be more versatile
  • other more minor refactoring

Once again, there are many commits, .... you know the drill ;-)

The aim is to make it easier to run the tests, and to make them more independent from the production database / cache / fedmsg config.

rebased

6 years ago

1 new commit added

  • Reorganize the utils modules to avoid circular imports
6 years ago

Pull-Request has been merged by sayanchowdhury

6 years ago
Metadata
Changes Summary 85
+5
file added
.coveragerc
+1 -0
file changed
.gitignore
+3 -0
file changed
MANIFEST.in
+1 -4
file changed
check-cache-coverage.py
+3 -2
file changed
check-queue-length.py
+2 -3
file changed
delete-user.py
+1 -1
file changed
docs/api/views.rst
+5 -8
file changed
hubs/app.py
+8 -12
file changed
hubs/backend/triage.py
+4 -8
file changed
hubs/backend/worker.py
+2 -3
file changed
hubs/migrations/env.py
+49 -42
file changed
hubs/tests/__init__.py
+53
file added
hubs/tests/fedmsg_test.cfg
+9 -4
file changed
hubs/tests/test_authz.py
-587
file removed
hubs/tests/test_fedora_hubs_flask_api.py
+0 -4
file changed
hubs/tests/test_models.py
+23 -19
file changed
hubs/tests/test_view_utils.py
+14 -20
file changed
hubs/tests/test_widget_base.py
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_about.TestBadges.test_data_simple
hubs/tests/vcr-request-data/hubs.tests.widgets.test_about.TestBadges.test_data_simple
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_about.TestBadges.test_should_invalidate_good_match
hubs/tests/vcr-request-data/hubs.tests.widgets.test_about.TestBadges.test_should_invalidate_good_match
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_about.TestBadges.test_should_invalidate_wrong_topic
hubs/tests/vcr-request-data/hubs.tests.widgets.test_about.TestBadges.test_should_invalidate_wrong_topic
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_about.TestBadges.test_should_invalidate_wrong_user
hubs/tests/vcr-request-data/hubs.tests.widgets.test_about.TestBadges.test_should_invalidate_wrong_user
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_badges.TestBadges.test_data_simple
hubs/tests/vcr-request-data/hubs.tests.widgets.test_badges.TestBadges.test_data_simple
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_badges.TestBadges.test_should_invalidate_good_match
hubs/tests/vcr-request-data/hubs.tests.widgets.test_badges.TestBadges.test_should_invalidate_good_match
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_badges.TestBadges.test_should_invalidate_wrong_topic
hubs/tests/vcr-request-data/hubs.tests.widgets.test_badges.TestBadges.test_should_invalidate_wrong_topic
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_badges.TestBadges.test_should_invalidate_wrong_user
hubs/tests/vcr-request-data/hubs.tests.widgets.test_badges.TestBadges.test_should_invalidate_wrong_user
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_badges.TestBadges.test_view_authz
hubs/tests/vcr-request-data/hubs.tests.widgets.test_badges.TestBadges.test_view_authz
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_fedmsgstats.TestFedmsgStats.test_data_old
hubs/tests/vcr-request-data/hubs.tests.widgets.test_fedmsgstats.TestFedmsgStats.test_data_old
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_fedmsgstats.TestFedmsgStats.test_data_simple
hubs/tests/vcr-request-data/hubs.tests.widgets.test_fedmsgstats.TestFedmsgStats.test_data_simple
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_fedmsgstats.TestFedmsgStats.test_view_authz
hubs/tests/vcr-request-data/hubs.tests.widgets.test_fedmsgstats.TestFedmsgStats.test_view_authz
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_halp.HalpFunctionsTestCase.test_execute
hubs/tests/vcr-request-data/hubs.tests.widgets.test_halp.HalpFunctionsTestCase.test_execute
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_halp.HalpViewsTestCase.test_data
hubs/tests/vcr-request-data/hubs.tests.widgets.test_halp.HalpViewsTestCase.test_data
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_halp.HalpViewsTestCase.test_data_wrong_hub
hubs/tests/vcr-request-data/hubs.tests.widgets.test_halp.HalpViewsTestCase.test_data_wrong_hub
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_halp.HalpViewsTestCase.test_search_all
hubs/tests/vcr-request-data/hubs.tests.widgets.test_halp.HalpViewsTestCase.test_search_all
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_halp.HalpViewsTestCase.test_search_date
hubs/tests/vcr-request-data/hubs.tests.widgets.test_halp.HalpViewsTestCase.test_search_date
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_halp.HalpViewsTestCase.test_search_hub
hubs/tests/vcr-request-data/hubs.tests.widgets.test_halp.HalpViewsTestCase.test_search_hub
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_halp.HalpViewsTestCase.test_search_meetingname
hubs/tests/vcr-request-data/hubs.tests.widgets.test_halp.HalpViewsTestCase.test_search_meetingname
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_halp.HalpViewsTestCase.test_search_people
hubs/tests/vcr-request-data/hubs.tests.widgets.test_halp.HalpViewsTestCase.test_search_people
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_halp.HalpViewsTestCase.test_search_requesters
hubs/tests/vcr-request-data/hubs.tests.widgets.test_halp.HalpViewsTestCase.test_search_requesters
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_meetings.TestMeetings.test_data_simple
hubs/tests/vcr-request-data/hubs.tests.widgets.test_meetings.TestMeetings.test_data_simple
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_meetings.TestMeetings.test_render_simple
hubs/tests/vcr-request-data/hubs.tests.widgets.test_meetings.TestMeetings.test_render_simple
+0 -0
file renamed
hubs/tests/vcr-request-data/hubs.tests.test_widgets.test_meetings.TestMeetings.test_view_authz
hubs/tests/vcr-request-data/hubs.tests.widgets.test_meetings.TestMeetings.test_view_authz
+0 -0
file renamed
hubs/tests/test_api/__init__.py
hubs/tests/views/__init__.py
+0 -0
file renamed
hubs/tests/test_api/test_hub.py
hubs/tests/views/test_api.py
+166
file added
hubs/tests/views/test_hub_config.py
+114
file added
hubs/tests/views/test_hub_edit.py
+91
file added
hubs/tests/views/test_hub_view.py
+138
file added
hubs/tests/views/test_hub_widgets.py
+50
file added
hubs/tests/views/test_root.py
+48 -0
file renamed
hubs/tests/test_api/test_notifications.py
hubs/tests/views/test_user.py
+23
file added
hubs/tests/views/test_widget.py
+2 -2
file renamed
hubs/tests/test_widgets/__init__.py
hubs/tests/widgets/__init__.py
+2 -2
file renamed
hubs/tests/test_widgets/test_about.py
hubs/tests/widgets/test_about.py
+14 -10
file renamed
hubs/tests/test_widgets/test_badges.py
hubs/tests/widgets/test_badges.py
+6 -11
file renamed
hubs/tests/test_widgets/test_contact.py
hubs/tests/widgets/test_contact.py
+2 -2
file renamed
hubs/tests/test_widgets/test_fedmsgstats.py
hubs/tests/widgets/test_fedmsgstats.py
+12 -11
file renamed
hubs/tests/test_widgets/test_halp.py
hubs/tests/widgets/test_halp.py
+2 -2
file renamed
hubs/tests/test_widgets/test_library.py
hubs/tests/widgets/test_library.py
+3 -3
file renamed
hubs/tests/test_widgets/test_meetings.py
hubs/tests/widgets/test_meetings.py
+26
file added
hubs/utils/__init__.py
+0 -22
file renamed
hubs/utils.py
hubs/utils/github.py
+15
file added
hubs/utils/text.py
+5 -6
file renamed
hubs/views/utils.py
hubs/utils/views.py
+1 -1
file changed
hubs/views/__init__.py
+1 -1
file changed
hubs/views/api.py
+1 -1
file changed
hubs/views/hub.py
+1 -1
file changed
hubs/views/root.py
+1 -1
file changed
hubs/views/user.py
+1 -1
file changed
hubs/views/widget.py
+5 -3
file changed
hubs/widgets/caching.py
+1 -5
file changed
hubs/widgets/contact/__init__.py
+4 -2
file changed
hubs/widgets/fedmsgstats/__init__.py
+5 -5
file changed
hubs/widgets/github_pr/__init__.py
+6 -3
file changed
hubs/widgets/halp/views.py
+2 -2
file changed
hubs/widgets/meetings/__init__.py
+1 -1
file changed
hubs/widgets/stats/__init__.py
+6 -5
file changed
hubs/widgets/subscriptions/__init__.py
+6 -3
file changed
hubs/widgets/view.py
+6 -7
file changed
populate-from-fas.py
+3 -2
file changed
populate.py
+1 -1
file changed
runserver.py
+1 -0
file changed
setup.cfg
+1 -1
file changed
setup.py
+1 -8
file changed
smart_cache_invalidator.py
+3 -2
file changed
tox.ini