Example #1
0
class TestRun(unittest.TestCase):
    def setUp(self):
        self.config = Configurator()
        self.config.begin()
        
    def tearDown(self):
        self.config.end()

    def test_app(self):
        from tattoo.run import app
        myapp = app(None, 
                    setup_db=setup_db, 
                    populate=populate, 
                    db_path='mongo://foo.com:1235/dbname',
                    min_url_len=21,
                    )
        self.assertEquals(myapp.__class__.__name__, 'Router')
        
    def test_app_without_db_string(self):
        from tattoo.run import app
        self.assertRaises(ValueError, app, 
                          None, 
                          setup_db=setup_db, 
                          populate=populate, 
                          min_url_len=21,
                          )

    def test_setup_db(self):
        from tattoo.run import setup_db
        from ming import Session
        from tattoo.models import SESSION_NAME
        db_uri = 'mongo://foo.com:1235/dbname'
        setup_db(db_uri)
        session = Session.by_name(SESSION_NAME)
        self.assertTrue(SESSION_NAME in session._registry.keys())
Example #2
0
def app(global_config, **settings):
    """ This function returns a WSGI application.
    
    It is usually called by the PasteDeploy framework during 
    ``paster serve``.
    """
    zcml_file = settings.get('configure_zcml', 'configure.zcml')
    db_string = settings.get('db_string')
    if db_string is None:
        raise ValueError("No 'db_string' value in application configuration.")
    initialize_sql(db_string)
    config = Configurator(root_factory=get_root, settings=settings)
    config.begin()
    config.load_zcml(zcml_file)
    config.end()
    # Ugly hack to configure the MapperExtension with the settings.
    removal_extension.path = settings.get('upload_directory')
    
    scheduler = Scheduler()
    # Send out queued mails
    from eportfolio.utilities.mail_delivery import trigger_queued_delivery
    scheduler.add_interval_job(trigger_queued_delivery, seconds=30)
    scheduler.start()
    
    return config.make_wsgi_app()
Example #3
0
def main(global_config, **settings):
    """ This function returns a WSGI application.
    
    It is usually called by the PasteDeploy framework during 
    ``paster serve``.
    """
    from repoze.bfg.authentication import AuthTktAuthenticationPolicy
    from checking.authorization import RouteAuthorizationPolicy
    from checking.authentication import verifyUser

    if not settings.get("sqlalchemy.url"):
        raise ValueError(
            "No 'sqlalchemy.url' value in application configuration.")
    config = Configurator(settings=settings,
                          authentication_policy=AuthTktAuthenticationPolicy(
                              "secret",
                              callback=verifyUser,
                              timeout=30 * 60,
                              max_age=30 * 60,
                              reissue_time=20 * 60),
                          authorization_policy=RouteAuthorizationPolicy())
    config.hook_zca()
    config.begin()
    setupSqlalchemy(settings)
    setupRoutes(config)
    setupChameleon(config)
    setupi18n(config)
    config.end()

    app = config.make_wsgi_app()
    app = TM(app)

    return app
Example #4
0
class ModelUtilTests(unittest.TestCase):
    def setUp(self):
        self.config = Configurator()
        self.config.begin()

    def tearDown(self):
        self.config.end()

    def test_create_child_no_kwargs(self):
        from rfd.models import create_child
        class Thing(object):
            pass
        parent = Thing()
        name = "alice"
        child = create_child(Thing, parent, name)
        self.assertEqual(child.__parent__, parent)
        self.assertEqual(child.__name__, name)

    def test_create_child_with_kwargs(self):
        from rfd.models import create_child
        class Thing(object):
            pass
        parent = Thing()
        name = "alice"
        child = create_child(Thing, parent, name, foo="foo", bar="bar")
        self.assertEqual(child.__parent__, parent)
        self.assertEqual(child.__name__, name)
        self.assertEqual(child.foo, "foo")
        self.assertEqual(child.bar, "bar")
Example #5
0
def main(global_config, **settings):
    """ This function returns a WSGI application.
    
    It is usually called by the PasteDeploy framework during 
    ``paster serve``.
    """
    from repoze.bfg.authentication import AuthTktAuthenticationPolicy
    from checking.authorization import RouteAuthorizationPolicy
    from checking.authentication import verifyUser

    if not settings.get("sqlalchemy.url"):
        raise ValueError("No 'sqlalchemy.url' value in application configuration.")
    config = Configurator(settings=settings,
            authentication_policy=AuthTktAuthenticationPolicy("secret",
                callback=verifyUser,
                timeout=30*60, max_age=30*60,
                reissue_time=20*60),
            authorization_policy=RouteAuthorizationPolicy())
    config.hook_zca()
    config.begin()
    setupSqlalchemy(settings)
    setupRoutes(config)
    setupChameleon(config)
    setupi18n(config)
    config.end()

    app = config.make_wsgi_app()
    app = TM(app)

    return app
Example #6
0
def app(global_config, **settings):
    """ This function returns a WSGI application.
    
    It is usually called by the PasteDeploy framework during 
    ``paster serve``.
    """
    zcml_file = settings.get('configure_zcml', 'configure.zcml')
    db_string = settings.get('db_string')
    if db_string is None:
        raise ValueError("No 'db_string' value in application configuration.")
    initialize_sql(db_string)
    config = Configurator(root_factory=get_root, settings=settings)
    config.begin()
    config.load_zcml(zcml_file)
    config.end()
    # Ugly hack to configure the MapperExtension with the settings.
    removal_extension.path = settings.get('upload_directory')

    scheduler = Scheduler()
    # Send out queued mails
    from eportfolio.utilities.mail_delivery import trigger_queued_delivery
    scheduler.add_interval_job(trigger_queued_delivery, seconds=30)
    scheduler.start()

    return config.make_wsgi_app()
Example #7
0
class CodecTests(unittest.TestCase):
    def setUp(self):
        self.config = Configurator()
        self.config.begin()
    
    def tearDown(self):
        self.config.end()

    def _make_codec(self):
        from tattoo.codec import decode, encode, map_dict
        CHARS = u"ABC123.ä~€+"
        BASE = len(CHARS)
        map_dict.clear()
        for num in range(BASE):
            map_dict[num] = CHARS[num]
            map_dict[CHARS[num]] = num
        return decode, encode, map_dict

    def test_encode(self):
        decode, encode, map_dict = self._make_codec()
        self.assertEqual(encode(0), u'A')
        self.assertEqual(encode(10), u'+')
        self.assertEqual(encode(7), u'\xe4')
        self.assertEqual(encode(4), u'2')

    def test_decode(self):
        decode, encode, map_dict = self._make_codec()
        self.assertEqual(decode(u'A'), 0)
        self.assertEqual(decode(u'+'), 10)
        self.assertEqual(decode(u'\xe4'), 7)
        self.assertEqual(decode(u'2'), 4)
Example #8
0
def app(global_config, **settings):
    """ This function returns a WSGI application.
    
    It is usually called by the PasteDeploy framework during 
    ``paster serve``.
    """
    names = ('src_path', 'store_url', 'cache_url', 'max_entries', 'database', 'content_dir')
    values = []
    for name in names:
        val = settings.get(name)
        if val is None: 
            raise ValueError("No ’%s’ value in application configuration." % name) 
        values.append(val)
        
    src_path, store_url, cache_url, max_entries, database, content_dir = values
    
    zcml_file = settings.get('configure_zcml', 'configure.zcml')
    config = Configurator(settings=settings, root_factory=ContentRoot(content_dir))
    # use local component registry
    config.hook_zca()
    config.begin()
    config.load_zcml(zcml_file)
    
    register_source(src_path)
    register_store(store_url, cache_url, max_entries=max_entries)
    register_catalog(database)
    config.end()
    
    return config.make_wsgi_app()
Example #9
0
def app(global_config, **settings):
    """ This function returns a WSGI application.
    """
    zcml_file = settings.get('configure_zcml', 'configure.zcml')
    config = Configurator(root_factory=get_root, settings=settings)
    config.begin()
    config.load_zcml(zcml_file)
    config.end()
    return config.make_wsgi_app()
Example #10
0
def maintenance(global_config, **local_conf):
    config = Configurator()
    config.begin()
    config.add_static_view('static', 'karl.views:static')
    config.add_route(name='maintenance',
                    path='/*url',
                    view=dummy_view,
                    view_renderer='down_for_maintenance.pt')
    config.end()
    return config.make_wsgi_app()
Example #11
0
class BaseTest(unittest.TestCase):
    def setUp(self):
        self.config = Configurator()
        self.config.begin()
        _initTestingDB()

    def tearDown(self):
        from seantisinvoice.models import DBSession
        import transaction
        DBSession.remove()
        transaction.abort()
        self.config.end()
Example #12
0
def app(global_config, **settings):
    """ This function returns a WSGI application.
    
    It is usually called by the PasteDeploy framework during 
    ``paster serve``.
    """
    config = Configurator()
    config.begin()
    config.add_view(home, renderer="templates/home.pt")
    config.add_view(expense, name='expense', renderer='templates/expense.pt')
    config.end()
    return config.make_wsgi_app()
Example #13
0
class ViewTests(unittest.TestCase):
    def setUp(self):
        self.config = Configurator()
        self.config.begin()

    def tearDown(self):
        self.config.end()

    def test_my_view(self):
        from bmibargains.views import my_view
        request = testing.DummyRequest()
        info = my_view(request)
        self.assertEqual(info['project'], 'bmibargains')
Example #14
0
class BaseTest(unittest.TestCase):
    def setUp(self):
        self.config = Configurator()
        self.config.begin()
        _initTestingDB()

    def tearDown(self):
        from seantisinvoice.models import DBSession
        import transaction

        DBSession.remove()
        transaction.abort()
        self.config.end()
Example #15
0
class ViewTests(unittest.TestCase):
    def setUp(self):
        self.config = Configurator()
        self.config.begin()

    def tearDown(self):
        self.config.end()

    def test_filedrop_view(self):
        from rfd.views import filedrop
        request = testing.DummyRequest()
        context = None          # this can't be right
        info = filedrop(context, request)
        self.assertEqual(info['project'], 'rfd (repoze file drop)')
Example #16
0
class ViewTests(unittest.TestCase):
    def setUp(self):
        self.config = Configurator()
        self.config.begin()

    def tearDown(self):
        self.config.end()

    def test_my_view(self):
        from dubcore.views import my_view

        request = testing.DummyRequest()
        info = my_view(request)
        self.assertEqual(info["project"], "dubcore")
Example #17
0
class TestUtility(unittest.TestCase):
    def setUp(self):
        self.config = Configurator()
        self.config.begin()
        
    def tearDown(self):
        self.config.end()

    def test_expire_one_year(self):
        import datetime
        from tattoo.utility import expire_one_year
        nowish = datetime.datetime.now()
        delta = expire_one_year()-nowish
        self.assertEquals(delta.days, 365)
Example #18
0
class ModelTests(unittest.TestCase):
    def setUp(self):
        self.config = Configurator()
        self.config.begin()
    
    def tearDown(self):
        self.config.end()

    def test_url_model(self):
        from tattoo.models import URL
        url = URL(1234, 'long', 'short')
        self.assertEquals(url._id, 1234)
        self.assertEquals(url.url, 'long')
        self.assertEquals(url.short_url, 'short')
        self.assertEquals(type(url.created), type(datetime.datetime.now()))
Example #19
0
def app(global_config, **settings):
    """ This function returns a WSGI application.
    
    It is usually called by the PasteDeploy framework during 
    ``paster serve``.
    """
    zcml_file = settings.get('configure_zcml', 'configure.zcml')
    root = Root(settings.get('amqp_host', 'localhost'),
                settings.get('amqp_exchange', EXCHANGE))
    config = Configurator(root_factory=lambda request: root, settings=settings)
    config.begin()
    config.load_zcml(zcml_file)
    config.end()
    if settings.get('debug', None):
        return DebuggedApplication(config.make_wsgi_app(), True)
    else:
        return config.make_wsgi_app()
Example #20
0
def app(global_config, **settings):
    """ This function returns a WSGI application.

    It is usually called by the PasteDeploy framework during
    ``paster serve``.
    """
    zodb_uri = settings.get('zodb_uri')
    zcml_file = settings.get('configure_zcml', 'configure.zcml')
    if zodb_uri is None:
        raise ValueError("No 'zodb_uri' in application configuration.")

    finder = PersistentApplicationFinder(zodb_uri, appmaker)
    def get_root(request):
        return finder(request.environ)
    config = Configurator(root_factory=get_root, settings=settings)
    config.begin()
    config.load_zcml(zcml_file)
    config.end()
    return config.make_wsgi_app()
Example #21
0
class ViewTests(unittest.TestCase):

    """ These tests are unit tests for the view.  They test the
    functionality of *only* the view.  They register and use dummy
    implementations of repoze.bfg functionality to allow you to avoid
    testing 'too much'"""

    def setUp(self):
        """ cleanUp() is required to clear out the application registry
        between tests (done in setUp for good measure too)
        """
        self.config = Configurator()
        self.config.begin()
        self.config.add_settings({'title' : 'Tattoo', 'description' : 'Another URL Shortener'})
        self.config.add_route(name='home', path='', request_method='GET')
        self.config.add_route(name='view', path=':short_url', request_method='GET')
        self.config.add_route(name='post', path ='', request_method='POST')
        self.config.add_route(name='put', path='', request_method='PUT')
        self.config.add_route(name='list', path='list', request_method='GET')
        self.config.add_route(name='nohead', path=':short_url', request_method='HEAD')
        self.config.add_static_view(name='static', path='templates/static', cache_max_age=0)
        self.config.scan()
        
    def tearDown(self):
        """ cleanUp() is required to clear out the application registry
        between tests
        """
        self.config.end()

    def _callFUT(self, context, request, view):
        return view(request)

    def test_home_view(self):
        from tattoo.views import home_view
        context = testing.DummyModel(title='Tattoo',
                                     description="URL Shortener")
        request = testing.DummyRequest()
        self._callFUT(context, request, home_view)
        view = home_view(request)
        self.assertEquals(view['title'], 'Tattoo')
        self.assertEquals(view['description'], "Another URL Shortener")
Example #22
0
def mailin_monitor_view(context, request):
    """
    Dispatches to a subapp from repoze.mailin.monitor.  I know this looks kind
    of horrible, but this is the best way I know how to mount another object
    graph onto the root object graph in BFG 1.2.  BFG 1.3 will theoretically
    allow SCRIPT_NAME/PATH_INFO rewriting for routes of the form
    '/some/path/*traverse', making it easier to do this with just a route,
    rather than actually constituting a whole new bfg app just to serve this
    subtree.
    """
    global _mailin_monitor_app
    if _mailin_monitor_app is None:
        # Keep imports local in hopes that this can be removed when BFG 1.3
        # comes out.
        from repoze.bfg.authorization import ACLAuthorizationPolicy
        from repoze.bfg.configuration import Configurator
        from karl.models.mailin_monitor import KarlMailInMonitor
        from karl.security.policy import get_groups
        from repoze.bfg.authentication import RepozeWho1AuthenticationPolicy

        authentication_policy = RepozeWho1AuthenticationPolicy(
            callback=get_groups
        )
        authorization_policy = ACLAuthorizationPolicy()
        config = Configurator(root_factory=KarlMailInMonitor(),
                              authentication_policy=authentication_policy,
                              authorization_policy=authorization_policy)
        config.begin()
        config.load_zcml('repoze.mailin.monitor:configure.zcml')
        config.end()
        _mailin_monitor_app = config.make_wsgi_app()

    # Dispatch to subapp
    import webob
    sub_environ = request.environ.copy()
    sub_environ['SCRIPT_NAME'] = '/%s/%s' % (model_path(context),
                                            request.view_name)
    sub_environ['PATH_INFO'] = '/' + '/'.join(request.subpath)
    sub_request = webob.Request(sub_environ)
    return sub_request.get_response(_mailin_monitor_app)
Example #23
0
def app(global_config, **settings):
    """ This function returns a repoze.bfg.router.Router object.
    
    It is usually called by the PasteDeploy framework during ``paster serve``.
    """
    db_string = settings.get('db_string')
    if db_string is None:
        raise ValueError("No 'db_string' value in application configuration.")
    initialize_sql(db_string)
    
    # Scheduler to copy recurring invoices
    s = Scheduler()
    # Check every 5 minutes for recurring invoices
    s.add_interval_task(copy_recurring, 300)
    s.start_scheduler()
    
    config = Configurator(root_factory=RootFactory, settings=settings)
    config.begin()
    zcml_file = settings.get('configure_zcml', 'configure.zcml')
    config.load_zcml(zcml_file)
    config.end()
    return config.make_wsgi_app()
Example #24
0
    authentication_policy = RemoteUserAuthenticationPolicy()
    authorization_policy = ACLAuthorizationPolicy()
    config = Configurator(
        root_factory=get_root,
        default_permission='view',
        authentication_policy=authentication_policy,
        authorization_policy=authorization_policy,
    )
    config.begin()

    ## Configure views
    config.add_view(unprotected)
    config.add_view(protected, 'protected.html', permission='view_protected')
    config.add_view(login, 'login.html')
    config.add_view(logout, 'logout.html')
    config.end()

    ## Create the app object.
    app = config.make_wsgi_app()

    # Configure the repoze.who middleware:

    ## fake .htpasswd authentication source
    io = StringIO()
    for name, password in [('admin', 'admin'), ('user', 'user')]:
        io.write('%s:%s\n' % (name, password))
    io.seek(0)

    def cleartext_check(password, hashed):
        return password == hashed
Example #25
0
    authentication_policy = RemoteUserAuthenticationPolicy()
    authorization_policy = ACLAuthorizationPolicy()
    config = Configurator(
        root_factory=get_root,
        default_permission="view",
        authentication_policy=authentication_policy,
        authorization_policy=authorization_policy,
    )
    config.begin()

    ## Configure views
    config.add_view(unprotected)
    config.add_view(protected, "protected.html", permission="view_protected")
    config.add_view(login, "login.html")
    config.add_view(logout, "logout.html")
    config.end()

    ## Create the app object.
    app = config.make_wsgi_app()

    # Configure the repoze.who middleware:

    ## fake .htpasswd authentication source
    io = StringIO()
    for name, password in [("admin", "admin"), ("user", "user")]:
        io.write("%s:%s\n" % (name, password))
    io.seek(0)

    def cleartext_check(password, hashed):
        return password == hashed
Example #26
0
class EPortfolioTestCase(unittest.TestCase):
    def setUp(self):
        # Warnings become errors!
        #import warnings
        #warnings.filterwarnings('error',category=Warning)

        self.config = Configurator()
        self.config.begin()
        _initTestingDB()

        # Setup dummy mailer
        self.mailer = DummyMailer()
        self.config.registry.registerUtility(self.mailer)
        self.config.registry.registerUtility(MailService())

    def tearDown(self):
        from eportfolio.models import DBSession
        import transaction
        DBSession.remove()
        transaction.abort()
        self.config.end()

    def _add_student(self,
                     first_name=u"Buck",
                     last_name=u"Mulligan",
                     email=u"*****@*****.**",
                     password=u'123456'):
        from eportfolio.models.student import Student
        from eportfolio.models import DBSession
        session = DBSession()
        student = Student()
        student.first_name = first_name
        student.last_name = last_name
        student.email = email
        student.password = u'{SHA}%s' % sha.new(password).hexdigest()
        session.add(student)
        session.flush()
        return student

    def _add_teacher(self,
                     first_name=u'Leopold',
                     last_name=u'Bloom',
                     email=u'*****@*****.**',
                     password=u'12345'):
        from eportfolio.models.teacher import Teacher
        from eportfolio.models import DBSession
        session = DBSession()
        teacher = Teacher()
        teacher.first_name = first_name
        teacher.last_name = last_name
        teacher.email = email
        teacher.password = u'{SHA}%s' % sha.new(password).hexdigest()
        session.add(teacher)
        session.flush()
        return teacher

    def _add_project(self, title=u"Project", start_date=None, end_date=None):
        from eportfolio.models.project import Project
        from eportfolio.models import DBSession

        if not start_date:
            start_date = datetime.date.today() - datetime.timedelta(days=10)

        if not end_date:
            end_date = datetime.date.today() + datetime.timedelta(days=10)

        session = DBSession()
        project = Project()
        project.title = title
        project.start_date = start_date
        project.end_date = end_date
        session.add(project)
        session.flush()
        return project

    def _add_objective(self,
                       title=u'Objective',
                       description=u'Objective',
                       project=None):
        from eportfolio.models.objective import Objective
        from eportfolio.models import DBSession

        if not project:
            project = self._add_project()

        session = DBSession()
        objective = Objective(title=title,
                              description=description,
                              project=project)
        session.add(objective)
        session.flush()
        return objective

    def _add_meta_competence(self,
                             title=u'Meta competence',
                             description=u'Meta competence'):
        from eportfolio.models.meta_competence import MetaCompetence
        from eportfolio.models import DBSession

        session = DBSession()
        meta_competence = MetaCompetence(title=title, description=description)
        session.add(meta_competence)
        session.flush()
        return meta_competence

    def _add_competence(self,
                        title=u'Competence',
                        description=u'Competence',
                        meta_competence=None):
        from eportfolio.models.competence import Competence
        from eportfolio.models import DBSession

        if not meta_competence:
            meta_competence = self._add_meta_competence()

        session = DBSession()
        competence = Competence(title=title,
                                description=description,
                                meta_competence=meta_competence)
        session.add(competence)
        session.flush()
        return competence

    def _add_indicator_set(self,
                           title=u'Indicator set',
                           description=u'Indicator set',
                           competence=None):
        from eportfolio.models.indicator_set import IndicatorSet
        from eportfolio.models import DBSession

        if not competence:
            competence = self._add_competence()

        session = DBSession()
        indicator_set = IndicatorSet(title=title,
                                     description=description,
                                     competence=competence)
        session.add(indicator_set)
        session.flush()
        return indicator_set

    def _add_indicator(self,
                       title=u'Indicator',
                       description=u'Indicator',
                       indicator_set=None):
        from eportfolio.models.indicator import Indicator
        from eportfolio.models import DBSession

        if not indicator_set:
            indicator_set = self._add_indicator_set()

        session = DBSession()
        indicator = Indicator(title=title,
                              description=description,
                              indicator_set=indicator_set)
        session.add(indicator)
        session.flush()
        return indicator
Example #27
0
class ViewTests(unittest.TestCase):
    def setUp(self):
        self.config = Configurator()
        self.config.begin()

    def tearDown(self):
        self.config.end()

    def test_view_home(self):
        from views import home

        request = testing.DummyRequest()
        info = home(request)
        self.assertEqual(info["message"], "")

    def test_get_bank_accounts_bad_domain(self):
        from views import _get_bank_accounts
        from views import NonXMLResponseError

        self.assertRaises(NonXMLResponseError, _get_bank_accounts, "baddomain", "email", "password")

    def test_get_bank_accounts_bad_auth(self):
        from views import _get_bank_accounts
        from views import BadAuthError

        self.assertRaises(BadAuthError, _get_bank_accounts, "koansyssandbox", "bademail", "badpassword")

    def test_get_bank_accounts_exist(self):
        from views import _get_bank_accounts

        domain = "koansyssandbox"
        email = "*****@*****.**"
        password = "******"
        accounts = _get_bank_accounts(domain, email, password)
        # we don't know the bank account numbers or names
        # so just check we get a non-empty dict and an id is integer
        self.assertEquals(type(accounts), dict)
        self.assertNotEqual(len(accounts), 0)
        self.assertTrue(int(accounts.keys()[0]))

    def test_get_bank_account_entries(self):
        from views import _get_bank_account_entries

        domain = "koansyssandbox"
        email = "*****@*****.**"
        password = "******"
        account = "6951"
        entries = _get_bank_account_entries(domain, email, password, account)
        print entries
        # we don't know the bank account numbers or names
        # so just check we get a non-empty dict and an id is integer
        # self.assertEquals(type(accounts), dict)
        # self.assertNotEqual(len(accounts), 0)
        # self.assertTrue(int(accounts.keys()[0]))

    def test_get_expense_types(self):
        from views import _get_expenses_types

        domain = "koansyssandbox"
        email = "*****@*****.**"
        password = "******"
        expenses = _get_expenses_types(domain, email, password)
        print expenses
Example #28
0
class ViewIntegrationTests(unittest.TestCase):
    def setUp(self):
        self.config = Configurator()
        self.config.begin()
        self.config.add_settings({'title' : 'Tattoo', 
                                  'description' : 'Another URL Shortener',
                                  'min_url_len': '21',
                                  'reload_templates' : False})
        self.config.add_route(name='home', path='', request_method='GET')
        self.config.add_route(name='view', path=':short_url', request_method='GET')
        self.config.add_route(name='post', path ='', request_method='POST')
        self.config.add_route(name='put', path='', request_method='PUT')
        self.config.add_route(name='list', path='list', request_method='GET')
        self.config.add_route(name='nohead', path=':short_url', request_method='HEAD')
        self.config.add_static_view(name='static', path='templates/static', cache_max_age=0)
        self.config.scan()

    def tearDown(self):
         self.config.end()

    def _make_request(self, dispatch):
        request = testing.DummyRequest(              
            url='AURL',
            environ={'HTTP_HOST': 'bfg.io:80'},
            matchdict= {'short_url': u'8K!kpD'},
            dispatch=dispatch)
        return request

    def test_url_view(self):
        from tattoo.views import url_view
        request = self._make_request(dispatch=None)
        result = url_view(request, URL=URL)
        self.assertEquals(result.status, '302 Found')
        self.assertEquals(result.headers['location'], 'AUrl')

    def test_url_not_found(self):
        from tattoo.views import url_view
        request = self._make_request(dispatch='test_stop_iteration')
        URL = DummyURL()
        URL.m.find = ModelURL({})
        URL.m.find.one = StopIteration
        result = url_view(request, URL=URL)
        self.assertEquals(result.status, '404 Not Found')
        self.assertEquals(result.body, '<h1>404 Not Found</h1> Nobody here but us fish...glug glug.')
        

    def test_post_view_new(self):
        from tattoo.views import create_post_view
        request = testing.DummyRequest(              
            url='http://bfg.io/create?url=http://example.com/somplace/really/long',
            environ={'HTTP_HOST': 'bfg.io:80'})
        result = create_post_view(request, url_factory=url_factory)
        self.assertEqual(result.status, '200 OK')

    def test_post_view_zero(self):
        from tattoo.views import create_post_view
        request = self._make_request(dispatch='test_zero')
        result = create_post_view(request, url_factory=url_factory)
        self.assertEqual(result.status, '412 Precondition Failed')

    def test_post_view_one(self):
        from tattoo.views import create_post_view
        request = self._make_request(dispatch='test_one')
        result = create_post_view(request, url_factory=url_factory)
        self.assertEqual(result.status, '303 See Other')

    def test_post_view_not_found(self):
        from tattoo.views import create_post_view
        request = self._make_request(dispatch='test_not_found')
        result = create_post_view(request, url_factory=url_factory)
        self.assertEqual(result.status, '404 Not Found')

    def test_post_view_precond_failed(self):
        from tattoo.views import create_post_view
        request = self._make_request(dispatch='test_precondfailed')
        result = create_post_view(request, url_factory=url_factory)
        self.assertEqual(result.status, '412 Precondition Failed')
        
    def test_post_view_too_short(self):
        from tattoo.views import create_post_view
        request = self._make_request(dispatch='test_too_short')
        result = create_post_view(request, url_factory=url_factory)
        self.assertEqual(result.status, '303 See Other')
        self.assertEqual(result.headers['location'], 'short')

    def test_put_view_integration(self):
        from tattoo.views import put_view
        request = testing.DummyRequest(              
            url='http://bfg.io/create?url=http://example.com/somplace/really/long',
            environ={'HTTP_HOST': 'bfg.io:80'})
        result = put_view(request, url_factory=url_factory)
        self.assertEqual(result.status, '201 Created')

    def test_put_view_zero(self):
        from tattoo.views import put_view
        request = self._make_request(dispatch='test_zero')
        result = put_view(request, url_factory=url_factory)
        self.assertEqual(result.status, '412 Precondition Failed')

    def test_put_view_one(self):
        from tattoo.views import put_view
        request = self._make_request(dispatch='test_one')
        result = put_view(request, url_factory=url_factory)
        self.assertEqual(result.status, '303 See Other')

    def test_put_view_not_found(self):
        from tattoo.views import put_view
        request = self._make_request(dispatch='test_not_found')
        result = put_view(request, url_factory=url_factory)
        self.assertEqual(result.status, '404 Not Found')

    def test_put_view_precond_failed(self):
        from tattoo.views import put_view
        request = self._make_request(dispatch='test_precondfailed')
        result = put_view(request, url_factory=url_factory)
        self.assertEqual(result.status, '412 Precondition Failed')
        
    def test_put_view_too_short(self):
        from tattoo.views import put_view
        request = self._make_request(dispatch='test_too_short')
        result = put_view(request, url_factory=url_factory)
        self.assertEqual(result.status, '303 See Other')
        self.assertEqual(result.headers['location'], 'short')

    def test_not_allowed(self):
        from tattoo.views import not_allowed
        request = self._make_request(dispatch=None)
        result = not_allowed(request)
        self.assertEquals(result.status, '405 Method Not Allowed')
        self.assertEquals(result.headers['Allow'], 'GET') 
Example #29
0
class EPortfolioTestCase(unittest.TestCase):
    
    def setUp(self):
        # Warnings become errors!
        #import warnings
        #warnings.filterwarnings('error',category=Warning)
        
        self.config = Configurator()
        self.config.begin()
        _initTestingDB()
        
        # Setup dummy mailer
        self.mailer = DummyMailer()
        self.config.registry.registerUtility(self.mailer)
        self.config.registry.registerUtility(MailService())
        
    def tearDown(self):
        from eportfolio.models import DBSession
        import transaction
        DBSession.remove()
        transaction.abort()
        self.config.end()
        
    def _add_student(self, first_name=u"Buck", last_name=u"Mulligan", 
                     email=u"*****@*****.**", password=u'123456'):
        from eportfolio.models.student import Student
        from eportfolio.models import DBSession
        session = DBSession()
        student = Student()
        student.first_name = first_name
        student.last_name = last_name
        student.email = email
        student.password = u'{SHA}%s' % sha.new(password).hexdigest()
        session.add(student)
        session.flush()
        return student
        
    def _add_teacher(self, first_name=u'Leopold', last_name=u'Bloom',
                     email=u'*****@*****.**', password=u'12345'):
        from eportfolio.models.teacher import Teacher
        from eportfolio.models import DBSession
        session = DBSession()
        teacher = Teacher()
        teacher.first_name = first_name
        teacher.last_name = last_name
        teacher.email = email
        teacher.password = u'{SHA}%s' % sha.new(password).hexdigest()
        session.add(teacher)
        session.flush()
        return teacher
        
    def _add_project(self, title=u"Project", start_date=None, end_date=None):
        from eportfolio.models.project import Project
        from eportfolio.models import DBSession
        
        if not start_date:
            start_date = datetime.date.today() - datetime.timedelta(days=10)
            
        if not end_date:
            end_date = datetime.date.today() + datetime.timedelta(days=10)
            
        session = DBSession()
        project = Project()
        project.title = title
        project.start_date = start_date
        project.end_date = end_date
        session.add(project)
        session.flush()
        return project
        
    def _add_objective(self, title=u'Objective', description=u'Objective', project=None):
        from eportfolio.models.objective import Objective
        from eportfolio.models import DBSession
        
        if not project:
            project = self._add_project()
        
        session = DBSession()
        objective = Objective(title=title, description=description, project=project)
        session.add(objective)
        session.flush()
        return objective
        
    def _add_meta_competence(self, title=u'Meta competence', description=u'Meta competence'):
        from eportfolio.models.meta_competence import MetaCompetence
        from eportfolio.models import DBSession
        
        session = DBSession()
        meta_competence = MetaCompetence(title=title, description=description)
        session.add(meta_competence)
        session.flush()
        return meta_competence
        
    def _add_competence(self, title=u'Competence', description=u'Competence', meta_competence=None):
        from eportfolio.models.competence import Competence
        from eportfolio.models import DBSession
        
        if not meta_competence:
            meta_competence = self._add_meta_competence()
        
        session = DBSession()
        competence = Competence(title=title, description=description, meta_competence=meta_competence)
        session.add(competence)
        session.flush()
        return competence
        
    def _add_indicator_set(self, title=u'Indicator set', description=u'Indicator set', competence=None):
        from eportfolio.models.indicator_set import IndicatorSet
        from eportfolio.models import DBSession
        
        if not competence:
            competence = self._add_competence()
            
        session = DBSession()
        indicator_set = IndicatorSet(title=title, description=description, competence=competence)
        session.add(indicator_set)
        session.flush()
        return indicator_set
        
    def _add_indicator(self, title=u'Indicator', description=u'Indicator', indicator_set=None):
        from eportfolio.models.indicator import Indicator
        from eportfolio.models import DBSession
        
        if not indicator_set:
            indicator_set = self._add_indicator_set()
        
        session = DBSession()
        indicator = Indicator(title=title, description=description, indicator_set=indicator_set)
        session.add(indicator)
        session.flush()
        return indicator