Exemple #1
0
    def test_unknown_provider(self):
        with pytest.raises(ModuleNotFoundError) as excinfo:
            Factory.create(providers=["dummy_provider"])
        assert str(excinfo.value) == "No module named 'dummy_provider'"

        with pytest.raises(ModuleNotFoundError) as excinfo:
            Factory.create(providers=["dummy_provider"], locale="it_IT")
        assert str(excinfo.value) == "No module named 'dummy_provider'"
Exemple #2
0
    def test_unknown_locale(self):
        with pytest.raises(AttributeError) as excinfo:
            Factory.create(locale="77")
        assert str(
            excinfo.value) == "Invalid configuration for faker locale `77`"

        with pytest.raises(AttributeError) as excinfo:
            Factory.create(locale="77_US")
        assert str(
            excinfo.value) == "Invalid configuration for faker locale `77_US`"
Exemple #3
0
    def test_pios_and_population_complete(self):
        '''check that all counties with a pick value > 0 have a at least one PIO and that
        all PIOs country code exists in the HorsePop file.'''

        provider = Factory.create(
            providers=['faker.providers.horse']).providers[0]

        # get a list of all the countries with a PIO
        pio_countries = set()
        for item in PIOS:
            pio_countries.add(item['country'])

        # get a list of all the countries with a horse population
        countries = set()
        for item in COUNTRY_POPULATION:
            if int(item['pick']) > 0:
                countries.add(item['iso3166'])

        # all PIOs are linked to a country with a horse population and  all countries with a horse population have a PIO
        if not countries.issubset(pio_countries):
            for item in countries.difference(pio_countries):
                print("No PIO in pios.csv for country code %s" % item)

            for item in pio_countries.difference(countries):
                print(
                    "PIO country code %s does not exist in horse_population.csv"
                    % item)

            self.assertTrue(
                0,
                "Data in data directory is missing data that could cause faker to fail"
            )
Exemple #4
0
    def __init__(self, locale=None, providers=None,
                 generator=None, includes=None, **config):
        self._factory_map = OrderedDict()
        self._weights = None

        if isinstance(locale, str):
            locales = [locale.replace('-', '_')]

        # This guarantees a FIFO ordering of elements in `locales` based on the final
        # locale string while discarding duplicates after processing
        elif isinstance(locale, (list, tuple, set)):
            assert all(isinstance(l, str) for l in locale)
            locales = []
            for l in locale:
                final_locale = l.replace('-', '_')
                if final_locale not in locales:
                    locales.append(final_locale)

        elif isinstance(locale, OrderedDict):
            assert all(isinstance(v, (int, float)) for v in locale.values())
            odict = OrderedDict()
            for k, v in locale.items():
                key = k.replace('-', '_')
                odict[key] = v
            locales = list(odict.keys())
            self._weights = list(odict.values())

        else:
            locales = [DEFAULT_LOCALE]

        for locale in locales:
            self._factory_map[locale] = Factory.create(locale, providers, generator, includes, **config)

        self._locales = locales
        self._factories = list(self._factory_map.values())
    def test_instance_seed_chain(self):
        factory = Factory.create()

        names = ['Real Name0', 'Real Name1', 'Real Name2', 'Real Name0', 'Real Name2']
        anonymized = [factory.seed_instance(name).name() for name in names]
        assert anonymized[0] == anonymized[3]
        assert anonymized[2] == anonymized[4]
Exemple #6
0
 def test_lang_unlocalized_provider(self):
     for locale in (None, "", "en_GB", "it_IT"):
         factory = Factory.create(providers=["faker.providers.file"],
                                  locale=locale)
         assert len(factory.providers) == 1
         assert factory.providers[0].__provider__ == "faker.providers.file"
         assert factory.providers[0].__lang__ is None
Exemple #7
0
    def __init__(self, gamma_host=None, gamma_port=None):
        self.gamma_host = gamma_host
        self.gamma_port = gamma_port
        self._init_request_arg()
        self._get_config()

        self._faker = Factory.create(locale='zh_CN')
 def test_http_put(self):
     fake = Factory.create("en_GB")
     client = AsyncHTTPClient(self.io_loop)
     for _ in range(10):
         data = {"item":{
             "email":     fake.email(),
             "firstname": fake.first_name(),
             "lastname":  fake.last_name(),
             "_password": fake.password()
         }}
         client.fetch("{}Person".format(BASE_URL), self.stop, 
                      method="PUT", 
                      body=dumps(data),
                      headers={"Content-Type": "application/json",
                               "simple-auth-token":"--foo-bar--"})
         response = self.wait()
         result = loads(response.body.decode("utf-8"))
         if result.get("error"):
             raise Exception(result["error"])
         
     for _ in range(10):
         data = {"item":{
             "name":  fake.name(),
             "dob": fake.date(),
             "active": fake.pybool(),
             "customer_type": "retail"
         }}
         client.fetch("{}Customer".format(BASE_URL), self.stop, 
                      method="PUT", 
                      body=dumps(data),
                      headers={"Content-Type": "application/json",
                               "simple-auth-token":"--foo-bar--"})
         response = self.wait()
         result = loads(response.body.decode("utf-8"))
         if result.get("error"):
             raise Exception(result["error"])
         
         data = {
             "item": {
                 "line1":  fake.address(),
                 "town": fake.city(),
                 "postcode": fake.postcode(),
                 "customer_type": "retail"
             },
             "to_add": [
                        [
                         "customers",
                         "Customer",
                         result["result"]["id"]
                        ]
                     ]
         }
         client.fetch("{}Address".format(BASE_URL), self.stop, 
                      method="PUT", 
                      body=dumps(data),
                      headers={"Content-Type": "application/json",
                               "simple-auth-token":"--foo-bar--"})
         response = self.wait()
         result = loads(response.body.decode("utf-8"))
def generate_child_account():
    filename = _child_file()
    locale = random.choice(['cs_CZ', 'de_DE', 'dk_DK', 'es_ES', 'et_EE', 'hr_HR', 'it_IT'])
    fake = Factory().create(locale)
    cp = configparser.RawConfigParser(allow_no_value=True)
    _generate_address(cp, fake)
    _generate_server(cp, fake)
    _generate_user(cp, fake)
    _add_anticaptcha(cp)
    with codecs.open(filename, 'w', 'utf8') as config_file:
        cp.write(config_file)
    return cp
Exemple #10
0
def generate_child_account():
    filename = _child_file()
    locale = random.choice(
        ['cs_CZ', 'de_DE', 'dk_DK', 'es_ES', 'et_EE', 'hr_HR', 'it_IT'])
    fake = Factory().create(locale)
    cp = ConfigParser.ConfigParser()
    _generate_address(cp, fake)
    _generate_server(cp, fake)
    _generate_user(cp, fake)
    _remove_unicode(cp)
    with codecs.open(filename, 'w', 'utf8') as config_file:
        cp.write(config_file)
    return cp
Exemple #11
0
    def setLocale(self, *args):
        """
        Give faker the option of not being completely useless and allowing each instance to change locales on
        demand.

        :param args: new desired locale(s)
        """
        locales = list(args)
        self._factory_map = {}
        for locale in locales:
            self._factory_map[locale] = Factory.create(locale, None, None, None)
        self._locales = locales
        self._factories = list(self._factory_map.values())
Exemple #12
0
    def __init__(self,
                 locale=None,
                 providers=None,
                 generator=None,
                 includes=None,
                 use_weighting=True,
                 **config):
        self._factory_map = OrderedDict()
        self._weights = None
        self._unique_proxy = UniqueProxy(self)

        if isinstance(locale, str):
            locales = [locale.replace('-', '_')]

        # This guarantees a FIFO ordering of elements in `locales` based on the final
        # locale string while discarding duplicates after processing
        elif isinstance(locale, (list, tuple, set)):
            locales = []
            for code in locale:
                if not isinstance(code, str):
                    raise TypeError('The locale "%s" must be a string.' %
                                    str(code))
                final_locale = code.replace('-', '_')
                if final_locale not in locales:
                    locales.append(final_locale)

        elif isinstance(locale, OrderedDict):
            assert all(isinstance(v, (int, float)) for v in locale.values())
            odict = OrderedDict()
            for k, v in locale.items():
                key = k.replace('-', '_')
                odict[key] = v
            locales = list(odict.keys())
            self._weights = list(odict.values())

        else:
            locales = [DEFAULT_LOCALE]

        for locale in locales:
            self._factory_map[locale] = Factory.create(
                locale,
                providers,
                generator,
                includes,
                use_weighting=use_weighting,
                **config)

        self._locales = locales
        self._factories = list(self._factory_map.values())
Exemple #13
0
def generate_config():
    config = UserOptions()
    filename = os.path.join(user_config_dir(), 'cloudomate.cfg')
    if os.path.exists(filename):
        print("cloudomate.cfg already present at %s" % filename)
        config.read_settings(filename=filename)
        return config
    locale = random.choice(
        ['cs_CZ', 'de_DE', 'dk_DK', 'es_ES', 'et_EE', 'hr_HR', 'it_IT'])
    fake = Factory().create(locale)
    cp = ConfigParser.ConfigParser()
    _generate_address(cp, fake)
    _generate_server(cp, fake)
    _generate_user(cp, fake)
    _remove_unicode(cp)
    with codecs.open(filename, 'w', 'utf8') as config_file:
        cp.write(config_file)
    return cp
Exemple #14
0
    def test_lang_localized_provider(self, with_default=True):
        class DummyProviderModule:
            localized = True

            def __init__(self):
                if with_default:
                    self.default_locale = "ar_EG"

            @property
            def __name__(self):
                return self.__class__.__name__

            class Provider:
                def __init__(self, *args, **kwargs):
                    pass

        with patch.multiple(
                "faker.factory",
                import_module=MagicMock(return_value=DummyProviderModule()),
                list_module=MagicMock(return_value=("en_GB", "it_IT")),
                DEFAULT_LOCALE="ko_KR",
        ):
            test_cases = [
                (None, False),
                ("", False),
                ("ar", False),
                ("es_CO", False),
                ("en", False),
                ("en_GB", True),
                ("ar_EG",
                 with_default),  # True if module defines a default locale
            ]
            for locale, expected_used in test_cases:
                factory = Factory.create(providers=["dummy"], locale=locale)
                assert factory.providers[0].__provider__ == "dummy"
                from faker.config import DEFAULT_LOCALE

                print(
                    f"requested locale = {locale} , DEFAULT LOCALE {DEFAULT_LOCALE}"
                )
                expected_locale = locale if expected_used else (
                    "ar_EG" if with_default else "ko_KR")
                assert factory.providers[0].__lang__ == expected_locale
Exemple #15
0
 def __init__(self, lambda_host = None, lambda_port = None, lambda_db_host = None):
     self._init_request_arg()
     from faker_nfd import NfdCompanyProvider
     from faker_nfd import NfdCreditCardProvide
     from faker_nfd import NfdDatatimeProvider
     from faker_nfd import NfdLoremProvider
     from faker_nfd import NfdPersonProvider
     from faker_nfd import NfdAddressProvider
     self._faker   = Factory.create(locale='zh_CN')
     self._faker.add_provider(NfdCompanyProvider)
     self._faker.add_provider(NfdCreditCardProvide)
     self._faker.add_provider(NfdDatatimeProvider)
     self._faker.add_provider(NfdLoremProvider)
     self._faker.add_provider(NfdPersonProvider)
     self._faker.add_provider(NfdAddressProvider)
     self.lambda_host = lambda_host
     self.lambda_port = lambda_port
     self.lambda_db_host = lambda_db_host
     self._get_config_lambda()
     self.db = LambdaDbCon(self._lambda_db_host,self._lambda_db_user,self._lambda_db_passwd,self._lambda_db_port,self._lambda_db_charset)
Exemple #16
0
def get_faker():
    faker = Factory()
    return faker.create()
Exemple #17
0
 def __init__(self):        
     self._get_config_arg()
     self._browser = None
     self._omega_browser = None 
     self._mp_browser =None
     self._myfaker = Factory.create(locale='zh_CN')
def createTickets():
    with open("tickets.csv", "wb") as csvfile:
        write_to_csv = csv.writer(csvfile, delimiter=",", quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
        write_to_csv.writerow(["ticket_id", "ticket_date", "ticket_desc"])
        for _ in range(1000):
            ticket_id = fake.random_int(min=100, max=99999)
            ticket_date = fake.date_time_between(start_date="-100d", end_date="now")
            ticket_desc = "Customer site returning a 500 instead of site content. Site has been down for 15 minutes."
            write_to_csv.writerow((ticket_id, ticket_date, ticket_desc))
        # Add spikes in tickets every 10 days
        # TODO: Add logging


def createZabbix():
    with open("zabbix.csv", "wb") as csvfile:
        write_to_csv = csv.writer(csvfile, delimiter=",", quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
        write_to_csv.writerow(["zabbix_id", "zabbix_date", "zabbix_desc"])
        for _ in range(1000):
            zabbix_id = fake.random_int(min=100, max=99999)
            zabbix_date = fake.date_time_between(start_date="-100d", end_date="now")
            server_number = random.randint(1000, 99999)
            zabbix_desc = "Server number {} is down.".format(server_number)
            write_to_csv.writerow((zabbix_id, zabbix_date, zabbix_desc))
        # Add spikes in tickets every 10 days
        # TODO: Add logging


if __name__ == "__main__":
    fake = Factory.create("en_US")
    writeTo_csv(fake)
Exemple #19
0
import factory
from factory.declarations import LazyAttribute
from factory.django import DjangoModelFactory
from faker.factory import Factory

from lily.tenant.factories import TenantFactory
from lily.utils.models.factories import PhoneNumberFactory

from .models import Account

faker = Factory.create("nl_NL")


class AccountFactory(DjangoModelFactory):
    tenant = factory.SubFactory(TenantFactory)
    name = LazyAttribute(lambda o: faker.company())
    description = LazyAttribute(lambda o: faker.bs())

    @factory.post_generation
    def phone_numbers(self, create, extracted, **kwargs):
        phone_str = faker.phone_number()
        if create:
            phone_number = PhoneNumberFactory(tenant=self.tenant, raw_input=phone_str)
            self.phone_numbers.add(phone_number)

    class Meta:
        model = Account
Exemple #20
0
def Faker(*args, **kwargs):
    return Factory.create(*args, **kwargs)
Exemple #21
0
# -*- coding:utf-8 -*-
import json
from robot.api import logger
from JiaseLibrary.utils.lambda_db import LambdaDbCon
from faker.factory import Factory
myfaker = Factory.create('zh_CN')
text = myfaker.text()  #随机生成一段文本


class _LambdaWithdrawalKeywords():
    def __init__(self):

        pass

    def withdrawal_get_custid(self, custname, custtype):
        """
        【功能】:获取客户id

        【参数】:

        custname: 客户名称

        custtype: 客户类型——GR/QY

        【返回值】:返回客户id
        """
        #通过custname和custtype获取custid
        if custtype == 'GR':
            url = "%s/cust/infos/personal/list" % self._lambda_url
        if custtype == 'QY':
            url = "%s/cust/infos/enterprise/list" % self._lambda_url
Exemple #22
0
from ....blog.models import Tag, Category, Post, Comment
from ....photo.models import Photo, Album, Tag as PhotoTag, Device, DeviceType
from ....userext.models import User
from ...models import PingServer
from django.core.management.base import BaseCommand
from django.utils import timezone
from faker.factory import Factory
from ....links.models import MyLink
from ....settings import MEDIA_ROOT

from django.core.files import File
import urllib.request
import os
import uuid

fake_ru = Factory.create('ru-RU')
fake_en = Factory.create('en-US')
fake = None


def clean():
    MyLink.objects.all().delete()
    Post.objects.all().delete()
    Comment.objects.all().delete()
    Tag.objects.all().delete()
    Category.objects.all().delete()
    PingServer.objects.all().delete()
    Album.objects.all().delete()
    PhotoTag.objects.all().delete()
    Device.objects.all().delete()
    DeviceType.objects.all().delete()
Exemple #23
0
 def __init__(self, host=None, port=None):
     self._host = host
     self._port = port
     self._faker = Factory.create(locale='zh_CN')
     self._get_config()
Exemple #24
0
from django.contrib.auth import authenticate, get_user
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.urls import reverse
from faker.factory import Factory

from .settings import USER_REGISTRATION_SETTINGS

factory = Factory.create()
from django.core import mail

UserModel = get_user_model()


def get_random_post_data(*args, **kwargs):
    """
    generates data used to register a new user
    """
    password = factory.password()
    return dict(
        email=factory.email(),
        password1=password,
        password2=password,
    )


@override_settings(**USER_REGISTRATION_SETTINGS)
class UserRegistrationTestCase(TestCase):
    UserModel = get_user_model()

    def setUp(self):
Exemple #25
0
            ticket_id = fake.random_int(min=100, max=99999)
            ticket_date = fake.date_time_between(start_date="-100d",
                                                 end_date="now")
            ticket_desc = "Customer site returning a 500 instead of site content. Site has been down for 15 minutes."
            write_to_csv.writerow((ticket_id, ticket_date, ticket_desc))
        # Add spikes in tickets every 10 days
        # TODO: Add logging


def createZabbix():
    with open('zabbix_list.csv', 'wb') as csvfile:
        write_to_csv = csv.writer(csvfile,
                                  delimiter=',',
                                  quotechar='"',
                                  quoting=csv.QUOTE_NONNUMERIC)
        write_to_csv.writerow(['zabbix_id,', 'zabbix_date,', 'zabbix_desc'])
        for _ in range(1000):
            zabbix_id = fake.random_int(min=100, max=99999)
            zabbix_date = fake.date_time_between(start_date="-100d",
                                                 end_date="now")
            server_number = random.randint(1000, 99999)
            zabbix_desc = "Server number {} is down.".format(server_number)
            write_to_csv.writerow((zabbix_id, zabbix_date, zabbix_desc))
        # Add spikes in tickets every 10 days
        # TODO: Add logging


if __name__ == "__main__":
    fake = Factory.create('en_US')
    writeTo_csv(fake)
Exemple #26
0
from django.core.urlresolvers import reverse
from factory import Factory, LazyFunction, SelfAttribute, SubFactory
from factory.fuzzy import FuzzyChoice, FuzzyInteger
from faker.factory import Factory as FakerFactory
from rest_framework.test import APIRequestFactory

faker = FakerFactory.create('en_GB')


def PingEventFactory(**kwargs):
    """
    Build a ping Request which is used by GitHub to ping webhooks. Event header
    is 'ping' and payload is built with the PingPayloadFactory.

    After generating the payload, hook ID is "synced" between the ``hook_id``
    and ``hook.id`` parameters - ``hook.id`` is disposed of and replaced with
    ``hook_id`.
    """
    uri = APIRequestFactory().get('/').build_absolute_uri(
        reverse('api:github'))

    data = PingPayloadFactory(hook__config__url=uri, **kwargs)
    data['hook']['id'] = data['hook_id']

    return PayloadRequestFactory(event='ping', data=data)


def PullRequestEventFactory(**kwargs):
    """
    Build a pull request Request generated when a Pull Request is created or
    updated.
            # TODO: Add logging

def createTickets():
    with open('tickets_list.csv', 'wb') as csvfile:
        write_to_csv = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
        write_to_csv.writerow(['ticket_id,', 'ticket_date,', 'ticket_desc'])
        for _ in range(1000):
            ticket_id = fake.random_int(min=100, max=99999)
            ticket_date = fake.date_time_between(start_date="-100d", end_date="now")
            ticket_desc = "Customer site returning a 500 instead of site content. Site has been down for 15 minutes."
            write_to_csv.writerow((ticket_id, ticket_date, ticket_desc))
        # Add spikes in tickets every 10 days
        # TODO: Add logging

def createZabbix():
    with open('zabbix_list.csv', 'wb') as csvfile:
        write_to_csv = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
        write_to_csv.writerow(['zabbix_id,', 'zabbix_date,', 'zabbix_desc'])
        for _ in range(1000):
            zabbix_id = fake.random_int(min=100, max=99999)
            zabbix_date = fake.date_time_between(start_date="-100d", end_date="now")
            server_number = random.randint(1000,99999)
            zabbix_desc = "Server number {} is down.".format(server_number)
            write_to_csv.writerow((zabbix_id, zabbix_date, zabbix_desc))
        # Add spikes in tickets every 10 days
        # TODO: Add logging

if __name__ == "__main__":
    fake = Factory.create('en_US')
    writeTo_csv(fake)
import factory

from factory.declarations import (SubFactory, LazyAttribute, SelfAttribute,
                                  Sequence, Iterator)
from factory.django import DjangoModelFactory
from factory.fuzzy import FuzzyChoice, FuzzyDate
from faker.factory import Factory

from lily.accounts.factories import AccountFactory
from lily.tenant.factories import TenantFactory
from lily.users.factories import LilyUserFactory
from lily.users.models import Team

from .models import Case, CaseStatus, CaseType

faker = Factory.create('nl_NL')

CASESTATUS_CHOICES = (
    'New',
    'Closed',
    'Pending input',
    'Waiting on hardware',
    'Follow up',
    'Client will contact us',
    'Documentation',
)

CASETYPE_CHOICES = (
    'Config',
    'Support',
    'Return Shipment',
Exemple #29
0
def _get_name():
    factory = Factory()
    faker = factory.create()
    return faker.name()
Exemple #30
0
def getFakerClass():
    # https://www.jianshu.com/p/6bd6869631d9
    fakerInfor = Factory().create('zh_CN')
    return fakerInfor
Exemple #31
0
from typing import Generator

from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from factory import LazyFunction, PostGenerationMethodCall, lazy_attribute, post_generation
from factory.django import DjangoModelFactory
from faker.factory import Factory as FakerFactory

faker = FakerFactory.create(providers=[])
max_retries = 200


class CleanModelFactory(DjangoModelFactory):
    """
    Ensures that created instances pass Django's `full_clean` checks.
    """
    class Meta:
        abstract = True

    @classmethod
    def _create(cls, model_class, *args, **kwargs):
        """
        Call `full_clean` on any created instance before saving

        Returns:
            model_class

        Raises:
            RuntimeError: Raised when validation fails on built model instance.
        """
        obj = model_class(*args, **kwargs)
def _get_name():
    factory = Factory()
    faker = factory.create()
    return faker.name()
Exemple #33
0
from typing import Generator

from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from factory import LazyFunction, PostGenerationMethodCall, lazy_attribute, post_generation
from factory.django import DjangoModelFactory
from faker.factory import Factory as FakerFactory

faker = FakerFactory.create(providers=[])
max_retries = 200


class CleanModelFactory(DjangoModelFactory):
    """
    Ensures that created instances pass Django's `full_clean` checks.
    """
    class Meta:
        abstract = True

    @classmethod
    def _create(cls, model_class, *args, **kwargs):
        """
        Call `full_clean` on any created instance before saving

        Returns:
            model_class

        Raises:
            RuntimeError: Raised when validation fails on built model instance.
        """
        obj = model_class(*args, **kwargs)
Exemple #34
0
import os
from datetime import datetime
import random

from django.contrib.auth.models import User
from django.utils.timezone import make_aware
from factory.django import DjangoModelFactory
from factory import fuzzy, Faker, post_generation
from faker.factory import Factory

fk = Factory.create()

from recipes.models import Recipe, RecipeRating

with open(os.path.join(os.path.dirname(__file__), 'foods.txt'), 'r', encoding='utf-8') as infp:
    INGREDIENTS = sorted(infp.read().strip().splitlines())

METHODS = [
    'boiled',
    'cooked',
    'deep-fried',
    'fried',
    'mashed',
    'massaged',
    'sautéed',
]

KINDS = [
    'casserole',
    'soup',
    'stew',
Exemple #35
0
def get_faker():
    faker = Factory()
    return faker.create()
Exemple #36
0
def Faker(*args,**kwargs):
    return Factory.create(*args,**kwargs)
Exemple #37
0
import factory
from factory.declarations import LazyAttribute
from factory.django import DjangoModelFactory
from faker.factory import Factory

from lily.tenant.factories import TenantFactory
from lily.utils.models.factories import PhoneNumberFactory

from .models import Account

faker = Factory.create()


class AccountFactory(DjangoModelFactory):
    tenant = factory.SubFactory(TenantFactory)
    name = LazyAttribute(lambda o: faker.company())
    description = LazyAttribute(lambda o: faker.bs())

    @factory.post_generation
    def phone_numbers(self, create, extracted, **kwargs):
        phone_str = faker.phone_number()
        if create:
            phone_number = PhoneNumberFactory(tenant=self.tenant, raw_input=phone_str)
            self.phone_numbers.add(phone_number)

    class Meta:
        model = Account
Exemple #38
0
from random import randint, choice
from ....blog.models import Tag, Category, Post, Comment
from ....userext.models import User
from django.core.management.base import BaseCommand
from django.utils import timezone
from faker.factory import Factory

#from odyssey.links import MyLink

fake_ru = Factory.create('ru-RU')
fake_en = Factory.create('en-US')
fake = None


def clean():
    #MyLink.objects.all().delete()
    Post.objects.all().delete()
    Comment.objects.all().delete()
    Tag.objects.all().delete()
    Category.objects.all().delete()

'''
def links_mylink():
    slug = 'facebook'
    name = '<i class="fa fa-facebook-official"></i> i on facebook'
    link = 'https://www.facebook.com/sergey.lagovskiy'
    ml = MyLink.objects.create(
        slug=slug,
        name=name,
        link=link,
        order=10