Esempio n. 1
0
def create_fake_observations(link_count=3, start=DEFAULT_START, duration=60*3, node_count=None):
    """Create a set of fake observations in the database."""

    create_fake_links(link_count=link_count, node_count=node_count)

    # Disable auto-add to db for mixer
    mixer = Mixer(commit=False)

    # Extract ids
    link_ids = set(db.session.query(Link.id))

    # A set of observation times
    obs_times = []
    for minutes in range(0, duration, 15):
        obs_times.append(start + datetime.timedelta(minutes=minutes))

    # For each link, create some random observations
    obs = []
    for link_id in link_ids:
        for type_ in ObservationType:
            obs.extend(mixer.cycle(len(obs_times)).blend(
                Observation, type=type_, link_id=link_id,
                observed_at=(t for t in obs_times)))
    log.info('Adding {0} observation(s) to database'.format(len(obs)))
    # For bulk inserts, the following is more efficient than, e.g.,
    # db.session.add_all(obs)
    obs_values = list(
        {
            'value': o.value, 'type': o.type,
            'observed_at': o.observed_at, 'link_id': o.link_id,
        }
        for o in obs
    )
    db.session.execute(Observation.__table__.insert(obs_values))
Esempio n. 2
0
def create_fake_links(link_count=3, node_count=None):
    # Default node count
    node_count = node_count or max(4, (link_count >> 1))

    # min lng, max lng, min lat, max lat
    bb = (-6.0, 1.5, 49.96, 60.8)

    # Generate random nodes
    nodes = []
    for _ in range(node_count):
        lng = bb[0] + random.random() * (bb[1] - bb[0])
        lat = bb[2] + random.random() * (bb[3] - bb[2])
        nodes.append((lng, lat))

    # Generate random link geometries
    def link_geoms():
        while True:
            a_idx, b_idx = None, None
            while a_idx == b_idx:
                a_idx, b_idx = random.sample(range(node_count), 2)
            a, b = tuple(nodes[i] for i in (a_idx, b_idx))
            yield 'SRID=4326;LINESTRING({0[0]} {0[1]}, {1[0]} {1[1]})'.format(a,b)

    # Disable auto-add to db for mixer
    mixer = Mixer(commit=False)

    # Create some random links
    links = mixer.cycle(link_count).blend(Link, geom=link_geoms)

    # For bulk inserts, the following is more efficient than, e.g.,
    # db.session.add_all(links)
    link_values = list({'uuid': l.uuid, 'geom': l.geom} for l in links)
    db.session.execute(Link.__table__.insert(link_values))
Esempio n. 3
0
def create_fake_link_aliases(alias_count=10):
    """Create a set of fake aliases for links.

    Requires a set of links in the database to exist.

    """
    # Disable auto-add to db for mixer
    mixer = Mixer(commit=False)

    # Extract link ids
    link_ids = set(db.session.query(Link.id))

    aliases = mixer.cycle(alias_count).blend(LinkAlias,
        name=mxfake.gen_slug(), link=None,
        link_id=mxgen.gen_choice(list(link_ids)))
    log.info('Adding {0} aliases to db'.format(len(aliases)))

    # For bulk inserts, the following is more efficient than, e.g.,
    # db.session.add_all(aliases)
    alias_values = list({'name': a.name, 'link_id': a.link_id} for a in aliases)
    db.session.execute(LinkAlias.__table__.insert(alias_values))
Esempio n. 4
0
    def test_base(self):
        from mixer.backend.flask import Mixer

        mixer = Mixer(commit=True)
        mixer.init_app(self.app)

        with self.app.test_request_context():
            db.create_all()

            node = mixer.blend('tests.test_flask.Node')
            self.assertTrue(node.id)
            self.assertFalse(node.parent)

            role = mixer.blend('tests.test_flask.Role')
            self.assertTrue(role.user)
            self.assertEqual(role.user_id, role.user.id)

            user = mixer.blend(User)
            self.assertTrue(user.id)
            self.assertTrue(user.username)
            self.assertEqual(user.score, 50)
            self.assertTrue(user.created_at)
            self.assertTrue(user.profile)
            self.assertEqual(user.profile.user, user)

            user = mixer.blend(User, username='******')
            self.assertEqual(user.username, 'test')

            role = mixer.blend('tests.test_flask.Role', user__username='******')
            self.assertEqual(role.user.username, 'test2')

            users = User.query.all()
            role = mixer.blend('tests.test_flask.Role', user=mixer.SELECT)
            self.assertTrue(role.user in users)

            role = mixer.blend('tests.test_flask.Role', user=mixer.RANDOM)
            self.assertTrue(role.user)

            profile = mixer.blend('tests.test_flask.Profile')
            user = mixer.blend(User, profile=profile)
            self.assertEqual(user.profile, profile)

            user = mixer.blend(User, score=mixer.RANDOM)
            self.assertNotEqual(user.score, 50)

            user = mixer.blend(User, username=lambda: 'callable_value')
            self.assertEqual(user.username, 'callable_value')

            # m2m
            messages = mixer.cycle(3).blend(Message)
            user = mixer.blend(User, messages=messages)
            self.assertEqual(len(user.messages), 3)

            user = mixer.blend(User, messages=mixer.RANDOM)
            self.assertEqual(len(user.messages), 1)

            user = mixer.blend(User, messages__content='message_content')
            self.assertEqual(len(user.messages), 1)
            self.assertEqual(user.messages[0].content, 'message_content')
Esempio n. 5
0
from Bizness import models
from BiznessWeb import app, db
from mixer.backend.flask import Mixer
from flask.ext.bcrypt import Bcrypt


mixer = Mixer(locale='en_US', commit=False)
bcrypt = Bcrypt(app)


@mixer.middleware(models.User)
def encrypt_password(user):
    user.password = bcrypt.generate_password_hash('def4ult')
    return user


with app.app_context():
    db.drop_all()
    db.create_all()

    mixer.init_app(app)
    mixer.register(models.User, email_address=mixer.faker.email_address)

    for user in mixer.cycle(20).blend(models.User):
        print(u"{} {}: {}({})".format(user.first_name, user.last_name, user.email_address, user.password))
Esempio n. 6
0
    def test_base(self):
        from mixer.backend.flask import Mixer

        mixer = Mixer(commit=True)
        mixer.init_app(self.app)

        with self.app.test_request_context():
            db.create_all()

            node = mixer.blend('tests.test_flask.Node')
            self.assertTrue(node.id)
            self.assertFalse(node.parent)

            role = mixer.blend('tests.test_flask.Role')
            self.assertTrue(role.user)
            self.assertEqual(role.user_id, role.user.id)

            user = mixer.blend(User)
            self.assertTrue(user.id)
            self.assertTrue(user.username)
            self.assertEqual(user.score, 50)
            self.assertTrue(user.created_at)
            self.assertTrue(user.profile)
            self.assertEqual(user.profile.user, user)

            user = mixer.blend(User, username='******')
            self.assertEqual(user.username, 'test')

            role = mixer.blend(
                'tests.test_flask.Role', user__username='******')
            self.assertEqual(role.user.username, 'test2')

            users = User.query.all()
            role = mixer.blend('tests.test_flask.Role', user=mixer.SELECT)
            self.assertTrue(role.user in users)

            role = mixer.blend('tests.test_flask.Role', user=mixer.RANDOM)
            self.assertTrue(role.user)

            profile = mixer.blend('tests.test_flask.Profile')
            user = mixer.blend(User, profile=profile)
            self.assertEqual(user.profile, profile)

            user = mixer.blend(User, score=mixer.RANDOM)
            self.assertNotEqual(user.score, 50)

            user = mixer.blend(User, username=lambda: 'callable_value')
            self.assertEqual(user.username, 'callable_value')
Esempio n. 7
0
    def test_base(self):
        from mixer.backend.flask import Mixer

        mixer = Mixer(commit=True)
        mixer.init_app(self.app)

        with self.app.test_request_context():
            db.create_all()

            node = mixer.blend('tests.test_flask.Node')
            self.assertTrue(node.id)
            self.assertFalse(node.parent)

            role = mixer.blend('tests.test_flask.Role')
            self.assertTrue(role.user)
            self.assertEqual(role.user_id, role.user.id)

            user = mixer.blend(User)
            self.assertTrue(user.id)
            self.assertTrue(user.username)
            self.assertEqual(user.score, 50)
            self.assertTrue(user.created_at)
            self.assertTrue(user.profile)
            self.assertEqual(user.profile.user, user)

            user = mixer.blend(User, username='******')
            self.assertEqual(user.username, 'test')

            role = mixer.blend(
                'tests.test_flask.Role', user__username='******')
            self.assertEqual(role.user.username, 'test2')

            users = User.query.all()
            role = mixer.blend('tests.test_flask.Role', user=mixer.select)
            self.assertTrue(role.user in users)

            role = mixer.blend('tests.test_flask.Role', user=mixer.random)
            self.assertTrue(role.user)

            profile = mixer.blend('tests.test_flask.Profile')
            user = mixer.blend(User, profile=profile)
            self.assertEqual(user.profile, profile)

            user = mixer.blend(User, score=mixer.random)
            self.assertNotEqual(user.score, 50)

            user = mixer.blend(User, username=lambda: 'callable_value')
            self.assertEqual(user.username, 'callable_value')
Esempio n. 8
0
from random import randint
from Bizness import models
from BiznessWeb import app, db
from mixer.backend.flask import Mixer
from mixer.backend.sqlalchemy import GenFactory


def fake_active():
    return randint(0, 10) > 2


class MyFactory(GenFactory):
    fakers = GenFactory.fakers
    fakers[('active', bool)] = fake_active


mixer = Mixer(locale='en_US', commit=False, factory=MyFactory)

with app.app_context():
    db.drop_all()
    db.create_all()

    mixer.init_app(app)

    for user in mixer.cycle(20).blend(models.User):
        print("{} {}: {}".format(user.first_name, user.last_name, user.active))
Esempio n. 9
0
    job_types = ['Developer', 'QA Analyst', 'UX Designer']

    experience_levels = ['', 'Senior', 'Junior', 'Intern']

    def title(self):
        pattern = self.random_element(self.formats)
        return self.generator.parse(pattern)

    @classmethod
    def job_type(cls):
        return cls.random_element(cls.job_types)

    @classmethod
    def experience_level(cls):
        return cls.random_element(cls.experience_levels)


mixer = Mixer(locale='en_US', commit=False)

with app.app_context():
    db.drop_all()
    db.create_all()

    mixer.init_app(app)
    mixer.faker.add_provider(JobTitleProvider)
    mixer.faker.add_provider(FixedPhoneNumberProvider)
    mixer.register(models.User, phone_number=mixer.faker.phone_number)

    for user in mixer.cycle(20).blend(models.User):
        print("{} {}: {} {}".format(user.first_name, user.last_name, user.title, user.phone_number))
Esempio n. 10
0
def mixer(app, fake):
    mixer = Mixer(commit=True)
    mixer.init_app(app)

    mixer.register(
        Component, code=fake.slug, description=fake.sentence,
        datasheet_url=fake.uri
    )

    mixer.register(User, name=fake.name)
    mixer.register(Collection, name=fake.text)
    mixer.register(
        UserCollectionPermission, permission=fake.random_element(Permission)
    )

    return mixer
Esempio n. 11
0
def populate(count):
    mixer = Mixer(app)
    count = int(count)

    models = [Client, Contact]

    for model in models:
        mixer.cycle(count).blend(model)

    mixer.cycle(count).blend(Pet,
                             neutering=mixer.sequence(True, False, None),
                             gender=mixer.sequence('m', 'f'))

    pets = Pet.query.limit(count)
    clients = Client.query.limit(count)

    mixer.cycle(count).blend(
        Register,
        comment=mixer.RANDOM,
        old_owner=(client for client in clients),
        old_pet=(pet for pet in pets),
    )
    mixer.cycle(count).blend(Adoption,
                             status='in process',
                             new_owner=(client for client in clients),
                             new_pet=(pet for pet in pets))

    mixer.cycle(count).blend(Image, pet=(pet for pet in pets))
    mixer.cycle(count).blend(Image, client=(client for client in clients))

    clients = Client.query.all()
    mixer.cycle(len(clients)).blend(User,
                                    client=(client for client in clients))
Esempio n. 12
0
def test_base():
    from mixer.backend.flask import Mixer

    mixer = Mixer(commit=True)
    mixer.init_app(app)

    with app.test_request_context():
        db.create_all()

        node = mixer.blend('tests.test_flask.Node')
        assert node.id
        assert not node.parent

        role = mixer.blend('tests.test_flask.Role')
        assert role.user
        assert role.user_id == role.user.id

        user = mixer.blend(User)
        assert user.id
        assert user.username
        assert user.score == 50
        assert user.created_at
        assert user.profile
        assert user.profile.user == user

        user = mixer.blend(User, username='******')
        assert user.username == 'test'

        role = mixer.blend('tests.test_flask.Role', user__username='******')
        assert role.user.username == 'test2'

        users = User.query.all()
        role = mixer.blend('tests.test_flask.Role', user=mixer.SELECT)
        assert role.user in users

        role = mixer.blend('tests.test_flask.Role', user=mixer.RANDOM)
        assert role.user

        profile = mixer.blend('tests.test_flask.Profile')
        user = mixer.blend(User, profile=profile)
        assert user.profile == profile

        user = mixer.blend(User, score=mixer.RANDOM)
        assert user.score != 50

        user = mixer.blend(User, username=lambda: 'callable_value')
        assert user.username == 'callable_value'

        # m2m
        messages = mixer.cycle(3).blend(Message)
        user = mixer.blend(User, messages=messages)
        assert len(user.messages) == 3

        user = mixer.blend(User, messages=mixer.RANDOM)
        assert len(user.messages) == 1

        user = mixer.blend(User, messages__content='message_content')
        assert len(user.messages) == 1
        assert user.messages[0].content == 'message_content'