Ejemplo n.º 1
0
def person(locale=None):
    if locale is None:
        locales = _MIMESIS_LOCALES
    else:
        locales = [locale]
    p = mimesis.Person(locale=choice(locales))
    gender = choice(['Male'] * 20 + ['Female'] * 21 + ['Other'])

    g = mimesis.enums.Gender.MALE if gender.lower(
    ) == 'male' else mimesis.enums.Gender.FEMALE
    first = p.name(g)
    last = p.last_name(g)

    return {
        'first_name': first,
        'last_name': last,
        'name': first + ' ' + last,  # western
        'age': p.age(),
        'gender': gender,
        'id': p.identifier(),
        'occupation': p.occupation(),
        'telephone': p.telephone(),
        'title': p.title(g),
        'username': p.username(),
        'university': p.university(),
    }
Ejemplo n.º 2
0
def importToEmployee():
    try:
        dsnStr = cx_Oracle.makedsn("217.173.198.135", "1522", "orcltp")
        con = cx_Oracle.connect(user="******", password="******", dsn=dsnStr)
        num = int(input("How many rows should be entered? "))
        last_id = getLastID("employee")
        print("Fetching rows...")
        for x in range(num):
            y = mimesis.Person('en')
            name = y.first_name()
            surname = y.last_name()
            code = '#' + y.identifier(mask='###')
            position = y.occupation()
            phone = y.telephone()
            email = y.email(domains=['mail.com'])
            login = y.username()
            passwd = y.password()
            location_id = random.randint(1, getLastID("location"))
            query = "INSERT INTO employee (id_employee, name, surname, code, position, phone, email, location_id, " \
                    "login, password) VALUES (:1, :2, :3, :4, :5, :6, :7, :8, :9, :10) "
            cursor = con.cursor()
            last_id = last_id + 1
            cursor.execute(query, (last_id, name, surname, code, position,
                                   phone, email, location_id, login, passwd))
            print(query)
            cursor.close()
        con.commit()
        print("Rows added successfully")
    except cx_Oracle.Error as error:
        print("Error occurred:")
        print(error)
    consoleInput()
Ejemplo n.º 3
0
    def test_registration_false2(self, browser: "class Browser", capabilities, domain):
        """
        Проверка валидации:
        login: Короткое имя
        pass: короткий пороль
        confirm pass: Пароль отличный от поля pass

        """
        self.browser = browser
        string = f"{capabilities[1]}, версия {capabilities[0]['version']}"
        browser.data["name"] = f"{self._NAME} попытка регистрации на занятый логин браузер {capabilities[0]['browserName']} {string}"
        browser.setup_browser(capabilities[0]["browserName"], remote=True, desired_capabilities=capabilities[0])
        page = Personal(browser)
        page.open()
        browser.driver.set_window_size(1920, 1080)
        page.open_reg_form()
        password = mimesis.Person().password(length=12)
        page.registration(login="******", password=password, password_confirm=password)
        if not browser.debug:
            btn = page.registration_sumbit()
            btn.hover()
            btn.click()
            assert btn.visible(wait=5), ("Ошибка: Кнопка подтверждения регистрации пропала."
                                         "Вероятно регистрация с некоректными данными успешна")
            error = page.get_registration_error()
            assert 'Пользователь с логином "test" уже существует.' == error
Ejemplo n.º 4
0
def importToAsset():
    try:
        dsnStr = cx_Oracle.makedsn("217.173.198.135", "1522", "orcltp")
        con = cx_Oracle.connect(user="******", password="******", dsn=dsnStr)
        num = int(input("How many rows should be entered? "))
        last_id = getLastID("asset")
        print("Fetching rows...")
        for x in range(num):
            y = mimesis.Person('en')
            d = mimesis.Datetime()
            name = 'Personal Computer'
            model_id = random.randint(1, getLastID("model"))
            supplier_id = random.randint(1, getLastID("supplier"))
            price = y.identifier(mask="####")
            date_of_creation = d.date(start=2015, end=2021)
            date_of_purchase = d.date(start=2015, end=2021)
            serial = y.identifier(mask="######")
            query = "INSERT INTO asset (id_asset, name, model_id, supplier_id, price, date_of_creation, date_of_purchase, serial) VALUES (:1, :2, :3, :4, :5, :6, :7, :8)"
            cursor = con.cursor()
            last_id = last_id + 1
            cursor.execute(query, (last_id, name, model_id, supplier_id, price,
                                   date_of_creation, date_of_purchase, serial))
            print(query)
            cursor.close()
        con.commit()
        print("Rows added successfully")
    except cx_Oracle.Error as error:
        print("Error occurred:")
        print(error)
    consoleInput()
Ejemplo n.º 5
0
def importToSupplier():
    try:
        dsnStr = cx_Oracle.makedsn("217.173.198.135", "1522", "orcltp")
        con = cx_Oracle.connect(user="******", password="******", dsn=dsnStr)
        num = int(input("How many rows should be entered? "))
        last_id = getLastID("supplier")
        print("Fetching rows...")
        for x in range(num):
            a = mimesis.Address('en')
            p = mimesis.Person('en')
            b = mimesis.Business('en')
            address = a.city()
            name = b.company()
            print(name)
            contact_person = p.full_name()
            phone = p.telephone()
            email = p.email(domains=['mail.com'])
            query = "INSERT INTO supplier (id_supplier, address, name, contact_person, phone, email) VALUES  (:1, :2, " \
                    ":3, :4, :5, :6) "
            cursor = con.cursor()
            last_id = last_id + 1
            cursor.execute(
                query, (last_id, address, name, contact_person, phone, email))
            print(query)
            cursor.close()
        con.commit()
        print("Rows added successfully")
    except cx_Oracle.Error as error:
        print("Error occurred:")
        print(error)
    consoleInput()
def generate_email_list(num: int) -> (str, dict):
    """
    Generates an unleash-style list of emails for testing.

    :param num:
    :return:
    """
    first_email = mimesis.Person('en').email()
    email_list_string = first_email

    context = {"userId": first_email}

    for _ in range(num - 1):
        email_list_string += "," + mimesis.Person('en').email()

    return (email_list_string, context)
Ejemplo n.º 7
0
def new_schooluser() -> dict:
    """Generate data for fake school user

    :return: dictionary with personal data
    :rtype: dict
    """
    random.seed()
    _person = mimesis.Person(locales.RU)
    _person_ru = mimesis.builtins.RussiaSpecProvider()
    _date = mimesis.Datetime()
    _gender = random.choice((enums.Gender.MALE, enums.Gender.FEMALE))
    _username = _person.username('ld')
    return {
        'username': _username,
        'password': _username,
        'first_name': _person.name(_gender),
        'last_name': _person.surname(_gender),
        'patronymic_name': _person_ru.patronymic(_gender),
        'birth_date': _date.formatted_date(fmt='%Y-%m-%d',
                                           start=1990,
                                           end=2000),
        'email': _person.email(),
        'language': random.choice(LANGUAGES),
        'is_active': True,
        'is_staff': False,
        'is_superuser': False
    }
Ejemplo n.º 8
0
def create_company(save=False):
    company = edgewise.new_doc("Company")
    company.name = mimesis.Person("en").last_name() + " "\
        + mimesis.Business().company_type(abbr=True)
    company.country = "United States"
    if save:
        company.save()
    return company
Ejemplo n.º 9
0
async def get_user(user_id: int):
    fake_user = mimesis.Person()
    return {
        "user_id": user_id,
        "username": fake_user.username(),
        "firstname": fake_user.first_name(),
        "lastname": fake_user.last_name(),
    }
Ejemplo n.º 10
0
    def populate(count=100) -> Generator['People', None, None]:
        import mimesis

        person = mimesis.Person()

        return (People(id=int(person.identifier('####')),
                       first_name=person.name(),
                       last_name=person.surname(),
                       twitter=person.username()) for _ in range(count))
Ejemplo n.º 11
0
def good_import_generator(n_citizens=20, n_relations=30):
    data = []
    address_generator = mimesis.Address('ru')
    number_generator = mimesis.Numbers()
    person_generator = mimesis.Person('ru')
    gender_generator = mimesis.Person('en')
    datetime_generator = mimesis.Datetime()
    for i in range(1, n_citizens + 1):
        street, building = address_generator.address().rsplit(' ', maxsplit=1)
        gender = gender_generator.gender().lower()
        while gender != 'male' and gender != 'female':
            gender = gender_generator.gender().lower()
        data.append({
            "citizen_id":
            i,
            "town":
            address_generator.city(),
            "street":
            street,
            "building":
            building,
            "apartment":
            number_generator.between(1, 100000),
            "name":
            person_generator.full_name(),
            "birth_date":
            datetime_generator.date(1900, 2018).strftime("%d.%m.%Y"),
            "gender":
            gender,
            "relatives": []
        })
    relations = set()
    for i in range(n_relations):
        relation = (number_generator.between(1, n_citizens),
                    number_generator.between(1, n_citizens))
        while relation in relations or (relation[1], relation[0]) in relations:
            relation = (number_generator.between(1, n_citizens),
                        number_generator.between(1, n_citizens))
        relations.add(relation)

        data[relation[0] - 1]["relatives"].append(relation[1])
        if relation[0] != relation[1]:
            data[relation[1] - 1]["relatives"].append(relation[0])
    return data
Ejemplo n.º 12
0
    def setup(self, browser):
        reg_link = "http://selenium1py.pythonanywhere.com/en-gb/accounts/login/"
        page = LoginPage(browser, reg_link)
        page.open()\
            .should_be_register_form()

        f_person = mimesis.Person()
        f_email = f_person.email(domains=['mimesis.name'], unique=True)
        f_password = f_person.password(length=10, hashed=False)
        page.register_new_user(f_email, f_password)
Ejemplo n.º 13
0
async def read_item(user_id: int, locale: Optional[str] = None):
    fake_user = mimesis.Person(locale=locale)
    return {
        "user_id": user_id,
        "username": fake_user.username(),
        "fullname": fake_user.full_name(),
        "age": fake_user.age(),
        "firstname": fake_user.first_name(),
        "lastname": fake_user.last_name(),
    }
Ejemplo n.º 14
0
 def test_registration_true(self, browser: "class Browser", capabilities, domain):
     self.browser = browser
     string = f"{capabilities[1]}, версия {capabilities[0]['version']}"
     browser.data["name"] = f"{self._NAME} корректный ввод браузер {capabilities[0]['browserName']} {string}"
     browser.setup_browser(capabilities[0]["browserName"], remote=True, desired_capabilities=capabilities[0])
     page = Personal(browser)
     page.open()
     browser.driver.set_window_size(1920, 1080)
     page.open_reg_form()
     login = mimesis.Person().password(length=12)
     password = mimesis.Person().password(length=12)
     page.registration(login=login, password=password, password_confirm=password)
     if not browser.debug:
         btn = page.registration_sumbit()
         btn.hover()
         btn.click()
         assert btn.hidden(wait=5), "Ошибка Клика: После клика не сработало событие регистрации и кнопка не пропала"
         
         page_profile = Profile(browser)
         page_profile.open()
         assert page_profile.sumbit().visible(), "Ошибка: Подтверждения регистрации"
Ejemplo n.º 15
0
def next_author(data_locale: str) -> typing.Iterator[Author]:
    personal = mimesis.Person(data_locale)
    author_id = 0

    while True:
        author_id += 1

        author = Author(author_id)
        author.first_name = personal.name()
        author.last_name = personal.surname()

        yield author
Ejemplo n.º 16
0
def create_user(save=False):
    person = mimesis.Person("en")
    user = edgewise.new_doc("User")
    user.first_name = person.name()
    user.last_name = person.last_name()
    # user.email = person.email()
    user.password = person.password()
    user.username = person.username()
    user.rbac_role = edgewise.new_doc("RBACRole",
                                      name='Database Administrator')
    if save:
        user.save()
    return user
Ejemplo n.º 17
0
    def generate_dummy_data(data_tokens):
        """
        Insert dummy data based on data tokens
        I - integer id
        L - login/username
        E - email
        P - password
        T - piece of text
        :return:
        """

        token_list = data_tokens.split(",")

        samples_count = random.randint(100, 1000)
        inserted_data = []
        for i in range(samples_count):
            values = []
            person = mimesis.Person("en")
            for token in token_list:
                person = mimesis.Person()
                if token == "I":
                    values.append(i)
                if token == "L":
                    data = person.username()
                    values.append(data)
                if token == "E":
                    data = person.email()
                    values.append(data)
                if token == "P":
                    data = person.password()
                    values.append(data)
                if token == "T":
                    sample_length = random.randint(1, 10)
                    data = mimesis.Text().text(quantity=sample_length)
                    values.append(data)
            inserted_data.append(tuple(values))

        return inserted_data, token_list
Ejemplo n.º 18
0
def next_owner(data_locale: str) -> typing.Iterator[Owner]:
    personal = mimesis.Person(data_locale)
    address = mimesis.Address(data_locale)
    owner_id = 0

    while True:
        owner_id += 1

        owner = Owner(owner_id)
        owner.first_name = personal.name()
        owner.last_name = personal.surname()
        owner.address = address.address()

        yield owner
Ejemplo n.º 19
0
    def seed():
        address = mimesis.Address()
        business = mimesis.Business()
        person = mimesis.Person()

        for _ in range(1, 6):
            distributor = models.Distributor(
                name=business.company(),
                email=person.email(),
                address=address.address(),
                campaign_cost=random.uniform(0, 10),
                max_sales_count=random.uniform(2, 10),
                ow_cost=random.uniform(0, 10),
            )
            db.session.add(distributor)

        db.session.commit()
Ejemplo n.º 20
0
    def seed():
        person = mimesis.Person()

        super_admin_role = models.Role.query.filter_by(
            name="Super Admin").first()
        account = models.Account(
            username="******",
            password="******",
            email="*****@*****.**",
            first_name="admin",
            last_name="admin",
            role=super_admin_role,
        )
        db.session.add(account)
        db.session.commit()

        distributors = models.Distributor.query.all()
        user_roles = models.Role.query.filter(
            models.Role.name != "Super Admin").all()

        for distributor in distributors:
            for user_role in user_roles:
                num_accounts = 2 if user_role.name not in {
                    "Shopper", "Admin Buyer"
                } else 1

                for _ in range(num_accounts):
                    first_name = person.first_name()
                    last_name = person.last_name()
                    username = f"{first_name[0]}{last_name}{random.randint(1, 9)}"

                    account = models.Account(
                        username=username.lower(),
                        password="******",
                        email=person.email(),
                        first_name=first_name,
                        last_name=last_name,
                        distributor_id=distributor.id,
                        role=user_role,
                    )
                    db.session.add(account)

        db.session.commit()
Ejemplo n.º 21
0
    def seed():
        address = mimesis.Address()
        business = mimesis.Business()
        person = mimesis.Person()

        vendor_types = [
            {
                "is_supplier": True
            },
            {
                "is_decorator": True
            },
            {
                "is_pick_pack": True
            },
            {
                "is_supplier": True,
                "is_pick_pack": True
            },
            {
                "is_decorator": True,
                "is_pick_pack": True
            },
        ]

        product_types = models.ProductType.query.all()

        # create five vendors for each product type
        for product_type in product_types:
            for vendor_type in vendor_types:
                vendor = models.Vendor(
                    name=f"{address.state()} {business.company()}",
                    email=person.email(),
                    address=address.address(),
                    **vendor_type,
                )

                product_type.vendors.append(vendor)

                db.session.add(vendor)
                db.session.add(product_type)
                db.session.commit()
Ejemplo n.º 22
0
def importToModel():
    try:
        dsnStr = cx_Oracle.makedsn("217.173.198.135", "1522", "orcltp")
        con = cx_Oracle.connect(user="******", password="******", dsn=dsnStr)
        num = int(input("How many rows should be entered? "))
        last_id = getLastID("model")
        print("Fetching rows...")
        for x in range(num):
            y = mimesis.Person()
            producer_id = random.randint(1, getLastID("producer"))
            type_id = random.randint(1, getLastID("type"))
            name = 'T' + y.identifier(mask="####")
            query = "INSERT INTO model (id_model, name, producer_id, type_id) VALUES (:1, :2, :3, :4)"
            cursor = con.cursor()
            last_id = last_id + 1
            cursor.execute(query, (last_id, name, producer_id, type_id))
            print(query)
            cursor.close()
        con.commit()
        print("Rows added successfully")
    except cx_Oracle.Error as error:
        print("Error occurred:")
        print(error)
    consoleInput()
Ejemplo n.º 23
0
def generate_userpass(seed):
    person = mimesis.Person(seed=seed)
    return [(f'{person.name()}_{person.surname()}', person.password(24, True))
            for i in range(30)]
Ejemplo n.º 24
0
# Generate a CSV with information for 50,000 fake persons

import mimesis
import csv
import random

person = mimesis.Person(locale='en')
genderEnum = mimesis.enums.Gender

with open('persons.csv', mode='w', newline='\n', encoding='utf-8') as person_file:
    writer = csv.writer(person_file)
    
    # Header Row
    writer.writerow(['Id', 'Full Name', 'Age', 'Occupation', 'Email', 'Telephone',
        'Nationality'])
    
    for i in range(0, 50000):
        rando = random.uniform(0, 1)
        if rando >= 0.5:
            gender = genderEnum.FEMALE
        else:
            gender = genderEnum.MALE
                
        row = [
            i,
            person.full_name(gender=gender),
            person.age(),
            person.occupation(),
            person.email(),
            person.telephone(),
            person.nationality()
outsize = config["customers"]["total"]
max_age = config["customers"]["max_age"]
min_age = config["customers"]["min_age"]
joined_start_date = config["customers"]["joined_start_date"]
joined_end_date = config["customers"]["joined_end_date"]
genders = config["genders"][language]
gender_prob = config["genders"]["percentages"]

# data processing config
amounts_cpu = config["data_processing"]["amount_in_cpu"]
auto_batch = True if config["data_processing"][
    "auto_batch_based_in_cpu"] == "True" else False

# loading mocking data type
business = mimesis.Business(language)
person = mimesis.Person(language)
address = mimesis.Address(language)
dates = mimesis.Datetime(language)

# Calculating random probabilities
# 245 countries
country_prob = common_functions.random_probabilities(1, 245)
ages_probab = common_functions.random_probabilities(min_age, max_age)

# Global customers array
customers = []


def generate_customers(amount, index_start):
    # generates customers' info
    # amount: number of customer to generate
Ejemplo n.º 26
0
def create_rbac_role(save=False):
    role = edgewise.new_doc("RBACRole")
    role.name = mimesis.Person("en").occupation().replace(' ', '')
    if save:
        role.save()
    return role
Ejemplo n.º 27
0
def person(request):
    return mimesis.Person(request.param)
Ejemplo n.º 28
0
def _mname(locale='en'):
    return mimesis.Person(locale).full_name()
Ejemplo n.º 29
0
import unittest

import mimesis

from api.blueprints import create_app
from api.blueprints.models import Post, User
from api.blueprints.tests.api_tests import utils

MODELS = [Post, User]
URL = '/api'

p = mimesis.Person()
t = mimesis.Text()


class AdminRegistrationTests(unittest.TestCase):
    link = f'{URL}/admin'

    def setUp(self):
        self.app, self.db = create_app(testing=True)
        username, password = p.username(), p.password()
        User.from_dict(dict(username=username, email=p.email(),
                            password=password, is_admin=True))
        self.code, self.admin = utils.post(
            self.app,
            f'{URL}/auth/login',
            username=username,
            password=password
        )
        self.headers = {'x-access-token': self.admin['token']}
Ejemplo n.º 30
0
def _occupation(locale='en'):
    return mimesis.Person(locale).occupation()