Example #1
0
def app(request, make_app_settings):
    """Session-wide test `Flask` application."""
    settings_override = make_app_settings()

    app = psef.create_app(
        settings_override, skip_celery=True, skip_perm_check=True
    )

    psef.tasks.celery.conf.update({
        'task_always_eager': False,
        'task_eager_propagates': False,
    })

    # Establish an application context before running the tests.
    with app.app_context():

        class FlaskTestClientProxy(object):
            def __init__(self, app):
                self.app = app

            def __call__(self, environ, start_response):
                if (
                    _TOKENS and _TOKENS[-1] is not None and
                    'HTTP_AUTHORIZATION' not in environ
                ):
                    environ['HTTP_AUTHORIZATION'] = f'Bearer {_TOKENS[-1]}'
                return self.app(environ, start_response)

        app.wsgi_app = FlaskTestClientProxy(app.wsgi_app)

        yield app
Example #2
0
def alembic_engine(alembic_tests_db, make_app_settings):
    app = psef.create_app(
        make_app_settings(database=alembic_tests_db.name),
        skip_all=True,
    )
    from flask_migrate import Migrate
    Migrate(app, psef.models.db, compare_type=True)
    with app.app_context():
        yield alembic_tests_db.engine
Example #3
0
def app(request):
    """Session-wide test `Flask` application."""
    settings_override = {
        'TESTING': True,
        'DEBUG': True,
        'UPLOAD_DIR': f'/tmp/psef/uploads',
        'RATELIMIT_STRATEGY': 'moving-window',
        'RATELIMIT_HEADERS_ENABLED': True,
        'CELERY_CONFIG': {
            'BROKER_URL': 'redis:///',
            'BACKEND_URL': 'redis:///'
        },
        'MIRROR_UPLOAD_DIR': f'/tmp/psef/mirror_uploads',
        'MAX_UPLOAD_SIZE': 2**20,  # 1mb
        'LTI_CONSUMER_KEY_SECRETS': {
            'my_lti': '12345678'
        },
    }
    if request.config.getoption('--postgresql'):
        print('Running with postgres!')
        pdb = request.config.getoption('--postgresql')
        settings_override['SQLALCHEMY_DATABASE_URI'] = f'postgresql:///{pdb}'
        settings_override['_USING_SQLITE'] = False
    else:
        settings_override['SQLALCHEMY_DATABASE_URI'] = TEST_DATABASE_URI
        settings_override['_USING_SQLITE'] = True

    settings_override['CELERY_CONFIG'] = {
        'CELERY_TASK_ALWAYS_EAGER': True,
        'CELERY_TASK_EAGER_PROPAGATES': True,
    }

    app = psef.create_app(settings_override, skip_celery=True)

    psef.tasks.celery.conf.update({
        'task_always_eager': False,
        'task_eager_propagates': False,
    })

    # Establish an application context before running the tests.
    with app.app_context():

        class FlaskTestClientProxy(object):
            def __init__(self, app):
                self.app = app

            def __call__(self, environ, start_response):
                if (_TOKENS and _TOKENS[-1] is not None
                        and 'HTTP_AUTHORIZATION' not in environ):
                    environ['HTTP_AUTHORIZATION'] = f'Bearer {_TOKENS[-1]}'
                return self.app(environ, start_response)

        app.wsgi_app = FlaskTestClientProxy(app.wsgi_app)

        yield app
Example #4
0
def app(request, make_app_settings):
    """Session-wide test `Flask` application."""
    settings_override = make_app_settings()

    app = psef.create_app(
        settings_override, skip_celery=True, skip_perm_check=True
    )
    app.config['__S_FEATURES']['GROUPS'] = True
    app.config['FEATURES'][psef.features.Feature.GROUPS] = True

    app.config['__S_FEATURES']['AUTO_TEST'] = True
    app.config['FEATURES'][psef.features.Feature.AUTO_TEST] = True

    app.config['__S_FEATURES']['INCREMENTAL_RUBRIC_SUBMISSION'] = True
    app.config['FEATURES'][psef.features.Feature.INCREMENTAL_RUBRIC_SUBMISSION
                           ] = True

    app.config['__S_FEATURES']['COURSE_REGISTER'] = True
    app.config['FEATURES'][psef.features.Feature.COURSE_REGISTER] = True

    app.config['__S_FEATURES']['RENDER_HTML'] = True
    app.config['FEATURES'][psef.features.Feature.RENDER_HTML] = True

    app.config['__S_FEATURES']['PEER_FEEDBACK'] = True
    app.config['FEATURES'][psef.features.Feature.PEER_FEEDBACK] = True

    psef.tasks.celery.conf.update({
        'task_always_eager': False,
        'task_eager_propagates': False,
    })

    # Establish an application context before running the tests.
    with app.app_context():

        class FlaskTestClientProxy(object):
            def __init__(self, app):
                self.app = app

            def __call__(self, environ, start_response):
                if (
                    _TOKENS and _TOKENS[-1] is not None and
                    'HTTP_AUTHORIZATION' not in environ
                ):
                    environ['HTTP_AUTHORIZATION'] = f'Bearer {_TOKENS[-1]}'
                return self.app(environ, start_response)

        app.wsgi_app = FlaskTestClientProxy(app.wsgi_app)

        yield app
Example #5
0
#!/usr/bin/env python3

# Run a test server.
import psef

if __name__ == '__main__':
    app = psef.create_app()
    app.run(host='0.0.0.0', port=5000, debug=True)
def migration_app(make_app_settings, fresh_database):
    app = psef.create_app(make_app_settings(database=fresh_database.name),
                          skip_celery=True,
                          skip_perm_check=True)
    Migrate(app, psef.models.db, compare_type=True)
    yield app
import os
import sys
import json
import uuid

main_dir = os.path.join(os.path.dirname(__file__), '..')
sys.path.append(main_dir)
os.chdir(main_dir)

if True:
    import psef
    from cg_request_args.open_api import OpenAPISchema

app = psef.create_app(skip_all=True)
app.config['SERVER_NAME'] = '$inst.codegra.de'
with app.app_context():
    res = OpenAPISchema({'psef': psef, 'uuid': uuid}).collect_for_current_app()

    base = os.path.join(os.path.dirname(__file__), '..')

    with open(sys.argv[1], 'w') as f:
        json.dump(res, f, indent=4)
Example #8
0
from flask_migrate import Migrate, MigrateCommand
from sqlalchemy_utils import PasswordType

import psef
import psef.models as m


def render_item(type_, col, autogen_context):
    if type_ == "type" and isinstance(col, PasswordType):
        autogen_context.imports.add("import sqlalchemy_utils")
        return "sqlalchemy_utils.PasswordType"
    else:
        return False


app = psef.create_app(skip_celery=True)

migrate = Migrate(app, psef.models.db, render_item=render_item)
manager = Manager(app)

manager.add_command('db', MigrateCommand)


@manager.command
def seed():
    if not app.config['DEBUG']:
        print(
            'Seeding the database is NOT safe if there is data in'
            ' the database, please use seed_force to seed anyway',
            file=sys.stderr
        )
Example #9
0
import psef
import cg_dt_utils
import psef.models as m


def render_item(type_, col, autogen_context):
    autogen_context.imports.add("import sqlalchemy_utils")
    if type_ == "type" and isinstance(col, PasswordType):
        return "sqlalchemy_utils.PasswordType"
    else:
        return False


app = psef.create_app(
    skip_celery=True,
    skip_perm_check=True,
    skip_secret_key_check=True,
)

migrate = Migrate(app,
                  psef.models.db,
                  render_item=render_item,
                  compare_type=True)
manager = Manager(app)

manager.add_command('db', MigrateCommand)


@manager.command
def seed():
    if not app.config['DEBUG']:
Example #10
0
def app(request):
    """Session-wide test `Flask` application."""
    auto_test_password = uuid.uuid4().hex
    settings_override = {
        'TESTING':
        True,
        'DEBUG':
        True,
        'UPLOAD_DIR':
        f'/tmp/psef/uploads',
        'RATELIMIT_STRATEGY':
        'moving-window',
        'RATELIMIT_HEADERS_ENABLED':
        True,
        'CELERY_CONFIG': {
            'BROKER_URL': 'redis:///',
            'BACKEND_URL': 'redis:///'
        },
        'MIRROR_UPLOAD_DIR':
        f'/tmp/psef/mirror_uploads',
        'MAX_FILE_SIZE':
        2**20,  # 1mb
        'MAX_NORMAL_UPLOAD_SIZE':
        4 * 2**20,  # 4 mb
        'MAX_LARGE_UPLOAD_SIZE':
        100 * 2**20,  # 100mb
        'LTI_CONSUMER_KEY_SECRETS': {
            'my_lti': 'Canvas:12345678',
            'no_secret': 'Canvas:',
            'no_lms': ':12345678',
            'no_colon': '12345678',
            'unknown_lms': 'unknown:12345678',
            'blackboard_lti': 'Blackboard:12345678',
            'moodle_lti': 'Moodle:12345678',
        },
        'LTI_SECRET_KEY':
        'hunter123',
        'SECRET_KEY':
        'hunter321',
        'HEALTH_KEY':
        'uuyahdsdsdiufhaiwueyrriu2h3',
        'CHECKSTYLE_PROGRAM': [
            "java",
            "-Dbasedir={files}",
            "-jar",
            os.path.join(os.path.dirname(__file__), '..', 'checkstyle.jar'),
            "-f",
            "xml",
            "-c",
            "{config}",
            "{files}",
        ],
        'PMD_PROGRAM': [
            os.path.join(os.path.dirname(__file__), '..', './pmd/bin/run.sh'),
            'pmd',
            '-dir',
            '{files}',
            '-failOnViolation',
            'false',
            '-format',
            'csv',
            '-shortnames',
            '-rulesets',
            '{config}',
        ],
        'MIN_PASSWORD_SCORE':
        3,
        'AUTO_TEST_PASSWORD':
        auto_test_password,
        'AUTO_TEST_CF_EXTRA_AMOUNT':
        2,
        '__S_AUTO_TEST_HOSTS': {
            f'http://127.0.0.1:{LIVE_SERVER_PORT}': {
                'password': auto_test_password,
                'type': 'simple_runner'
            }
        },
        'AUTO_TEST_DISABLE_ORIGIN_CHECK':
        True,
        'AUTO_TEST_MAX_TIME_COMMAND':
        3,
    }
    if request.config.getoption('--postgresql'):
        pdb, _ = get_database_name(request)

        settings_override['SQLALCHEMY_DATABASE_URI'] = f'postgresql:///{pdb}'
        settings_override['_USING_SQLITE'] = False
    else:
        settings_override['SQLALCHEMY_DATABASE_URI'] = TEST_DATABASE_URI
        settings_override['_USING_SQLITE'] = True

    settings_override['CELERY_CONFIG'] = {
        'CELERY_TASK_ALWAYS_EAGER': True,
        'CELERY_TASK_EAGER_PROPAGATES': True,
    }

    app = psef.create_app(settings_override,
                          skip_celery=True,
                          skip_perm_check=True)
    app.config['__S_FEATURES']['GROUPS'] = True
    app.config['FEATURES'][psef.features.Feature.GROUPS] = True

    app.config['__S_FEATURES']['AUTO_TEST'] = True
    app.config['FEATURES'][psef.features.Feature.AUTO_TEST] = True

    app.config['__S_FEATURES']['INCREMENTAL_RUBRIC_SUBMISSION'] = True
    app.config['FEATURES'][
        psef.features.Feature.INCREMENTAL_RUBRIC_SUBMISSION] = True

    psef.tasks.celery.conf.update({
        'task_always_eager': False,
        'task_eager_propagates': False,
    })

    # Establish an application context before running the tests.
    with app.app_context():

        class FlaskTestClientProxy(object):
            def __init__(self, app):
                self.app = app

            def __call__(self, environ, start_response):
                if (_TOKENS and _TOKENS[-1] is not None
                        and 'HTTP_AUTHORIZATION' not in environ):
                    environ['HTTP_AUTHORIZATION'] = f'Bearer {_TOKENS[-1]}'
                return self.app(environ, start_response)

        app.wsgi_app = FlaskTestClientProxy(app.wsgi_app)

        yield app
Example #11
0
        f.write(
            'export const FRONTEND_SETTINGS_DEFAULTS = Object.freeze(<const>{\n'
        )
        for opt in frontend_opts:
            f.write('    ')
            f.write(opt.tag)
            f.write(': ')
            json.dump(cg_json.JSONResponse.dump_to_object(opt.default), f)
            f.write(',\n')
        f.write('});\n\n')

        f.write('export const ALL_SITE_SETTINGS = Object.freeze(<const>[\n')
        for opt in all_opts:
            f.write('    {')
            f.write(f' name: {opt.tag!r},')
            f.write(f' typ: {opt.ts_type!r},')
            f.write(f' doc: {opt.doc!r},')
            f.write(f' format: {opt.ts_format!r},')
            f.write(f' group: ')
            json.dump(opt.group, f)
            f.write(', list: ')
            json.dump(opt.is_list, f)
            f.write(' },\n')
        f.write(']);\n\n')


if __name__ == '__main__':
    with psef.create_app(skip_all=True).app_context():
        main()
Example #12
0
import psef

app = psef.create_app(None, True)
celery = psef.tasks.celery