コード例 #1
0
def run():
    person = Person()
    text = Text()
    internet = Internet()
    dateTime = Datetime()

    for i in range(100):
        User.objects.create(password="******",
                            username=person.username(),
                            first_name=person.name(),
                            last_name=person.last_name(),
                            email=person.email())

    users = User.objects.all()

    for i in range(100):
        Post.objects.create(author=choice(users),
                            link=internet.home_page(),
                            title=text.title(),
                            description=text.text())

    posts = Post.objects.all()

    for i in range(100):
        Comment.objects.create(author=choice(users),
                               post=choice(posts),
                               description=text.text())
    def handle(self, *args, **options):
        # raise NotImplementedError()
        Snippet.objects.all().delete()
        users = []
        person = Person()
        for _ in range(40):
            User.objects.create(password=person.password(),
                                username=person.username(),
                                first_name=person.name(),
                                last_name=person.last_name(),
                                email=person.email())

        text = Text()
        users = User.objects.all()

        for _ in range(30):
            language = choice(['python', 'javascript', 'ruby', 'java'])

            if language == "java":
                content = open(BASE_DIR + "/core/fakecode/file.java").read()
            elif language == "python":
                content = open(BASE_DIR + "/core/fakecode/python.py").read()
            elif language == "javascript":
                content = open(BASE_DIR +
                               "/core/fakecode/javascript.js").read()
            else:
                content = open(BASE_DIR + "/core/fakecode/ruby.rb").read()
            title = text.sentence()
            if not Snippet.objects.filter(title=title).exists():
                Snippet.objects.create(author=choice(users),
                                       title=title,
                                       language=language,
                                       content=content)
コード例 #3
0
def get_new_user() -> User:
    person = Person()
    username = person.username()
    email = person.email(domains=["gmail.com", "yahoo.com"])
    password = person.password(length=25)
    user = User(username=username, email=email, password=password)
    user, error = user.save()
    return user
コード例 #4
0
    def __init__(self, master=None):
        threading.Thread.__init__(self)
        person = Person('ja')
        self.nickname = person.username()
        master.title('Chat')
        canvas = tk.Canvas(root, height=700, width=400,)
        canvas.pack()

        self.create_interface()
コード例 #5
0
    def handle(self, *args, **options):
        print('Deleting database!')
        Post.objects.all().delete()
        User.objects.filter(is_superuser=False).delete()
        Comment.objects.all().delete()
        Favorite.objects.all().delete()
        Like.objects.all().delete()

        person = Person()
        fake = Faker()
        # populator = Faker.getPopulator()

        users = []
        for fake_user in range(100):
            fake_user = User.objects.create_user(person.username(),
                                                 person.email(), 'password')
            users.append(fake_user)
        print("100 Fake users created!")

        fake_posts = []
        for i in range(50):
            post_dictionary = {
                'title': fake.sentence(),
                'description': fake.text(),
                'user': users[random.randrange(100)],
            }
            fake_posts.append(post_dictionary)

        posts = []
        for post_data in fake_posts:
            post = Post.objects.create(**post_data)
            posts.append(post)
        print('50 Posts imported!!!')

        for i in range(100):
            Like.objects.create(post=posts[random.randrange(50)],
                                user=users[i])
        print('100 Likes imported!!!')

        for i in range(100):
            Favorite.objects.create(post=posts[random.randrange(50)],
                                    user=users[i])
        print('100 Favorites imported!!!')

        for i in range(200):
            Comment.objects.create(post=posts[random.randrange(50)],
                                   user=users[random.randrange(100)],
                                   comment=fake.sentence())
        print('200 comments imported!')

        for i in range(100):
            Follow.objects.create(following=users[i],
                                  followed=users[random.randrange(30)])
        print('100 follows imported!')

        print('All data imported successfully!')
コード例 #6
0
ファイル: sandbox.py プロジェクト: InnaKorsun/oxwall_site
def persin_test():
    person = Person("en")
    print("u")
    user_info = dict(username=person.username(),
                     email=person.email(),
                     password=person.password(),
                     real_name=person.full_name(),
                     gender='men',
                     birthday=("1", "3", "1990"))
    print(user_info)
コード例 #7
0
    def handle(self, *args, **options):

        users = User.objects.all()
        for user in users:
            if not user.is_staff:
                user.delete()

        Post.objects.all().delete()
        person = Person('en')
        text = Text('en')
        users = []
        for i in range(5):
            user = User.objects.create_user(username=person.username(),
                                            password="******")
            users.append(user)

        posts = []
        for _ in range(40):

            post = Post(
                title=text.title(),
                description=text.text(8),
                link="https://github.com/momentum-cohort-2018-10/w5-apile-fan-sam",
                author=choice(users)
            )

            post.slug = slugify(post.title) + f'-{randint(1, 255)}'
            post.save()
            posts.append(post)

        for x in range(20):
            Vote.objects.create(vote=True,
                                voter=users[0],
                                post=posts[x])

            Vote.objects.create(vote=choice((True, False)),
                                voter=users[1],
                                post=posts[x])

            Vote.objects.create(vote=True,
                                voter=users[2],
                                post=posts[x])

            Vote.objects.create(vote=choice((True, False)),
                                voter=users[3],
                                post=posts[x])

            Vote.objects.create(vote=choice((True, False)),
                                voter=users[4],
                                post=posts[x])
コード例 #8
0
 def handle(self, *args, **kwargs):
     person = Person('ru')
     total = kwargs['total']
     admin = kwargs['admin']
     for i in range(total):
         password = User.objects.make_random_password()
         if admin:
             user = User.objects.create_superuser(
                 username=person.username(),
                 first_name=person.first_name(),
                 last_name=person.last_name(),
                 email=person.email(),
                 password=password,
             )
             print(f'Create new Superuser: {user} and password: {password}')
         else:
             user = User.objects.create_user(
                 username=person.username(),
                 first_name=person.first_name(),
                 last_name=person.last_name(),
                 email=person.email(),
                 password=password,
             )
             print(f'Create new user: {user} and password: {password}')
コード例 #9
0
ファイル: mimesis_class.py プロジェクト: LevNic/to_do
def get_user(number):
    """
    Creates random user data
    :param number: number of users
    :return: user data list
    """
    data = []
    for i in range(number):
        user_gender = random.sample([Gender.MALE, Gender.FEMALE], 1)[0]
        person = Person('ru')
        data.append(
            OrderedDict(first_name=person.first_name(gender=user_gender),
                        last_name=person.last_name(gender=user_gender),
                        age=person.age(minimum=18, maximum=66),
                        email=person.email(domains=('yandex.ru', 'gmail.com')),
                        username=person.username(template='UU_d')))
    return data
コード例 #10
0
    def handle(self, *args, **kwargs):
        print('Deleting Database...')
        User.objects.filter(is_superuser=False).delete()
        Post.objects.all().delete()
        Follow.objects.all().delete()
        Response.objects.all().delete()

        person = Person()
        fake = Faker()

        users = []
        for fake_user in range(100):
            # double check "create_user" vs "create"
            fake_user = User.objects.create_user(person.username(),
                                                 person.email(),
                                                 'password',
                                                 bio='Default Bio')
            users.append(fake_user)
        print("100 Fake Users Created")

        fake_posts = []
        for i in range(50):
            post_dictionary = {
                'text': fake.sentence(),
                'user': users[random.randrange(100)],
            }
            fake_posts.append(post_dictionary)

        posts = []
        for post_data in fake_posts:
            post = Post.objects.create(**post_data)
            posts.append(post)
        print('50 Posts Imported')

        for i in range(200):
            Response.objects.create(post=posts[random.randrange(50)],
                                    user=users[random.randrange(100)],
                                    text=fake.sentence())
        print('200 Responses Imported')

        for i in range(100):
            Follow.objects.create(following_user=users[i],
                                  followed_user=users[random.randrange(30)])
        print('100 Follows Imported')

        print('All Data Imported Successfully')
    def handle(self, *args, **options):
        Chilipili.objects.all().delete()
        Like.objects.all().delete()
        users = []
        person = Person()
        for _ in range(10):
            User.objects.create(password=person.password(), username=person.username(
            ), first_name=person.name(), last_name=person.last_name(), email=person.email())
        # date = Datetime()
        text = Text()
        users = User.objects.all()
        for _ in range(20):
            Chilipili.objects.create(author_user=choice(
                users), text=text.sentence())

        chilipilis = Chilipili.objects.all()
        for _ in range(100):
            Like.objects.create(like_user=choice(
                users), chilipili=choice(chilipilis))
コード例 #12
0
ファイル: test_bootstrap.py プロジェクト: tana2123/arxiv-auth
    def setUpClass(cls):
        """Generate some fake data."""
        cls.app = Flask('test')
        util.init_app(cls.app)
        cls.app.config['CLASSIC_DATABASE_URI'] = 'sqlite:///test.db'
        cls.app.config['CLASSIC_SESSION_HASH'] = 'foohash'
        cls.app.config['CLASSIC_SESSION_TIMEOUT'] = '36000'

        with cls.app.app_context():
            util.create_all()
            COUNT = 50

            cls.users = []

            _users = []
            _domain_users = []
            for i in range(COUNT):
                with util.transaction() as session:
                    locale = _get_locale()
                    person = Person(locale)
                    net = Internet(locale)
                    ip_addr = net.ip_v4()
                    email = person.email()
                    approved = 1 if _prob(90) else 0
                    deleted = 1 if _prob(2) else 0
                    banned = 1 if random.randint(0, 100) <= 1 else 0
                    first_name = person.name()
                    last_name = person.surname()
                    suffix_name = person.title()
                    name = (first_name, last_name, suffix_name)
                    joined_date = util.epoch(
                        Datetime(locale).datetime().replace(tzinfo=EASTERN))
                    db_user = models.DBUser(
                        first_name=first_name,
                        last_name=last_name,
                        suffix_name=suffix_name,
                        share_first_name=1,
                        share_last_name=1,
                        email=email,
                        flag_approved=approved,
                        flag_deleted=deleted,
                        flag_banned=banned,
                        flag_edit_users=0,
                        flag_edit_system=0,
                        flag_email_verified=1,
                        share_email=8,
                        email_bouncing=0,
                        policy_class=2,  # Public user. TODO: consider admin.
                        joined_date=joined_date,
                        joined_ip_num=ip_addr,
                        joined_remote_host=ip_addr)
                    session.add(db_user)

                    # Create a username.
                    username_is_valid = 1 if _prob(90) else 0
                    username = person.username()
                    db_nick = models.DBUserNickname(
                        user=db_user,
                        nickname=username,
                        flag_valid=username_is_valid,
                        flag_primary=1)

                    # Create the user's profile.
                    archive, subject_class = _random_category()
                    db_profile = models.DBProfile(
                        user=db_user,
                        country=locale,
                        affiliation=person.university(),
                        url=net.home_page(),
                        rank=random.randint(1, 5),
                        archive=archive,
                        subject_class=subject_class,
                        original_subject_classes='',
                        flag_group_math=1 if _prob(5) else 0,
                        flag_group_cs=1 if _prob(5) else 0,
                        flag_group_nlin=1 if _prob(5) else 0,
                        flag_group_q_bio=1 if _prob(5) else 0,
                        flag_group_q_fin=1 if _prob(5) else 0,
                        flag_group_stat=1 if _prob(5) else 0)

                    # Set the user's password.
                    password = person.password()
                    db_password = models.DBUserPassword(
                        user=db_user,
                        password_storage=2,
                        password_enc=util.hash_password(password))

                    # Create some endorsements.
                    archive, subject_class = _random_category()
                    net_points = 0
                    for _ in range(0, random.randint(1, 4)):
                        etype = random.choice(['auto', 'user', 'admin'])
                        point_value = random.randint(-10, 10)
                        net_points += point_value
                        if len(_users) > 0 and etype == 'auto':
                            endorser_id = random.choice(_users).user_id
                        else:
                            endorser_id = None
                        issued_when = util.epoch(
                            Datetime(locale).datetime().replace(
                                tzinfo=EASTERN))
                        session.add(
                            models.DBEndorsement(endorsee=db_user,
                                                 endorser_id=endorser_id,
                                                 archive=archive,
                                                 subject_class=subject_class,
                                                 flag_valid=1,
                                                 endorsement_type=etype,
                                                 point_value=point_value,
                                                 issued_when=issued_when))

                    session.add(db_password)
                    session.add(db_nick)
                    session.add(db_profile)
                    _users.append(db_user)
                    _domain_users.append(
                        (domain.User(user_id=str(db_user.user_id),
                                     username=db_nick.nickname,
                                     email=db_user.email,
                                     name=domain.UserFullName(
                                         forename=db_user.first_name,
                                         surname=db_user.last_name,
                                         suffix=db_user.suffix_name),
                                     verified=bool(
                                         db_user.flag_email_verified)),
                         domain.Authorizations(
                             classic=util.compute_capabilities(db_user), )))
                    session.commit()
                    # We'll use these data to run tests.
                    cls.users.append((
                        email,
                        username,
                        password,
                        name,
                        (archive, subject_class, net_points),
                        (approved, deleted, banned),
                    ))
コード例 #13
0
from mimesis.enums import Gender

print('#' * 5 + '个人信息' + '#' * 5)
person = Person('zh')
# 可以传递性别给full_name()
print(person.full_name(Gender.MALE))
print(person.level_of_english())
print(person.nationality())
print(person.work_experience())
print(person.political_views())
print(person.worldview())

# 自定义名字pattern
templates = ['l-d', 'U-d']
for item in templates:
    print(person.username(template=item))

print('\n')

print('#' * 5 + '地址' + '#' * 5)
address = Address('zh')
print(address.coordinates())
print(address.city())
print('\n')

print('#' * 5 + '地址' + '#' * 5)
business = Business('zh')
print(business.company())
print(business.company_type())
print('\n')
コード例 #14
0
class Users:
    def __init__(self):
        self.person = Person('en')
        self.generic = Generic('en')
        self.questions = Question.objects.all()

    def generate(self):
        for i in range(1, 101):
            if i % 2 != 0:
                user_gender = Gender.MALE
            else:
                user_gender = Gender.FEMALE
            firstname = self.person.first_name(gender=user_gender)
            lastname = self.person.last_name(gender=user_gender)
            user = User.objects.create_user(self.person.username(),
                                            self.person.email(), 'Qwerty1!')
            user.first_name = firstname
            user.last_name = lastname
            user.is_active = True
            self.update_aboutMe(user)
            self.update_aboutYou(user)
            user.save()

    def update_aboutMe(self, user):
        user.aboutme.gender = choice(list(commonInfo.GENDER))[0]

        randColorHairCount = randrange(1, len(commonInfo.COLOR_HAIR))
        user.aboutme.color_hair = sample(
            [index[0] for index in list(commonInfo.COLOR_HAIR)],
            k=randColorHairCount)

        randColorAyeCount = randrange(1, len(commonInfo.COLOR_AYE))
        user.aboutme.color_aye = sample(
            [index[0] for index in list(commonInfo.COLOR_AYE)],
            k=randColorAyeCount)

        user.aboutme.activate = True

        d1 = datetime.strptime('1/1/1970', '%m/%d/%Y')
        d2 = datetime.strptime('1/1/2002', '%m/%d/%Y')
        user.aboutme.birthday = self.random_date(d1, d2).strftime('%Y-%m-%d')

        user.aboutme.weight = randrange(45, 150)
        user.aboutme.growth = randrange(100, 250)

        user.aboutme.genres.set(
            self.get_random_list_of_multiple_data_from_objects(Genres.objects))
        user.aboutme.music_types.set(
            self.get_random_list_of_multiple_data_from_objects(
                MusicType.objects))
        user.aboutme.films.set(
            self.get_random_list_of_multiple_data_from_objects(Films.objects))
        user.aboutme.books.set(
            self.get_random_list_of_multiple_data_from_objects(Books.objects))
        user.aboutme.hobbies.set(
            self.get_random_list_of_multiple_data_from_objects(
                Hobbies.objects))
        user.aboutme.foods.set(
            self.get_random_list_of_multiple_data_from_objects(Foods.objects))
        user.aboutme.country = self.get_random_data_from_objects(
            Countries.objects)
        user.aboutme.save()
        self.save_questionary(user, user.aboutme)

    def update_aboutYou(self, user):
        user.aboutyou.gender = choice(list(commonInfo.GENDER))[0]

        randColorHairCount = randrange(1, len(commonInfo.COLOR_HAIR))
        user.aboutyou.color_hair = sample(
            [index[0] for index in list(commonInfo.COLOR_HAIR)],
            k=randColorHairCount)

        randColorAyeCount = randrange(1, len(commonInfo.COLOR_AYE))
        user.aboutyou.color_aye = sample(
            [index[0] for index in list(commonInfo.COLOR_AYE)],
            k=randColorAyeCount)

        min_age = randrange(18, 60)
        user.aboutyou.min_age = min_age
        user.aboutyou.max_age = randrange(min_age, 61)

        min_growth = randrange(100, 250)
        user.aboutyou.min_growth = min_growth
        user.aboutyou.max_growth = randrange(min_growth, 251)

        min_weight = randrange(45, 150)
        user.aboutyou.min_weight = min_weight
        user.aboutyou.max_weight = randrange(min_weight, 151)

        user.aboutyou.genres.set(
            self.get_random_list_of_multiple_data_from_objects(Genres.objects))
        user.aboutyou.music_types.set(
            self.get_random_list_of_multiple_data_from_objects(
                MusicType.objects))
        user.aboutyou.films.set(
            self.get_random_list_of_multiple_data_from_objects(Films.objects))
        user.aboutyou.books.set(
            self.get_random_list_of_multiple_data_from_objects(Books.objects))
        user.aboutyou.hobbies.set(
            self.get_random_list_of_multiple_data_from_objects(
                Hobbies.objects))
        user.aboutyou.foods.set(
            self.get_random_list_of_multiple_data_from_objects(Foods.objects))
        user.aboutyou.countries.set(
            self.get_random_list_of_multiple_data_from_objects(
                Countries.objects))
        user.aboutyou.save()
        self.save_questionary(user, user.aboutyou)

    def save_questionary(self, user, obj):
        for question in self.questions:
            question = Question.objects.get(pk=question.pk)
            answer = self.get_random_data_from_objects(
                Answer.objects.filter(question=question))
            obj_type = ContentType.objects.get_for_model(obj)
            questionary_obj, is_created = Questionary.objects.get_or_create(
                content_type=obj_type,
                user=user,
                question=question,
                defaults={'answer': answer})
            questionary_obj.answer = answer
            questionary_obj.save()

    def random_date(self, start, end):
        """
        This function will return a random datetime between two datetime
        objects.
        """
        delta = end - start
        int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
        random_second = randrange(int_delta)
        return start + timedelta(seconds=random_second)

    def get_random_data_from_objects(self, Objects):
        modelDataIds = Objects.values_list('id', flat=True)
        ChoiceId = choice(list(modelDataIds))
        Data = Objects.get(pk=ChoiceId)
        return Data

    def get_random_list_of_multiple_data_from_objects(self, Objects):
        countOfdata = Objects.count()
        randDataCount = randrange(1, countOfdata + 1)
        modelDataIds = Objects.values_list('id', flat=True)
        listOfRandomDataIds = sample(list(modelDataIds), k=randDataCount)
        multipleData = Objects.filter(id__in=listOfRandomDataIds)
        return multipleData
コード例 #15
0
ファイル: FakeData.py プロジェクト: vitalee78/test_bis
 def get_fake_authentication(self, loc):
     per = Person(loc)
     nickname = per.username(template=None)
     email = per.email(domains=None)
     password = per.password(8)
     return nickname, email, password
コード例 #16
0
class TestUserModel(TestCase):
    def setUp(self):
        self.db = db
        self.db.create_all()
        self.person = Person()

    def tearDown(self):
        self.db.session.remove()
        self.db.drop_all()

    def test_user_table(self):
        self.assertTrue(self.db.engine.has_table(User.__tablename__))

    def test_user_mode(self):
        username = self.person.username()
        email = self.person.email(domains=["gmail.com"])
        password = self.person.password(length=25)
        user = User(username=username, email=email, password=password)
        self.assertIsNotNone(user)
        self.user = user

    def test_user_save(self):
        username = self.person.username()
        email = self.person.email(domains=["gmail.com"])
        password = self.person.password(length=25)
        user = User(username=username, email=email, password=password)

        user, error = user.save()

        self.assertFalse(error)
        self.assertIsInstance(user, User)
        self.assertNotIsInstance(user, str)
        self.assertEqual(user.email, email)
        self.assertEqual(user.email, email)
        self.assertEqual(user.username, username)
        self.assertIsInstance(user.joined_at, datetime.datetime)

    def test_user_repr(self):
        username = self.person.username()
        email = self.person.email(domains=["gmail.com"])
        password = self.person.password(length=25)
        user = User(username=username, email=email, password=password)
        user, error = user.save()
        self.assertFalse(error)

        user_string = str(user)
        self.assertIsNotNone(user_string)

    def test_user_check_password(self):
        username = self.person.username()
        email = self.person.email(domains=["gmail.com"])
        password = self.person.password(length=25)
        user = User(username=username, email=email, password=password)
        user.save()

        self.assertTrue(user.check_password(password))
        self.assertFalse(user.check_password("wrong password"))

    def test_user_json_property(self):
        username = self.person.username()
        email = self.person.email(domains=["gmail.com"])
        password = self.person.password(length=25)
        user = User(username=username, email=email, password=password)
        user.save()

        user_json: Dict[str, Any] = user.json

        self.assertEqual(user_json.get("uid"), user.uid)
        self.assertEqual(user_json.get("username"), user.username)
        self.assertEqual(user_json.get("email"), user.email)

    def test_user_duplicate_error(self):
        username = self.person.username()
        email = self.person.email(domains=["gmail.com"])
        password = self.person.password(length=25)
        user = User(username=username, email=email, password=password)
        user.save()

        user2 = User(username=username, email=email, password=password)
        user2, error = user2.save()
        self.assertTrue(error)
        self.assertTrue("duplicate key value violates unique constraint" in user2)

    def test_add_user_in_bulk(self):
        users = list()
        length = 5
        for _ in range(length):
            username = self.person.username()
            email = self.person.email(domains=["gmail.com", "aol.com"])
            password = self.person.password(length=50)
            users.append(User(username, email, password))
        self.db.session.add_all(users)

        self.assertTrue(User.query.count() >= length)

    def test_user_level(self):
        username = self.person.username()
        email = self.person.email(domains=["gmail.com"])
        password = self.person.password(length=25)
        user_level = UserLevelEnum.ADMIN
        user = User(username=username, email=email, password=password, _user_level=user_level)
        user.save()

        self.assertEqual(user._user_level, user_level)

    def test_user_address(self):
        username = self.person.username()
        email = self.person.email(domains=["gmail.com"])
        password = self.person.password(length=25)
        user_level = UserLevelEnum.USER
        user = User(username=username, email=email, password=password, _user_level=user_level)
        user.save()

        self.assertDictEqual(user.address, {})

        address = {
            "area": "Mohakhali",
            "city": "Dhaka",
            "thana": {
                "name": "Banani",
                "zip": 1213
            }
        }

        user, err = user.update(address=address)
        self.assertFalse(err)

        self.assertDictEqual(user.address, address)
        self.assertEqual(user.address.get("city"), address.get("city"))

    def test_user_phone(self):
        username = self.person.username()
        email = self.person.email(domains=["gmail.com"])
        password = self.person.password(length=25)
        user_level = UserLevelEnum.SUPER_ADMIN
        user = User(username=username, email=email, password=password, _user_level=user_level)
        user.save()

        self.assertListEqual(user.phones, [])

        phones = ["01711111110", "01600000001"]
        user, err = user.update(phones=phones)
        self.assertFalse(err)

        self.assertListEqual(user.phones, phones)
        self.assertEqual(len(user.phones), len(phones))

    def test_user_update_in_bulk(self):
        users = list()
        length = 3
        for _ in range(length):
            username = self.person.username()
            email = self.person.email(domains=["gmail.com", "aol.com"])
            password = self.person.password(length=50)
            users.append(User(username, email, password))
        self.db.session.add_all(users)

        User.update_all(users, address={"city": "Dhaka"})
        self.assertTrue(any(user.address != {} for user in users))

        for user in users:
            self.assertEqual(user.address.get("city"), "Dhaka")

    def test_user_delete(self):
        username = self.person.username()
        email = self.person.email(domains=["gmail.com"])
        password = self.person.password(length=25)
        user_level = UserLevelEnum.SUPER_ADMIN
        user = User(username=username, email=email, password=password, _user_level=user_level)
        user.save()

        find_user: User = User.query.filter(
            User.username == username
        ).first()
        self.assertIsNotNone(find_user)

        find_user.delete()

        find_user: User = User.query.filter(
            User.username == username
        ).first()
        self.assertIsNone(find_user)

    def test_user_relationship_laptops(self):
        username = self.person.username()
        email = self.person.email(domains=["gmail.com"])
        password = self.person.password(length=25)
        user_level = UserLevelEnum.MODERATOR
        user = User(username=username, email=email, password=password, _user_level=user_level)
        user.save()

        laptop1 = Laptop(user.uid, serial_number="unique_serial_" + Generator.uuid(),
                         mac_address="unique_mac_" + Generator.uuid(), is_stolen=True)
        laptop2 = Laptop(user.uid, serial_number="unique_serial_" + Generator.uuid(),
                         mac_address="unique_mac_" + Generator.uuid(),
                         remarks="This laptop is imported and genuine operating system installed.")

        user.laptops.append(laptop1)
        user.laptops.append(laptop2)
        db.session.commit()

        find_user = User.query.get(user.uid)
        self.assertIsNotNone(find_user)

        self.assertTrue(find_user.laptops != [])
        self.assertEqual(len(find_user.laptops), 2)

        self.assertTrue(laptop1.owner == laptop2.owner)

        laptops = [laptop1, laptop2]
        for index, laptop in enumerate(laptops):
            self.assertEqual(find_user.laptops[index].uid, laptops[index].uid)
            self.assertEqual(find_user.laptops[index].item_type, ItemTypeEnum.LAPTOP)
            self.assertEqual(find_user.laptops[index].is_stolen, laptops[index].is_stolen)
            self.assertEqual(find_user.laptops[index].gd_copy_number, laptops[index].gd_copy_number)
            self.assertEqual(find_user.laptops[index].remarks, laptops[index].remarks)
            self.assertEqual(find_user.laptops[index].remarks, laptops[index].remarks)
            self.assertEqual(find_user.laptops[index].record_time, laptops[index].record_time)
            self.assertEqual(find_user.laptops[index].last_update, laptops[index].last_update)

            self.assertEqual(find_user.laptops[index].serial_number, laptops[index].serial_number)
            self.assertEqual(find_user.laptops[index].mac_address, laptops[index].mac_address)

    def test_user_relationship_cellphones(self):
        username = self.person.username()
        email = self.person.email(domains=["gmail.com"])
        password = self.person.password(length=25)
        user_level = UserLevelEnum.USER
        user = User(username=username, email=email, password=password, _user_level=user_level)
        user.save()

        generic = Generic("en")

        phone1 = CellPhone(user.uid, imei_1=generic.code.imei())
        phone2 = CellPhone(user.uid, imei_1=generic.code.imei(), imei_2=generic.code.imei(),
                           remarks="Dual sim phone.", is_stolen=True, gd_copy_number=f"GD-{Generator.uuid()}")
        phone3 = CellPhone(user.uid, imei_2=generic.code.imei(), is_stolen=False,
                           remarks="Oneek bhaalo phone!")

        user.cell_phones.append(phone1)
        user.cell_phones.append(phone2)
        user.cell_phones.append(phone3)
        db.session.commit()

        find_user = User.query.get(user.uid)
        self.assertIsNotNone(find_user)

        self.assertTrue(find_user.cell_phones != [])
        self.assertEqual(len(find_user.cell_phones), 3)

        self.assertTrue(phone1.owner == phone2.owner == phone3.owner)

        phones = [phone1, phone2, phone3]
        for index, _ in enumerate(phones):
            self.assertEqual(find_user.cell_phones[index].uid, phones[index].uid)
            self.assertEqual(find_user.cell_phones[index].item_type, ItemTypeEnum.CELL_PHONE)
            self.assertEqual(find_user.cell_phones[index].is_stolen, phones[index].is_stolen)
            self.assertEqual(find_user.cell_phones[index].gd_copy_number, phones[index].gd_copy_number)
            self.assertEqual(find_user.cell_phones[index].remarks, phones[index].remarks)
            self.assertEqual(find_user.cell_phones[index].remarks, phones[index].remarks)
            self.assertEqual(find_user.cell_phones[index].record_time, phones[index].record_time)
            self.assertEqual(find_user.cell_phones[index].last_update, phones[index].last_update)

            self.assertEqual(find_user.cell_phones[index].imei_1, phones[index].imei_1)
            self.assertEqual(find_user.cell_phones[index].imei_2, phones[index].imei_2)

    def test_user_relationship_vehicles(self):
        username = self.person.username()
        email = self.person.email(domains=["gmail.com"])
        password = self.person.password(length=25)
        user_level = UserLevelEnum.ADMIN
        user = User(username=username, email=email, password=password, _user_level=user_level)
        user.save()

        vehicle1 = Vehicle(user.uid, serial_number=f"serial-{Generator.uuid()}")
        vehicle2 = Vehicle(user.uid,
                           serial_number=f"serial-{Generator.uuid()}",
                           engine_number=f"engine_{Generator.uuid()}")
        vehicle3 = Vehicle(user.uid,
                           serial_number=f"serial-{Generator.uuid()}",
                           engine_number=f"engine_{Generator.uuid()}",
                           license_number=f"license-{Generator.uuid()}")

        user.vehicles.append(vehicle1)
        user.vehicles.append(vehicle2)
        user.vehicles.append(vehicle3)
        db.session.commit()

        find_user = User.query.get(user.uid)
        self.assertIsNotNone(find_user)

        self.assertTrue(find_user.vehicles != [])
        self.assertEqual(len(find_user.vehicles), 3)

        self.assertTrue(vehicle1.owner == vehicle2.owner == vehicle3.owner)

        vehicles = [vehicle1, vehicle2, vehicle3]
        for index, _ in enumerate(vehicles):
            self.assertEqual(find_user.vehicles[index].uid, vehicles[index].uid)
            self.assertEqual(find_user.vehicles[index].item_type, ItemTypeEnum.VEHICLE)
            self.assertEqual(find_user.vehicles[index].is_stolen, vehicles[index].is_stolen)
            self.assertEqual(find_user.vehicles[index].gd_copy_number, vehicles[index].gd_copy_number)
            self.assertEqual(find_user.vehicles[index].remarks, vehicles[index].remarks)
            self.assertEqual(find_user.vehicles[index].remarks, vehicles[index].remarks)
            self.assertEqual(find_user.vehicles[index].record_time, vehicles[index].record_time)
            self.assertEqual(find_user.vehicles[index].last_update, vehicles[index].last_update)

            self.assertEqual(find_user.vehicles[index].serial_number, vehicles[index].serial_number)
            self.assertEqual(find_user.vehicles[index].engine_number, vehicles[index].engine_number)
            self.assertEqual(find_user.vehicles[index].license_number, vehicles[index].license_number)
コード例 #17
0
          tweet VARCHAR(600)NOT NULL,
          twitter_user INT REFERENCES twitteruser ON DELETE CASCADE NOT NULL)"""
          )
c.execute(
    """CREATE TABLE IF NOT EXISTS notifications(id SERIAL NOT NULL PRIMARY KEY,
          tweet REFERENCES tweet_table ON DELETE CASCADE NOT NULL,
          receiver INT REFERENCES twitteruser ON DELETE CASCADE NOT NULL)""")

conn.commit()

for new_user in range(500):
    c.execute(
        'INSERT INTO twitteruser(id, username, password, display_name) VALUES(?,?,?,?)',
        [
            new_user + 1,
            person.username(),
            person.password(),
            person.full_name()
        ],
    )

for new_tweet in range(1000):
    c.execute(
        'INSERT INTO tweet(id, tweet, twitter_user) VALUES(?,?,(SELECT id FROM twitteruser ORDER BY RANDOM() LIMIT 1001))',
        [new_tweet + 1, text.text(quantity=1)])

for new_notification in range(200):
    rand_user = random.sample(range(1, 500), 2)
    rand_sender = random.choice(rand_user)
    c.execute(
        'INSERT INTO notifications(id, tweet, receiver) VALUES(?,?,(SELECT id FROM twitteruser ORDER BY RANDOM() LIMIT 201) )',