conftest.py 8.25 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
'''
Faraday Penetration Test IDE
Copyright (C) 2013  Infobyte LLC (http://www.infobytesec.com/)
See the file 'doc/LICENSE' for the license information

'''
from tempfile import NamedTemporaryFile

import os
import sys
import json
import inspect
import pytest
from factory import Factory
from flask.testing import FlaskClient
from flask_principal import Identity, identity_changed
from sqlalchemy import event
from pytest_factoryboy import register

sys.path.append(os.path.abspath(os.getcwd()))
from server.app import create_app
from server.models import db
from test_cases import factories

25 26

TEMPORATY_SQLITE = NamedTemporaryFile()
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
# Discover factories to automatically register them to pytest-factoryboy and to
# override its session
enabled_factories = []
for attr_name in dir(factories):
    obj = getattr(factories, attr_name)
    if not inspect.isclass(obj):
        continue
    if not issubclass(obj, Factory):
        continue
    if obj._meta.model is None:
        # It is an abstract class
        continue
    enabled_factories.append(obj)

for factory in enabled_factories:
    register(factory)

register(factories.WorkspaceFactory, "second_workspace")


class CustomClient(FlaskClient):

    def open(self, *args, **kwargs):
        if kwargs.pop('use_json_data', True) and 'data' in kwargs:
            # JSON-encode data by default
            kwargs['data'] = json.dumps(kwargs['data'])
            kwargs['headers'] = kwargs.get('headers', []) + [
                ('Content-Type', 'application/json'),
            ]

        # Reset queries to make the log_queries_count
        from flask import _app_ctx_stack
        _app_ctx_stack.top.sqlalchemy_queries = []

        ret = super(CustomClient, self).open(*args, **kwargs)
        #Now set in flask 1.0
        #if ret.headers.get('content-type') == 'application/json':
        #    try:
        #        ret.json = json.loads(ret.data)
        #    except ValueError:
        #        ret.json = None
        return ret


def pytest_addoption(parser):
    # currently for tests using sqlite and memory have problem while using transactions
    # we need to review sqlite configuraitons for persistence using PRAGMA.
74
    parser.addoption('--connection-string', default='sqlite:////{0}'.format(TEMPORATY_SQLITE.name),
75 76 77 78 79 80 81 82 83 84 85 86 87 88
                     help="Database connection string. Defaults to in-memory "
                     "sqlite if not specified:")
    parser.addoption('--ignore-nplusone', action='store_true',
                     help="Globally ignore nplusone errors")
    parser.addoption("--with-hypothesis", action="store_true",
                     dest="use_hypothesis", default=False,
                     help="Run property based tests")


def pytest_configure(config):
    if not config.option.use_hypothesis:
        config.option.markexpr = 'not hypothesis'


89
@pytest.fixture(scope='session')
90
def app(request):
91 92
    app = create_app(db_connection_string=request.config.getoption(
        '--connection-string'), testing=True)
93 94 95 96 97 98 99
    app.test_client_class = CustomClient

    # Establish an application context before running the tests.
    ctx = app.app_context()
    ctx.push()

    def teardown():
100
        TEMPORATY_SQLITE.close()
101 102 103 104 105 106 107 108
        ctx.pop()

    request.addfinalizer(teardown)
    app.config['NPLUSONE_RAISE'] = not request.config.getoption(
        '--ignore-nplusone')
    return app


109
@pytest.fixture(scope='session')
110 111 112
def database(app, request):
    """Session-wide test database."""

113 114 115 116 117 118 119 120 121 122 123
    def teardown():
        try:
            db.engine.execute('DROP TABLE vulnerability CASCADE')
        except Exception:
            pass
        try:
            db.engine.execute('DROP TABLE vulnerability_template CASCADE')
        except Exception:
            pass
        db.drop_all()

124 125 126
    # Disable check_vulnerability_host_service_source_code constraint because
    # it doesn't work in sqlite
    vuln_constraints = db.metadata.tables['vulnerability'].constraints
127 128 129 130 131
    vuln_constraints.remove(next(
        constraint for constraint in vuln_constraints
        if constraint.name == 'check_vulnerability_host_service_source_code'))

    db.app = app
132 133
    db.create_all()

134
    request.addfinalizer(teardown)
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    return db


@pytest.fixture(scope='function')
def fake_session(database, request):
    connection = database.engine.connect()
    transaction = connection.begin()

    options = {"bind": connection, 'binds': {}}
    session = db.create_scoped_session(options=options)

    database.session = session
    db.session = session

    for factory in enabled_factories:
        factory._meta.sqlalchemy_session = session

    def teardown():
        # rollback - everything that happened with the
        # Session above (including calls to commit())
        # is rolled back.
        # be careful with this!!!!!
        transaction.rollback()
        connection.close()
        session.remove()

    request.addfinalizer(teardown)
    return session


@pytest.fixture(scope='function')
def session(database, request):
    """Use this fixture if the function being tested does a session
    rollback.

    See http://docs.sqlalchemy.org/en/latest/orm/session_transaction.html#joining-a-session-into-an-external-transaction-such-as-for-test-suites
    for further information
    """
    connection = database.engine.connect()
174
    transaction = connection.begin()
175 176 177 178 179

    options = {"bind": connection, 'binds': {}}
    session = db.create_scoped_session(options=options)

    # start the session in a SAVEPOINT...
180 181 182 183 184 185 186 187 188 189 190 191 192
    session.begin_nested()

    # then each time that SAVEPOINT ends, reopen it
    @event.listens_for(session, "after_transaction_end")
    def restart_savepoint(session, transaction):
        if transaction.nested and not transaction._parent.nested:

            # ensure that state is expired the way
            # session.commit() at the top level normally does
            # (optional step)
            session.expire_all()

            session.begin_nested()
193 194 195 196 197 198 199 200 201 202 203 204

    database.session = session
    db.session = session

    for factory in enabled_factories:
        factory._meta.sqlalchemy_session = session

    def teardown():
        # rollback - everything that happened with the
        # Session above (including calls to commit())
        # is rolled back.
        # be careful with this!!!!!
205
        transaction.rollback()
206 207 208 209 210 211 212 213 214
        connection.close()
        session.remove()

    request.addfinalizer(teardown)
    return session


@pytest.fixture
def test_client(app):
215 216 217 218 219 220 221 222 223

    # flask.g is persisted in requests, and the werkzeug
    # CSRF checker could fail if we don't do this
    from flask import g
    try:
        del g.csrf_token
    except:
        pass

224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
    return app.test_client()


def create_user(app, session, username, email, password, **kwargs):
    user = app.user_datastore.create_user(username=username,
                                          email=email,
                                          password=password,
                                          **kwargs)
    session.add(user)
    session.commit()
    return user


@pytest.fixture
def user(app, database, session):
    # print 'user', id(session), session
    return create_user(app, session, 'test', 'user@test.com', 'password',
                       is_ldap=False)


@pytest.fixture
def ldap_user(app, session):
    return create_user(app, session, 'ldap', 'ldap@test.com', 'password',
                       is_ldap=True)


@pytest.fixture
def host_with_hostnames(host, hostname_factory):
    hostname_factory.create_batch(3, workspace=host.workspace, host=host)
    return host


def login_as(test_client, user):
    with test_client.session_transaction() as sess:
        # Without this line the test breaks. Taken from
        # http://pythonhosted.org/Flask-Testing/#testing-with-sqlalchemy
        assert user.id is not None
        db.session.add(user)
        sess['user_id'] = user.id
        identity_changed.send(test_client.application,
                              identity=Identity(user.id))


@pytest.fixture
def logged_user(test_client, user):
    login_as(test_client, user)
    return user


@pytest.fixture
def ignore_nplusone(app):
    old = app.config['NPLUSONE_RAISE']
    app.config['NPLUSONE_RAISE'] = False
    yield
    app.config['NPLUSONE_RAISE'] = old
279 280 281 282 283 284


@pytest.fixture
def csrf_token(logged_user, test_client):
    session_response = test_client.get('/session')
    return session_response.json.get('csrf_token')