Example #1
0
    def setUp(self):
        from wsgi import container

        self.container = container
        self._with_subdomains = False

        self.acting_user = False
        self.factory = Factory()
        self.withoutExceptionHandling()
        self.withoutCsrf()
        if not self._transaction:
            self.startTransaction()
            if hasattr(self, "setUpFactories"):
                self.setUpFactories()

        if self.sqlite and env("DB_CONNECTION") != "sqlite":
            raise Exception(
                "Cannot run tests without using the 'sqlite' database.")

        if not self.transactions and self.refreshes_database:
            self.refreshDatabase()

        self.route_middleware = False
        self.http_middleware = False
        self.headers = {}
Example #2
0
    def setUp(self):
        with self.schema().create("users") as table:
            table.increments("id")
            table.string("name").unique()
            table.string("email").unique()
            table.boolean("admin").default(True)
            table.timestamps()

        with self.schema().create("posts") as table:
            table.increments("id")
            table.integer("user_id")
            table.string("title").unique()
            table.text("content").unique()
            table.timestamps()

            table.foreign("user_id").references("id").on("users")

        self.factory = Factory()

        @self.factory.define(User)
        def users_factory(faker):
            return {"name": faker.name(), "email": faker.email(), "admin": False}

        @self.factory.define(User, "admin")
        def users_factory(faker):
            attributes = self.factory.raw(User)

            attributes.update({"admin": True})

            return attributes

        @self.factory.define(Post)
        def posts_factory(faker):
            return {"title": faker.sentence(), "content": faker.text()}
Example #3
0
    def setUp(self):
        from wsgi import container
        self.container = container
        self.acting_user = False
        self.factory = Factory()
        self.withoutExceptionHandling()
        self.withoutCsrf()
        if not self._transaction:
            self.startTransaction()
            if hasattr(self, 'setUpFactories'):
                self.setUpFactories()

        if self.sqlite and env('DB_CONNECTION') != 'sqlite':
            raise Exception("Cannot run tests without using the 'sqlite' database.")

        if not self.transactions and self.refreshes_database:
            self.refreshDatabase()
Example #4
0
    def setUp(self):
        with self.schema().create('users') as table:
            table.increments('id')
            table.string('name').unique()
            table.string('email').unique()
            table.boolean('admin').default(True)
            table.timestamps()

        with self.schema().create('posts') as table:
            table.increments('id')
            table.integer('user_id')
            table.string('title').unique()
            table.text('content').unique()
            table.timestamps()

            table.foreign('user_id').references('id').on('users')

        self.factory = Factory()

        @self.factory.define(User)
        def users_factory(faker):
            return {
                'name': faker.name(),
                'email': faker.email(),
                'admin': False
            }

        @self.factory.define(User, 'admin')
        def users_factory(faker):
            attributes = self.factory.raw(User)

            attributes.update({'admin': True})

            return attributes

        @self.factory.define(Post)
        def posts_factory(faker):
            return {
                'title': faker.sentence(),
                'content': faker.text()
            }
Example #5
0
    def setUp(self):
        with self.schema().create('users') as table:
            table.increments('id')
            table.string('name').unique()
            table.string('email').unique()
            table.boolean('admin').default(True)
            table.timestamps()

        with self.schema().create('posts') as table:
            table.increments('id')
            table.integer('user_id')
            table.string('title').unique()
            table.text('content').unique()
            table.timestamps()

            table.foreign('user_id').references('id').on('users')

        self.factory = Factory()

        @self.factory.define(User)
        def users_factory(faker):
            return {
                'name': faker.name(),
                'email': faker.email(),
                'admin': False
            }

        @self.factory.define(User, 'admin')
        def users_factory(faker):
            attributes = self.factory.raw(User)

            attributes.update({'admin': True})

            return attributes

        @self.factory.define(Post)
        def posts_factory(faker):
            return {
                'title': faker.sentence(),
                'content': faker.text()
            }
Example #6
0
class FactoryTestCase(OratorTestCase):

    @classmethod
    def setUpClass(cls):
        Model.set_connection_resolver(DatabaseConnectionResolver())

    @classmethod
    def tearDownClass(cls):
        Model.unset_connection_resolver()

    def connection(self):
        return Model.get_connection_resolver().connection()

    def schema(self):
        return self.connection().get_schema_builder()

    def setUp(self):
        with self.schema().create('users') as table:
            table.increments('id')
            table.string('name').unique()
            table.string('email').unique()
            table.boolean('admin').default(True)
            table.timestamps()

        with self.schema().create('posts') as table:
            table.increments('id')
            table.integer('user_id')
            table.string('title').unique()
            table.text('content').unique()
            table.timestamps()

            table.foreign('user_id').references('id').on('users')

        self.factory = Factory()

        @self.factory.define(User)
        def users_factory(faker):
            return {
                'name': faker.name(),
                'email': faker.email(),
                'admin': False
            }

        @self.factory.define(User, 'admin')
        def users_factory(faker):
            attributes = self.factory.raw(User)

            attributes.update({'admin': True})

            return attributes

        @self.factory.define(Post)
        def posts_factory(faker):
            return {
                'title': faker.sentence(),
                'content': faker.text()
            }

    def tearDown(self):
        self.schema().drop('posts')
        self.schema().drop('users')

    def test_factory_make(self):
        user = self.factory.make(User)

        self.assertIsInstance(user, User)
        self.assertIsNotNone(user.name)
        self.assertIsNotNone(user.email)
        self.assertIsNone(User.where('name', user.name).first())

    def test_factory_create(self):
        user = self.factory.create(User)

        self.assertIsInstance(user, User)
        self.assertIsNotNone(user.name)
        self.assertIsNotNone(user.email)
        self.assertIsNotNone(User.where('name', user.name).first())

    def test_factory_create_with_attributes(self):
        user = self.factory.create(User, name='foo', email='*****@*****.**')

        self.assertIsInstance(user, User)
        self.assertEqual('foo', user.name)
        self.assertEqual('*****@*****.**', user.email)
        self.assertIsNotNone(User.where('name', user.name).first())

    def test_factory_create_with_relations(self):
        users = self.factory.build(User, 3)
        users = users.create().each(lambda u: u.posts().save(self.factory.make(Post)))

        self.assertEqual(3, len(users))
        self.assertIsInstance(users[0], User)
        self.assertEqual(3, User.count())
        self.assertEqual(3, Post.count())

    def test_factory_call(self):
        user = self.factory(User).create()
        self.assertFalse(user.admin)

        users = self.factory(User, 3).create()

        self.assertEqual(3, len(users))
        self.assertFalse(users[0].admin)

        admin = self.factory(User, 'admin').create()
        self.assertTrue(admin.admin)

        admins = self.factory(User, 'admin', 3).create()
        self.assertEqual(3, len(admins))
        self.assertTrue(admins[0].admin)
Example #7
0
from orator.orm import Factory
from app.User import User
from app.Car import Car
from app.Customer import Customer
from app.Engine import Engine
from app.ServiceHistory import ServiceHistory

factory = Factory()


def users_factory(faker):
    return {
        "name": faker.name(),
        "email": faker.email(),
        "password":
        "******",  # == 'secret'
    }


def customers_factory(faker):
    return {}


def cars_factory(faker):
    return {
        "make": faker.name(),
        "model": faker.company(),
        "year": faker.pyint(),
        "color": faker.safe_color_name(),
        "engine": faker.catch_phrase(),
        "mileage": faker.pyint(min_value=10, max_value=200000),
Example #8
0
class FactoryTestCase(OratorTestCase):
    @classmethod
    def setUpClass(cls):
        Model.set_connection_resolver(DatabaseConnectionResolver())

    @classmethod
    def tearDownClass(cls):
        Model.unset_connection_resolver()

    def connection(self):
        return Model.get_connection_resolver().connection()

    def schema(self):
        return self.connection().get_schema_builder()

    def setUp(self):
        with self.schema().create("users") as table:
            table.increments("id")
            table.string("name").unique()
            table.string("email").unique()
            table.boolean("admin").default(True)
            table.timestamps()

        with self.schema().create("posts") as table:
            table.increments("id")
            table.integer("user_id")
            table.string("title").unique()
            table.text("content").unique()
            table.timestamps()

            table.foreign("user_id").references("id").on("users")

        self.factory = Factory()

        @self.factory.define(User)
        def users_factory(faker):
            return {"name": faker.name(), "email": faker.email(), "admin": False}

        @self.factory.define(User, "admin")
        def users_factory(faker):
            attributes = self.factory.raw(User)

            attributes.update({"admin": True})

            return attributes

        @self.factory.define(Post)
        def posts_factory(faker):
            return {"title": faker.sentence(), "content": faker.text()}

    def tearDown(self):
        self.schema().drop("posts")
        self.schema().drop("users")

    def test_factory_make(self):
        user = self.factory.make(User)

        self.assertIsInstance(user, User)
        self.assertIsNotNone(user.name)
        self.assertIsNotNone(user.email)
        self.assertIsNone(User.where("name", user.name).first())

    def test_factory_create(self):
        user = self.factory.create(User)

        self.assertIsInstance(user, User)
        self.assertIsNotNone(user.name)
        self.assertIsNotNone(user.email)
        self.assertIsNotNone(User.where("name", user.name).first())

    def test_factory_create_with_attributes(self):
        user = self.factory.create(User, name="foo", email="*****@*****.**")

        self.assertIsInstance(user, User)
        self.assertEqual("foo", user.name)
        self.assertEqual("*****@*****.**", user.email)
        self.assertIsNotNone(User.where("name", user.name).first())

    def test_factory_create_with_relations(self):
        users = self.factory.build(User, 3)
        users = users.create().each(lambda u: u.posts().save(self.factory.make(Post)))

        self.assertEqual(3, len(users))
        self.assertIsInstance(users[0], User)
        self.assertEqual(3, User.count())
        self.assertEqual(3, Post.count())

    def test_factory_call(self):
        user = self.factory(User).create()
        self.assertFalse(user.admin)

        users = self.factory(User, 3).create()

        self.assertEqual(3, len(users))
        self.assertFalse(users[0].admin)

        admin = self.factory(User, "admin").create()
        self.assertTrue(admin.admin)

        admins = self.factory(User, "admin", 3).create()
        self.assertEqual(3, len(admins))
        self.assertTrue(admins[0].admin)
Example #9
0
from orator.orm import Factory
from src.models.user import User
from src.models.chat import Chat

factory = Factory()


@factory.define(User)
def users_factory(fake):
    return {
        'id': fake.random_int(),
        'name': fake.name(),
        'chat_id': fake.random_int(),
        'lang': '-',
        'status': 1,
        'gender': 'M',
    }


@factory.define(Chat)
def chats_factory(fake):
    return {
        'started_at': None,
    }
Example #10
0
from orator.orm import Factory
from app.User import User
from app.Member import Member

factory = Factory()


def users_factory(faker):
    return {
        'name': faker.name(),
        'email': faker.email(),
        'password': '******',  # == 'secret'
    }


def members_factory(faker):
    return {
        'full_name': faker.name(),
        'position': faker.job(),
        'image_url': 'uploads/temp_team.jpg'
        }

factory.register(User, users_factory)
factory.register(Member, members_factory)
Example #11
0
"""Factories that returns dummy data."""
from orator.orm import Factory

from app.Entry import Entry
from app.User import User

factory = Factory()


def users_factory(faker):
    """Return Fake user."""
    return {
        "name": faker.name(),
        "email": faker.email(),
        "password": "******",  # == 'secret'
    }


def entries_factory(faker):
    """Return Fake Entry."""

    import random

    author_ids = [user.id for user in User.select("id").get()]

    entry_date = faker.date_between(start_date="-30d", end_date="today")
    return {
        "note": faker.sentence(nb_words=6),
        "rating": faker.random_int(min=-2, max=2),
        "entry_for_date": entry_date,
        "author_id": random.randint(1, len(author_ids)),
Example #12
0
from orator.orm import Factory
from app.User import User
from app.Project import Project
import random

factory = Factory()


def users_factory(faker):
    return {
        'name': faker.name(),
        'email': faker.email(),
        'password': '******',  # == 'secret'
    }


def project_factory(faker):
    return {
        'name': faker.company(),
        'description': faker.paragraph(),
        'manager_id': random.randint(1, 50)
    }


factory.register(User, users_factory)
factory.register(Project, project_factory)
Example #13
0
from orator.orm import Factory
from app.User import User
from app.Country import Country

from random import randrange
factory = Factory()


def users_factory(faker):
    return {
        'name': faker.name(),
        'email': faker.email(),
        'password':
        '******',  # == 'secret'
    }


def countries_factory(faker):
    return {
        'name': faker.country(),
        'case_number': randrange(1, 100),
        'case_death': randrange(1, 100),
        'case_recovered': randrange(1, 100)
    }


factory.register(User, users_factory)
factory.register(Country, countries_factory)
Example #14
0
class TestCase(unittest.TestCase):

    sqlite = True
    transactions = True
    refreshes_database = False
    _transaction = False
    _with_subdomains = False

    def setUp(self):
        from wsgi import container
        self.container = container
        self.acting_user = False
        self.factory = Factory()
        self.withoutExceptionHandling()
        self.withoutCsrf()
        if not self._transaction:
            self.startTransaction()
            if hasattr(self, 'setUpFactories'):
                self.setUpFactories()

        if self.sqlite and env('DB_CONNECTION') != 'sqlite':
            raise Exception("Cannot run tests without using the 'sqlite' database.")

        if not self.transactions and self.refreshes_database:
            self.refreshDatabase()

    @classmethod
    def setUpClass(cls):
        cls.staticSetUpDatabase()

    @classmethod
    def tearDownClass(cls):
        if not cls.refreshes_database and cls.transactions:
            cls.staticStopTransaction()
        else:
            cls.staticTearDownDatabase()

    def refreshDatabase(self):
        if not self.refreshes_database and self.transactions:
            self.stopTransaction()
            self.startTransaction()
            if hasattr(self, 'setUpFactories'):
                self.setUpFactories()
        else:
            self.tearDownDatabase()
            self.setUpDatabase()

    def startTransaction(self):
        from config.database import DB
        DB.begin_transaction()
        self.__class__._transaction = True

    def stopTransaction(self):
        from config.database import DB
        DB.rollback()
        self.__class__._transaction = False

    @classmethod
    def staticStopTransaction(cls):
        from config.database import DB
        DB.rollback()
        cls._transaction = False

    def make(self, model, factory, amount=50):
        self.registerFactory(model, factory)
        self.makeFactory(model, amount)

    def makeFactory(self, model, amount):
        return self.factory(model, amount).create()

    def registerFactory(self, model, callable_factory):
        self.factory.register(model, callable_factory)

    def setUpDatabase(self):
        self.tearDownDatabase()
        Migrations().run()
        if hasattr(self, 'setUpFactories'):
            self.setUpFactories()

    def tearDownDatabase(self):
        Migrations().reset()

    @staticmethod
    def staticSetUpDatabase():
        Migrations().run()

    @staticmethod
    def staticTearDownDatabase():
        Migrations().reset()

    def tearDown(self):
        if not self.transactions and self.refreshes_database:
            self.tearDownDatabase()

        if self.container.has('Request'):
            self.container.make('Request').get_and_reset_headers()

    def call(self, method, url, params, wsgi={}):
        custom_wsgi = {
            'PATH_INFO': url,
            'REQUEST_METHOD': method
        }

        custom_wsgi.update(wsgi)
        if not self._with_csrf:
            params.update({'__token': 'tok'})
            custom_wsgi.update({
                'HTTP_COOKIE': 'csrf_token=tok',
                'CONTENT_LENGTH': len(str(json.dumps(params))),
                'wsgi.input': io.BytesIO(bytes(json.dumps(params), 'utf-8')),
            })

        custom_wsgi.update({
            'QUERY_STRING': urlencode(params),
        })

        self.run_container(custom_wsgi)
        self.container.make('Request').request_variables = params
        return self.route(url, method)

    def get(self, url, params={}, wsgi={}):
        return self.call('GET', url, params, wsgi=wsgi)

    def withSubdomains(self):
        self._with_subdomains = True
        return self

    def json(self, method, url, params={}):
        return self.call(method, url, params, wsgi={
            'CONTENT_TYPE': 'application/json',
            'CONTENT_LENGTH': len(str(json.dumps(params))),
            'wsgi.input': io.BytesIO(bytes(json.dumps(params), 'utf-8')),
        })

    def post(self, url, params={}):
        return self.call('POST', url, params)

    def put(self, url, params={}):
        return self.json('PUT', url, params)

    def patch(self, url, params={}):
        return self.json('PATCH', url, params)

    def delete(self, url, params={}):
        return self.json('DELETE', url, params)

    def actingAs(self, user):
        if not user:
            raise TypeError("Cannot act as a user of type: {}".format(type(user)))
        self.acting_user = user
        return self

    def route(self, url, method=False):
        for route in self.container.make('WebRoutes'):
            matchurl = create_matchurl(url, route)
            if self.container.make('Request').has_subdomain():
                # Check if the subdomain matches the correct routes domain
                if not route.has_required_domain():
                    continue

            if matchurl.match(url) and method in route.method_type:
                return MockRoute(route, self.container)

        raise RouteNotFoundException("Could not find a route based on the url '{}'".format(url))

    def routes(self, routes=[], only=False):
        if only:
            self.container.bind('WebRoutes', flatten_routes(only))
            return

        self.container.bind('WebRoutes', flatten_routes(self.container.make('WebRoutes') + routes))

    @contextmanager
    def captureOutput(self):
        new_out, new_err = io.StringIO(), io.StringIO()
        old_out, old_err = sys.stdout, sys.stderr
        try:
            sys.stdout, sys.stderr = new_out, new_err
            yield sys.stdout
        finally:
            sys.stdout, sys.stderr = old_out, old_err

    def run_container(self, wsgi_values={}):
        wsgi = generate_wsgi()
        wsgi.update(wsgi_values)
        # self.container.make('Request').activate_subdomains()
        self.container.bind('Environ', wsgi)
        self.container.make('Request')._test_user = self.acting_user
        if self._with_subdomains:
            self.container.make('Request').activate_subdomains()
        try:
            for provider in self.container.make('WSGIProviders'):
                self.container.resolve(provider.boot)
        except Exception as e:
            if self._exception_handling:
                self.container.make('ExceptionHandler').load_exception(e)
            else:
                raise e

    def withExceptionHandling(self):
        self._exception_handling = True

    def withoutExceptionHandling(self):
        self._exception_handling = False

    def withCsrf(self):
        self._with_csrf = True

    def withoutCsrf(self):
        self._with_csrf = False

    def assertDatabaseHas(self, schema, value):
        from config.database import DB

        table = schema.split('.')[0]
        column = schema.split('.')[1]

        self.assertTrue(DB.table(table).where(column, value).first())

    def assertDatabaseNotHas(self, schema, value):
        from config.database import DB

        table = schema.split('.')[0]
        column = schema.split('.')[1]

        self.assertFalse(DB.table(table).where(column, value).first())

    def on_bind(self, obj, method):
        self.container.on_bind(obj, method)
        return self
Example #15
0
class TestCase(unittest.TestCase):

    sqlite = True
    transactions = True
    refreshes_database = False
    _transaction = False
    _with_subdomains = False

    def setUp(self):
        from wsgi import container
        self.container = container

        self.acting_user = False
        self.factory = Factory()
        self.withoutExceptionHandling()
        self.withoutCsrf()
        if not self._transaction:
            self.startTransaction()
            if hasattr(self, 'setUpFactories'):
                self.setUpFactories()

        if self.sqlite and env('DB_CONNECTION') != 'sqlite':
            raise Exception("Cannot run tests without using the 'sqlite' database.")

        if not self.transactions and self.refreshes_database:
            self.refreshDatabase()

        self.route_middleware = False
        self.http_middleware = False

    def buildOwnContainer(self):
        self.container = self.create_container()
        return self

    @classmethod
    def setUpClass(cls):
        cls.staticSetUpDatabase()

    @classmethod
    def tearDownClass(cls):
        if not cls.refreshes_database and cls.transactions:
            cls.staticStopTransaction()
        else:
            cls.staticTearDownDatabase()

    def refreshDatabase(self):
        if not self.refreshes_database and self.transactions:
            self.stopTransaction()
            self.startTransaction()
            if hasattr(self, 'setUpFactories'):
                self.setUpFactories()
        else:
            self.tearDownDatabase()
            self.setUpDatabase()

    def startTransaction(self):
        from config.database import DB
        DB.begin_transaction()
        self.__class__._transaction = True

    def stopTransaction(self):
        from config.database import DB
        DB.rollback()
        self.__class__._transaction = False

    @classmethod
    def staticStopTransaction(cls):
        from config.database import DB
        DB.rollback()
        cls._transaction = False

    def make(self, model, factory, amount=50):
        self.registerFactory(model, factory)
        self.makeFactory(model, amount)

    def makeFactory(self, model, amount):
        return self.factory(model, amount).create()

    def registerFactory(self, model, callable_factory):
        self.factory.register(model, callable_factory)

    def setUpDatabase(self):
        self.tearDownDatabase()
        Migrations().run()
        if hasattr(self, 'setUpFactories'):
            self.setUpFactories()

    def tearDownDatabase(self):
        Migrations().reset()

    @staticmethod
    def staticSetUpDatabase():
        Migrations().run()

    @staticmethod
    def staticTearDownDatabase():
        Migrations().reset()

    def tearDown(self):
        if not self.transactions and self.refreshes_database:
            self.tearDownDatabase()

        if self.container.has('Request'):
            self.container.make('Request').get_and_reset_headers()

    def call(self, method, url, params, wsgi={}):
        custom_wsgi = {
            'PATH_INFO': url,
            'REQUEST_METHOD': method
        }

        custom_wsgi.update(wsgi)
        if not self._with_csrf:
            params.update({'__token': 'tok'})
            custom_wsgi.update({
                'HTTP_COOKIE': 'csrf_token=tok',
                'CONTENT_LENGTH': len(str(json.dumps(params))),
                'wsgi.input': io.BytesIO(bytes(json.dumps(params), 'utf-8')),
            })

        custom_wsgi.update({
            'QUERY_STRING': urlencode(params),
        })

        self.run_container(custom_wsgi)
        self.container.make('Request').request_variables = params
        return self.route(url, method)

    def get(self, url, params={}, wsgi={}):
        return self.call('GET', url, params, wsgi=wsgi)

    def withSubdomains(self):
        self._with_subdomains = True
        return self

    def json(self, method, url, params={}):
        return self.call(method, url, params, wsgi={
            'CONTENT_TYPE': 'application/json',
            'CONTENT_LENGTH': len(str(json.dumps(params))),
            'wsgi.input': io.BytesIO(bytes(json.dumps(params), 'utf-8')),
        })

    def post(self, url, params={}):
        return self.call('POST', url, params)

    def put(self, url, params={}):
        return self.json('PUT', url, params)

    def patch(self, url, params={}):
        return self.json('PATCH', url, params)

    def delete(self, url, params={}):
        return self.json('DELETE', url, params)

    def actingAs(self, user):
        if not user:
            raise TypeError("Cannot act as a user of type: {}".format(type(user)))
        self.acting_user = user
        return self

    def route(self, url, method=False):
        for route in self.container.make('WebRoutes'):
            matchurl = create_matchurl(url, route)
            if self.container.make('Request').has_subdomain():
                # Check if the subdomain matches the correct routes domain
                if not route.has_required_domain():
                    continue

            if matchurl.match(url) and method in route.method_type:
                return MockRoute(route, self.container)

        raise RouteNotFoundException("Could not find a route based on the url '{}'".format(url))

    def routes(self, routes=[], only=False):
        if only:
            self.container.bind('WebRoutes', flatten_routes(only))
            return

        self.container.bind('WebRoutes', flatten_routes(self.container.make('WebRoutes') + routes))

    @contextmanager
    def captureOutput(self):
        new_out, new_err = io.StringIO(), io.StringIO()
        old_out, old_err = sys.stdout, sys.stderr
        try:
            sys.stdout, sys.stderr = new_out, new_err
            yield sys.stdout
        finally:
            sys.stdout, sys.stderr = old_out, old_err

    def run_container(self, wsgi_values={}):
        wsgi = generate_wsgi()
        wsgi.update(wsgi_values)
        self.container.bind('Environ', wsgi)
        self.container.make('Request')._test_user = self.acting_user
        self.container.make('Request').load_app(self.container)
        if self._with_subdomains:
            self.container.make('Request').activate_subdomains()

        if self.route_middleware is not False:
            print('bind new middleware', self.route_middleware)
            self.container.bind('RouteMiddleware', self.route_middleware)

        if self.http_middleware is not False:
            self.container.bind('HttpMiddleware', self.http_middleware)

        try:
            for provider in self.container.make('WSGIProviders'):
                self.container.resolve(provider.boot)
        except Exception as e:
            if self._exception_handling:
                self.container.make('ExceptionHandler').load_exception(e)
            else:
                raise e

    def withExceptionHandling(self):
        self._exception_handling = True

    def withoutExceptionHandling(self):
        self._exception_handling = False

    def withCsrf(self):
        self._with_csrf = True
        return self

    def withoutCsrf(self):
        self._with_csrf = False
        return self

    def assertDatabaseHas(self, schema, value):
        from config.database import DB

        table = schema.split('.')[0]
        column = schema.split('.')[1]

        self.assertTrue(DB.table(table).where(column, value).first())

    def assertDatabaseNotHas(self, schema, value):
        from config.database import DB

        table = schema.split('.')[0]
        column = schema.split('.')[1]

        self.assertFalse(DB.table(table).where(column, value).first())

    def on_bind(self, obj, method):
        self.container.on_bind(obj, method)
        return self

    def withRouteMiddleware(self, middleware):
        self.route_middleware = middleware
        return self

    def withHttpMiddleware(self, middleware):
        self.http_middleware = middleware
        return self

    def withoutHttpMiddleware(self):
        self.http_middleware = []
        return self

    def create_container(self):
        container = App()
        from config import application
        from config import providers

        container.bind('WSGI', generate_wsgi())
        container.bind('Application', application)
        container.bind('Container', container)

        container.bind('ProvidersConfig', providers)
        container.bind('Providers', [])
        container.bind('WSGIProviders', [])

        """Bind all service providers
        Let's register everything into the Service Container. Once everything is
        in the container we can run through all the boot methods. For reasons
        some providers don't need to execute with every request and should
        only run once when the server is started. Providers will be ran
        once if the wsgi attribute on a provider is False.
        """

        for provider in container.make('ProvidersConfig').PROVIDERS:
            located_provider = provider()
            located_provider.load_app(container).register()
            if located_provider.wsgi:
                container.make('WSGIProviders').append(located_provider)
            else:
                container.make('Providers').append(located_provider)

        for provider in container.make('Providers'):
            container.resolve(provider.boot)

        """Get the application from the container
        Some providers may change the WSGI Server like wrapping the WSGI server
        in a Whitenoise container for an example. Let's get a WSGI instance
        from the container and pass it to the application variable. This
        will allow WSGI servers to pick it up from the command line
        """

        return container
Example #16
0
class FactoryTestCase(OratorTestCase):
    @classmethod
    def setUpClass(cls):
        Model.set_connection_resolver(DatabaseConnectionResolver())

    @classmethod
    def tearDownClass(cls):
        Model.unset_connection_resolver()

    def connection(self):
        return Model.get_connection_resolver().connection()

    def schema(self):
        return self.connection().get_schema_builder()

    def setUp(self):
        with self.schema().create('users') as table:
            table.increments('id')
            table.string('name').unique()
            table.string('email').unique()
            table.boolean('admin').default(True)
            table.timestamps()

        with self.schema().create('posts') as table:
            table.increments('id')
            table.integer('user_id')
            table.string('title').unique()
            table.text('content').unique()
            table.timestamps()

            table.foreign('user_id').references('id').on('users')

        self.factory = Factory()

        @self.factory.define(User)
        def users_factory(faker):
            return {
                'name': faker.name(),
                'email': faker.email(),
                'admin': False
            }

        @self.factory.define(User, 'admin')
        def users_factory(faker):
            attributes = self.factory.raw(User)

            attributes.update({'admin': True})

            return attributes

        @self.factory.define(Post)
        def posts_factory(faker):
            return {'title': faker.sentence(), 'content': faker.text()}

    def tearDown(self):
        self.schema().drop('posts')
        self.schema().drop('users')

    def test_factory_make(self):
        user = self.factory.make(User)

        self.assertIsInstance(user, User)
        self.assertIsNotNone(user.name)
        self.assertIsNotNone(user.email)
        self.assertIsNone(User.where('name', user.name).first())

    def test_factory_create(self):
        user = self.factory.create(User)

        self.assertIsInstance(user, User)
        self.assertIsNotNone(user.name)
        self.assertIsNotNone(user.email)
        self.assertIsNotNone(User.where('name', user.name).first())

    def test_factory_create_with_attributes(self):
        user = self.factory.create(User, name='foo', email='*****@*****.**')

        self.assertIsInstance(user, User)
        self.assertEqual('foo', user.name)
        self.assertEqual('*****@*****.**', user.email)
        self.assertIsNotNone(User.where('name', user.name).first())

    def test_factory_create_with_relations(self):
        users = self.factory.build(User, 3)
        users = users.create().each(
            lambda u: u.posts().save(self.factory.make(Post)))

        self.assertEqual(3, len(users))
        self.assertIsInstance(users[0], User)
        self.assertEqual(3, User.count())
        self.assertEqual(3, Post.count())

    def test_factory_call(self):
        user = self.factory(User).create()
        self.assertFalse(user.admin)

        users = self.factory(User, 3).create()

        self.assertEqual(3, len(users))
        self.assertFalse(users[0].admin)

        admin = self.factory(User, 'admin').create()
        self.assertTrue(admin.admin)

        admins = self.factory(User, 'admin', 3).create()
        self.assertEqual(3, len(admins))
        self.assertTrue(admins[0].admin)
from orator.orm import Factory

from personalwebpageapi.models.post import Post
from personalwebpageapi.models.post_content import PostContent
from personalwebpageapi.models.auth import Auth

from tests.factories.post import post_factory, post_is_draft_factory
from tests.factories.post_content import post_content_factory
from tests.factories.auth import auth_factory

from functools import partial

factory = Factory()

# Post
factory.register(Post, post_factory)
factory.register_as(
    Post,
    'is_draft',
    partial(post_is_draft_factory, factory),
)

# PostContent
factory.register(PostContent, post_content_factory)

# Auth
factory.register(Auth, auth_factory)


__all__ = (
    'factory',
Example #18
0
class TestCase(unittest.TestCase):

    sqlite = True
    transactions = True
    refreshes_database = False
    _transaction = False

    def setUp(self):
        from wsgi import container

        self.container = container
        self._with_subdomains = False

        self.acting_user = False
        self.factory = Factory()
        self.withoutExceptionHandling()
        self.withoutCsrf()
        if not self._transaction:
            self.startTransaction()
            if hasattr(self, "setUpFactories"):
                self.setUpFactories()

        if self.sqlite and env("DB_CONNECTION") != "sqlite":
            raise Exception(
                "Cannot run tests without using the 'sqlite' database.")

        if not self.transactions and self.refreshes_database:
            self.refreshDatabase()

        self.route_middleware = False
        self.http_middleware = False
        self.headers = {}

    def buildOwnContainer(self):
        self.container = self.create_container()
        return self

    @classmethod
    def setUpClass(cls):
        cls.staticSetUpDatabase()

    @classmethod
    def tearDownClass(cls):
        if not cls.refreshes_database and cls.transactions:
            cls.staticStopTransaction()
        else:
            cls.staticTearDownDatabase()

    def refreshDatabase(self):
        if not self.refreshes_database and self.transactions:
            self.stopTransaction()
            self.startTransaction()
            if hasattr(self, "setUpFactories"):
                self.setUpFactories()
        else:
            self.tearDownDatabase()
            self.setUpDatabase()

    def startTransaction(self):
        from config.database import DB

        DB.begin_transaction()
        self.__class__._transaction = True

    def stopTransaction(self):
        from config.database import DB

        DB.rollback()
        self.__class__._transaction = False

    @classmethod
    def staticStopTransaction(cls):
        from config.database import DB

        DB.rollback()
        cls._transaction = False

    def make(self, model, factory, amount=50):
        self.registerFactory(model, factory)
        self.makeFactory(model, amount)

    def makeFactory(self, model, amount):
        return self.factory(model, amount).create()

    def registerFactory(self, model, callable_factory):
        self.factory.register(model, callable_factory)

    def setUpDatabase(self):
        self.tearDownDatabase()
        Migrations().run()
        if hasattr(self, "setUpFactories"):
            self.setUpFactories()

    def tearDownDatabase(self):
        Migrations().reset()

    @staticmethod
    def staticSetUpDatabase():
        Migrations().run()

    @staticmethod
    def staticTearDownDatabase():
        Migrations().reset()

    def tearDown(self):
        if not self.transactions and self.refreshes_database:
            self.tearDownDatabase()

        if self.container.has("Request"):
            self.container.make("Request").get_and_reset_headers()

    def call(self, method, url, params, wsgi={}):
        custom_wsgi = {"PATH_INFO": url, "REQUEST_METHOD": method}

        custom_wsgi.update(wsgi)
        if not self._with_csrf:
            params.update({"__token": "tok"})
            custom_wsgi.update({
                "HTTP_COOKIE":
                "csrf_token=tok",
                "CONTENT_LENGTH":
                len(str(json.dumps(params))),
                "wsgi.input":
                io.BytesIO(bytes(json.dumps(params), "utf-8")),
            })

        custom_wsgi.update({"QUERY_STRING": urlencode(params)})

        self.run_container(custom_wsgi)
        self.container.make("Request").request_variables = params
        return self.route(url, method)

    def get(self, url, params={}, wsgi={}):
        return self.call("GET", url, params, wsgi=wsgi)

    def withSubdomains(self):
        self._with_subdomains = True
        return self

    def json(self, method, url, params={}):
        return self.call(
            method,
            url,
            params,
            wsgi={
                "CONTENT_TYPE": "application/json",
                "CONTENT_LENGTH": len(str(json.dumps(params))),
                "wsgi.input": io.BytesIO(bytes(json.dumps(params), "utf-8")),
            },
        )

    def post(self, url, params={}):
        return self.call("POST", url, params)

    def put(self, url, params={}):
        return self.json("PUT", url, params)

    def patch(self, url, params={}):
        return self.json("PATCH", url, params)

    def delete(self, url, params={}):
        return self.json("DELETE", url, params)

    def actingAs(self, user):
        if not user:
            raise TypeError("Cannot act as a user of type: {}".format(
                type(user)))
        self.acting_user = user
        return self

    def route(self, url, method=False):
        for route in self.container.make("WebRoutes"):
            matchurl = create_matchurl(url, route)
            if self.container.make("Request").has_subdomain():
                # Check if the subdomain matches the correct routes domain
                if not route.has_required_domain():
                    continue

            if matchurl.match(url) and method in route.method_type:
                return MockRoute(route, self.container)

        raise RouteNotFoundException(
            "Could not find a route based on the url '{}'".format(url))

    def routes(self, routes=[], only=False):
        if only:
            self.container.bind("WebRoutes", flatten_routes(only))
            return

        self.container.bind(
            "WebRoutes",
            flatten_routes(self.container.make("WebRoutes") + routes))

    @contextmanager
    def captureOutput(self):
        new_out, new_err = io.StringIO(), io.StringIO()
        old_out, old_err = sys.stdout, sys.stderr
        try:
            sys.stdout, sys.stderr = new_out, new_err
            yield sys.stdout
        finally:
            sys.stdout, sys.stderr = old_out, old_err

    def run_container(self, wsgi_values={}):
        wsgi = generate_wsgi()
        wsgi.update(wsgi_values)
        self.container.bind("Environ", wsgi)
        self.container.make("Request")._test_user = self.acting_user
        self.container.make("Request").load_app(
            self.container).load_environ(wsgi)
        if self._with_subdomains:
            self.container.make("Request").activate_subdomains()

        if self.headers:
            self.container.make("Request").header(self.headers)

        if self.route_middleware is not False:
            self.container.bind("RouteMiddleware", self.route_middleware)

        if self.http_middleware is not False:
            self.container.bind("HttpMiddleware", self.http_middleware)

        try:
            for provider in self.container.make("WSGIProviders"):
                self.container.resolve(provider.boot)
        except Exception as e:  # skipcq
            if self._exception_handling:
                self.container.make("ExceptionHandler").load_exception(e)
            else:
                raise e

    def withExceptionHandling(self):
        self._exception_handling = True

    def withoutExceptionHandling(self):
        self._exception_handling = False

    def withCsrf(self):
        self._with_csrf = True
        return self

    def withoutCsrf(self):
        self._with_csrf = False
        return self

    def assertDatabaseHas(self, schema, value):
        from config.database import DB

        table = schema.split(".")[0]
        column = schema.split(".")[1]

        self.assertTrue(DB.table(table).where(column, value).first())

    def assertDatabaseNotHas(self, schema, value):
        from config.database import DB

        table = schema.split(".")[0]
        column = schema.split(".")[1]

        self.assertFalse(DB.table(table).where(column, value).first())

    def on_bind(self, obj, method):
        self.container.on_bind(obj, method)
        return self

    def withRouteMiddleware(self, middleware):
        self.route_middleware = middleware
        return self

    def withHttpMiddleware(self, middleware):
        self.http_middleware = middleware
        return self

    def withHeaders(self, headers={}):
        self.headers = headers
        return self

    def withoutHttpMiddleware(self):
        self.http_middleware = []
        return self

    def create_container(self):
        return create_container()