Exemplo n.º 1
0
    def test_login_management(faker: Faker) -> None:

        auth = Connector.get_authentication_instance()

        if BaseAuthentication.default_user:
            logins = auth.get_logins(BaseAuthentication.default_user)

            assert isinstance(logins, list)
            assert len(logins) > 0

            auth.flush_failed_logins(BaseAuthentication.default_user)
            logins = auth.get_logins(BaseAuthentication.default_user,
                                     only_unflushed=True)
            assert len(logins) == 0

            logins = auth.get_logins(BaseAuthentication.default_user,
                                     only_unflushed=False)
            assert len(logins) > 0

        logins = auth.get_logins(faker.ascii_email())
        assert isinstance(logins, list)
        assert len(logins) == 0

        logins = auth.get_logins(faker.pystr())
        assert isinstance(logins, list)
        assert len(logins) == 0
Exemplo n.º 2
0
def generate_data(n):

    b_official = backend_official(config['user'], config['pass'],
                                  config['host'], config['port'],
                                  config['db_name'])

    b_profile = backend_profile(config['user'], config['pass'], config['host'],
                                config['port'], config['db_name'])

    b_score = backend_score(config['user'], config['pass'], config['host'],
                            config['port'], config['db_name'])
    fake = Faker()
    for i in range(n):
        profile = dict()
        profile['name'] = fake.name()
        profile['phone'] = fake.phone_number()[:12]
        profile['email'] = fake.ascii_email()
        profile['referral'] = fake.name()
        profile['age'] = random.randint(0, 99)
        profile['password'] = fake.ean13()
        b_profile.insert_profile(profile)
        b_official.update_written_exam(profile['email'], random.randint(0, 40),
                                       'Intro In English')
        term = ['spring', 'summer', 'fall']
        b_score.write_class_score(profile['email'], 'Intro In English',
                                  random.randint(2000, 2019),
                                  term[random.randint(0, 2)], 10)
    def handle(self, *args, **options):

        nb_admins = options["nb_admins"][0]
        verbose = options["verbose"]
        fake = Faker(options["locale"])
        for admin_num in range(1, nb_admins + 1):
            hf = self.get_random_hf()
            claim_admin = create_test_claim_admin({
                "code":
                ''.join(
                    random.choices(string.ascii_uppercase + string.digits,
                                   k=8)),
                "last_name":
                fake.last_name(),
                "other_names":
                fake.first_name(),
                "email_id":
                fake.ascii_email(),
                "phone":
                "+" + fake.msisdn(),
                "health_facility_id":
                hf
            })
            if verbose:
                print(admin_num, "created claim admin", claim_admin, "for HF",
                      hf, "with code", claim_admin.code)
Exemplo n.º 4
0
        def test_05_no_notification_email_for_wrong_usernames(
            self, client: FlaskClient, faker: Faker
        ) -> None:

            if not Env.get_bool("MAIN_LOGIN_ENABLE"):  # pragma: no cover
                log.warning("Skipping admin/users tests")
                return

            uuid, data = self.create_user(client)

            self.delete_mock_email()

            # Just to verify that email is deleted
            with pytest.raises(FileNotFoundError):
                self.read_mock_email()

            email = faker.ascii_email()
            # Wrong credentials with a non existing email
            # -> No notification will be sent
            for _ in range(0, max_login_attempts):
                self.do_login(client, email, data["password"], status_code=401)

            # Verify the ban (i.e. status 403)
            headers, _ = self.do_login(client, email, data["password"], status_code=403)
            assert headers is None

            # Verify that there are no mocked email
            with pytest.raises(FileNotFoundError):
                self.read_mock_email()

            # Goodbye temporary user
            self.delete_user(client, uuid)
Exemplo n.º 5
0
def user_data(faker: Faker):
    return {
        "email": faker.ascii_email(),
        "name": faker.name(),
        "cpf": faker.ssn(),
        "password": faker.password(length=12),
    }
Exemplo n.º 6
0
def seed_users(apps, schema_editor):

    User.objects.create_superuser('*****@*****.**', 'secret')

    fake = Faker()

    if config('SEED', default=False, cast=bool):

        print('Sedding users')
        for i in range(1, 10):

            User.objects.create_user(fake.ascii_email(), 'secret')
def generate_user(dong=0):
    Faker.seed(dong)
    fake = Faker(['cs_CZ', 'en_GB', 'ru_RU'])
    user = ''
    email = ''
    while len(user) < 7 or len(user) > 15 or len(email) < 7:
        user = fake.user_name()
        email = fake.ascii_email()
    data = {
        'username': user,
        'email': email,
        'password': fake.credit_card_security_code()
    }
    return data
def generate_data():
    Faker.seed(432)
    data = []
    fake = Faker(['cs_CZ', 'en_GB', 'ru_RU'])
    for _ in range(1000):
        user = ''
        email = ''
        while len(user) < 6 and len(email) < 7:
            user = fake.user_name()
            email = fake.ascii_email()
        data.append({
            'username': user,
            'email': email,
            'password': fake.credit_card_security_code()
        })
    return data
Exemplo n.º 9
0
def generation(nb_generation, cpt):
    motif = "'"

    cpt += 1
    chaine_generated = ""

    generator = Faker()
    '''
    chaine_generated += motif
    chaine_generated+=str(cpt)
    chaine_generated += motif

    chaine_generated +=","+motif
    '''

    chaine_generated += "'"
    chaine_split = generator.name().split(" ")

    chaine_generated += chaine_split[0]
    chaine_generated += motif
    chaine_generated += "," + motif
    chaine_generated += chaine_split[1]
    chaine_generated += motif

    chaine_generated += "," + motif
    chaine_generated += generator.ascii_email()
    chaine_generated += motif
    chaine_generated += "," + motif
    chaine_generated += generator.date(pattern="%Y/%m/%d", end_datetime=None)
    chaine_generated += motif
    chaine_generated += "," + motif
    chaine_generated += generator.country()
    chaine_generated += motif
    chaine_generated += "," + motif
    chaine_generated += generator.city()
    chaine_generated += motif
    chaine_generated += "," + motif
    chaine_generated += generator.zipcode()
    chaine_generated += motif + ","
    chaine_generated += motif
    chaine_generated += generator.phone_number()
    chaine_generated += motif

    #debug
    #print(chaine_generated)

    return chaine_generated
Exemplo n.º 10
0
def add_user():
    faker = Faker(locale="zh_CN")
    num = request.args.get('num', 1, type=int)
    for i in range(num):
        sno = '20170900{0:04d}'.format(i + 164)
        name = faker.name()
        password = '******'
        phone = faker.phone_number()
        email = faker.ascii_email()
        user = User()
        user.sno = sno
        user.phone = phone
        user.password = password
        user.name = name
        user.email = email
        db.session.add(user)
        db.session.commit()
    return 'successfully added user {}'.format(num)
Exemplo n.º 11
0
    def test_admin_stats(self, client: FlaskClient, faker: Faker) -> None:

        if not Env.get_bool("AUTH_ENABLE"):
            log.warning("Skipping admin/logins tests")
            return

        r = client.get(f"{API_URI}/admin/logins")
        assert r.status_code == 401

        random_username = faker.ascii_email()
        self.do_login(client, random_username, faker.pystr(), status_code=401)

        headers, _ = self.do_login(client, None, None)

        r = client.get(f"{API_URI}/admin/logins", headers=headers)
        assert r.status_code == 200
        logins = self.get_content(r)
        assert isinstance(logins, list)
        assert len(logins) > 0
        assert "username" in logins[0]
        assert "date" in logins[0]
        assert "IP" in logins[0]
        assert "location" in logins[0]
        assert "failed" in logins[0]
        assert "flushed" in logins[0]

        for login in logins:
            if login["username"] == BaseAuthentication.default_user:
                break
        else:  # pragma: no cover
            pytest.fail("Default user not found in logins table")

        for login in logins:
            if login["username"] == random_username:
                assert login["failed"] is True
                assert login["flushed"] is False
                break
        else:  # pragma: no cover
            pytest.fail("Random user not found in logins table")
Exemplo n.º 12
0
    def get_random_email(cls,
                         faker: Faker,
                         name: str,
                         surname: str,
                         recursion: int = 0) -> str:
        # Please Faker, add some types hints and let me remove this str()!
        email = str(faker.ascii_email())

        # This email contains the name, re-sampling again
        if name.lower() in email.lower():  # pragma: no cover
            return cls.get_random_email(faker,
                                        name,
                                        surname,
                                        recursion=recursion + 1)

        # This email contains the surname, re-sampling again
        if surname.lower() in email.lower():  # pragma: no cover
            return cls.get_random_email(faker,
                                        name,
                                        surname,
                                        recursion=recursion + 1)

        email_tokens = email.split("@")
        email_username = email_tokens[0]
        if len(email_username) > 3:
            # Please Faker, add some types hints!
            return email

        # Probably this Faker locale only has very short emails.
        # It can happens with Chinese?
        # Let's return a repetition of the name it self
        if recursion >= 10:  # pragma: no cover
            return f"{email_username * 4}@{email_tokens[1]}"

        return cls.get_random_email(  # pragma: no cover
            faker,
            surname,
            surname,
            recursion=recursion + 1)
Exemplo n.º 13
0
class SchemaStringGenerator:
    def __init__(self):
        self._faker = Faker()

    def generate_string(self, schema: dict) -> str:
        format = schema.get(JsonSchemaPropertiesConstants.STRING_TYPE_FORMAT, None)
        min_length = schema.get(JsonSchemaPropertiesConstants.STRING_TYPE_MIN_LENGTH, None)
        max_length = schema.get(JsonSchemaPropertiesConstants.STRING_TYPE_MAX_LENGTH, None)
        enum = schema.get(JsonSchemaPropertiesConstants.STRING_TYPE_ENUM, None)
        pattern = schema.get(JsonSchemaPropertiesConstants.STRING_TYPE_PATTERN, None)

        if pattern is not None:
            return rstr.xeger(pattern)

        if enum is not None:
            return self._faker.random_elements(elements=enum, length=1)[0]

        if min_length is not None or max_length is not None:
            if max_length is None:
                max_length = 5
            return self._faker.pystr(min_length, max_length)

        if format:
            return self._generate_from_string_format(format)

        return self._faker.name()

    def _generate_from_string_format(self, format):
        return {
            "date-time": self._faker.date_time().strftime("%Y-%m-%dT%H:%M:%S%z"),
            "date": self._faker.date_time().strftime("%Y-%m-%d"),
            "time": self._faker.date_time().strftime("%H:%M:%S"),
            "email": self._faker.ascii_email(),
            "ipv4": self._faker.ipv4(),
            "ipv6": self._faker.ipv6(),
        }[format]
Exemplo n.º 14
0
def fake_users(iteration):
    fake = Faker()
    fake.add_provider(internet)
    fake.add_provider(person)
    fake.add_provider(misc)

    for _ in range(iteration):
        username = fake.user_name()
        first_name = fake.first_name()
        last_name = fake.last_name()
        email = fake.ascii_email()
        avatar_file_name = username + first_name + last_name + '.jpg'
        avatar_file_path = 'uploads\\' + avatar_file_name

        create_random_image_file(avatar_file_path)

        CustomUser.objects.create_user(username=username,
                                       first_name=first_name,
                                       last_name=last_name,
                                       password='******',
                                       email=email,
                                       avatar=avatar_file_path)
        print(username)
    print(f'{iteration} fake-users are created')
Exemplo n.º 15
0
Arquivo: 11111.py Projeto: yao0013/py3
import requests
from faker import Faker

f=Faker(locale='zh_CN')
for i in range(3):
    headers = {
    'Cookie': 'CID=e05ef3e6bcb4d7afa8accc77052726cf; SEID=4b315ba8e3f143a6e52d160100c35a3029b5ae48c9649e072dc1ca43407736826b58029e9fb18bf08b402648d830e7ac38902ae4070c82eabcc0a0ec; UID=110003619_N1_1569398339'
    }
    data = {
    'birthday':f.date(pattern="%Y-%m-%d"),
    'calendar':1,
    'naddress':'[{"value":"%s","name":"单位地址","label":"COMPANY"}]'%(f.address()),
    'name':f.name(),
    'nemail':'[{"label":"EMAIL","name":"邮箱","value":"%s"}]'%(f.ascii_email()),
    'new_company_name':'[{"label":"COMPANY","name":"公司","value":"%s"}]'%(f.company()),
    'new_position':'[{"label":"POSITION","value":"","name":"职位"}]',
    'nwebsite':'[]',
    'social':'[]',
    'tel':'[{"label":"MOBILE","value":"%s","name":"手机"}]'%(f.phone_number()),
    }

    url = 'http://yun.115rc.com/api/1.0/ios/9.0.0/22431/customer/save_member'



    r=requests.post(url=url,headers=headers,data=data)
    back = r.json()
    print(back)
Exemplo n.º 16
0
from faker import Faker
from databases import mycollection

user = Faker()
for _ in range(20):

    # generate and insert fake user data in database
    name = user.first_name()
    last_name = user.last_name()
    email = user.ascii_email()
    password = user.password(length=8)

    document = {
        "name": name,
        "last_name": last_name,
        "email": email,
        "password": password
    }
    userid = mycollection.insert_one(document)

print("OK")
Exemplo n.º 17
0
class Database:
    def __init__(self):
        self.fake = Faker()
        self.cnx = mysql.connector.connect(
            user='******',
            password='******',
            host='localhost',
            database='P6DB',
        )

    def insert_categories(self):
        cursor = self.cnx.cursor()
        sql_cat = "Insert IGNORE INTO category (name) VALUES (%(cat_name)s)"
        categories_list = ['Pizza', 'Dessert', 'Boissons', 'Snack']
        for cat in categories_list:
            cat_add = {'cat_name': cat}
            cursor.execute(sql_cat, cat_add)
        self.cnx.commit()
        cursor.close()

    def insert_delivery_mode(self):
        cursor = self.cnx.cursor()
        sql_delivery_mode = ("INSERT IGNORE INTO Delevery_mode (name)"
                             " VALUES (%(mode_n)s)")
        mode = ['à emporter', 'sur place', 'livraison']
        for mod in mode:
            mode_add = {'mode_n': mod}
            cursor.execute(sql_delivery_mode, mode_add)
        self.cnx.commit()
        cursor.close()

    def insert_payment_mode(self):
        cursor = self.cnx.cursor()
        sql_payment_mode = ("INSERT IGNORE INTO payment_mode (name) "
                            "VALUES (%(mode_payment)s)")
        mode_p = ['à la livraison', 'en ligne', 'sur place']
        for mode in mode_p:
            md = {'mode_payment': mode}
            cursor.execute(sql_payment_mode, md)
        self.cnx.commit()
        cursor.close()

    def insert_status(self):
        cursor = self.cnx.cursor()
        sql_status = "INSERT IGNORE INTO Status (name) VALUES (%(stat)s)"
        status = [
            'En attente de validation', 'En cours de préparation',
            'En cours de livraison'
        ]
        for i in status:
            stat_add = {'stat': i}
            cursor.execute(sql_status, stat_add)
        self.cnx.commit()
        cursor.close()

    def insert_right(self):
        cursor = self.cnx.cursor()
        sql_right = "INSERT IGNORE INTO Right (name) VALUES (%(right_n)s)"
        right_names = [
            'Connexion', 'Regarder la carte', 'Passer commande',
            'Voir recettes', 'Consulter stock'
        ]
        for name in right_names:
            name_add = {'right_n': name}
            cursor.execute(sql_right, name_add)
        self.cnx.commit()
        cursor.close()

    def insert_role(self):
        cursor = self.cnx.cursor()
        role = ['invité', 'client', 'employé']
        sql_role = ("INSERT IGNORE INTO Role (name) " "VALUES (%(role_n)s)")
        for r in role:
            role_add = {'role_n': r}
            cursor.execute(sql_role, role_add)
        self.cnx.commit()
        cursor.close()

    def insert_role_right(self):
        cursor = self.cnx.cursor()
        sqlrole_r = "INSERT IGNORE INTO Role_has_Right Role_id"

    def insert_user(self):
        for _ in range(10):
            self.fake.first_name()
            self.fake.last_name()
            self.fake.ascii_email()
            self.fake.phone_number()
            self.fake.password(length=12)
Exemplo n.º 18
0
#!/usr/bin/python

from faker import Faker
fake = Faker()
print("{Fake Name Generator}\n")
print("Name: " + fake.name())
print("Country: " + fake.country())
print("City: " + fake.city())
print("State: " + fake.state())
print("Address: " + fake.address())
print("Zip Code: " + fake.zipcode())
print("Credit Card: " + fake.credit_card_number())
print("Credit Card Security Code: " + fake.credit_card_security_code())
print("Credit Card Expire Date: " +
      fake.credit_card_expire(start="now", end="+10y", date_format="%m/%y"))
print("Birth Date: " + fake.date(pattern="%Y-%m-%d", end_datetime=None))
print("Email: " + fake.ascii_email())
print("Job: " + fake.job())

wait = input("\nPress [Enter] to go back...")
os.system("python3 DPredator.py")
Exemplo n.º 19
0
class EventGenerator:
    '''Generates a set of synthetic behavioral events, with timestamps constrained to a particular date.
    '''
    def __init__(self, start_date):
        self.faker = Faker()
        self.faker.add_provider(internet)
        self.start_date = start_date
        self.ua_generator = Randomize()

    def _gen_user_agent(self):
        devices = [
            ('desktop', 'mac'),
            ('desktop', 'windows'),
            ('tablet', 'ios'),
            ('smartphone', 'ios'),
            ('smartphone', 'android'),
        ]
        ua = self.ua_generator.random_agent(*random.choice(devices))
        return ua

    def _gen_event_type(self):
        '''Creates event type like "io.dagster.page_view".
        '''
        event_types = [
            'page_view',
            'button_click',
            'reload',
            'user_create',
            'user_delete',
            'signup',
        ]
        return 'io.dagster.{}'.format(random.choice(event_types))

    def _gen_timestamp(self):
        midnight = datetime.datetime.combine(
            self.start_date, datetime.time.min,
            tzinfo=datetime.timezone.utc).timestamp()
        return midnight + random.randint(0, 86400 - 1)

    def __iter__(self):
        return self

    def __next__(self):
        # pylint: disable=no-member
        return json.dumps({
            'environment':
            'production',
            'method':
            'GET',
            # Nested dicts
            'cookies': {
                'session': secrets.token_urlsafe(16),
                'persistent': secrets.token_urlsafe(16),
            },
            'run_id':
            self.faker.uuid4(),
            'type':
            self._gen_event_type(),
            'user_agent':
            self._gen_user_agent(),
            'ip_address':
            self.faker.ipv4_public(),
            'timestamp':
            self._gen_timestamp(),
            'url':
            '/' + self.faker.uri_path(),
            # like any good production system, we throw some random PII in our behavioral events
            'name':
            self.faker.name(),
            'email':
            self.faker.ascii_email(),
            # Nested lists
            'location':
            list(self.faker.location_on_land(coords_only=False)),
        })
    def test_registration(self, client: FlaskClient, faker: Faker) -> None:

        # Always enabled during core tests
        if not Env.get_bool("ALLOW_REGISTRATION"):  # pragma: no cover
            log.warning("User registration is disabled, skipping tests")
            return

        project_tile = get_project_configuration("project.title",
                                                 default="YourProject")
        proto = "https" if PRODUCTION else "http"

        # registration, empty input
        r = client.post(f"{AUTH_URI}/profile")
        assert r.status_code == 400

        # registration, missing information
        r = client.post(f"{AUTH_URI}/profile", data={"x": "y"})
        assert r.status_code == 400
        registration_data = {}
        registration_data["password"] = faker.password(5)
        r = client.post(f"{AUTH_URI}/profile", data=registration_data)
        assert r.status_code == 400
        registration_data["email"] = BaseAuthentication.default_user
        r = client.post(f"{AUTH_URI}/profile", data=registration_data)
        assert r.status_code == 400
        registration_data["name"] = faker.first_name()
        r = client.post(f"{AUTH_URI}/profile", data=registration_data)
        assert r.status_code == 400

        registration_data["surname"] = faker.last_name()
        r = client.post(f"{AUTH_URI}/profile", data=registration_data)
        assert r.status_code == 400

        registration_data["password_confirm"] = faker.password(strong=True)
        r = client.post(f"{AUTH_URI}/profile", data=registration_data)
        assert r.status_code == 400

        min_pwd_len = Env.get_int("AUTH_MIN_PASSWORD_LENGTH", 9999)

        registration_data["password"] = faker.password(min_pwd_len - 1)
        r = client.post(f"{AUTH_URI}/profile", data=registration_data)
        assert r.status_code == 400

        registration_data["password"] = faker.password(min_pwd_len)
        r = client.post(f"{AUTH_URI}/profile", data=registration_data)
        assert r.status_code == 409
        m = f"This user already exists: {BaseAuthentication.default_user}"
        assert self.get_content(r) == m

        registration_data["email"] = faker.ascii_email()
        r = client.post(f"{AUTH_URI}/profile", data=registration_data)
        assert r.status_code == 409
        assert self.get_content(
            r) == "Your password doesn't match the confirmation"

        registration_data["password"] = faker.password(min_pwd_len,
                                                       low=False,
                                                       up=True)
        registration_data["password_confirm"] = registration_data["password"]
        r = client.post(f"{AUTH_URI}/profile", data=registration_data)
        assert r.status_code == 409
        m = "Password is too weak, missing lower case letters"
        assert self.get_content(r) == m

        registration_data["password"] = faker.password(min_pwd_len, low=True)
        registration_data["password_confirm"] = registration_data["password"]
        r = client.post(f"{AUTH_URI}/profile", data=registration_data)
        assert r.status_code == 409
        m = "Password is too weak, missing upper case letters"
        assert self.get_content(r) == m

        registration_data["password"] = faker.password(min_pwd_len,
                                                       low=True,
                                                       up=True)
        registration_data["password_confirm"] = registration_data["password"]
        r = client.post(f"{AUTH_URI}/profile", data=registration_data)
        assert r.status_code == 409
        m = "Password is too weak, missing numbers"
        assert self.get_content(r) == m

        registration_data["password"] = faker.password(min_pwd_len,
                                                       low=True,
                                                       up=True,
                                                       digits=True)
        registration_data["password_confirm"] = registration_data["password"]
        r = client.post(f"{AUTH_URI}/profile", data=registration_data)
        assert r.status_code == 409
        m = "Password is too weak, missing special characters"
        assert self.get_content(r) == m

        registration_data["password"] = faker.password(strong=True)
        registration_data["password_confirm"] = registration_data["password"]
        r = client.post(f"{AUTH_URI}/profile", data=registration_data)
        # now the user is created but INACTIVE, activation endpoint is needed
        assert r.status_code == 200
        registration_message = "We are sending an email to your email address where "
        registration_message += "you will find the link to activate your account"
        assert self.get_content(r) == registration_message

        events = self.get_last_events(1)
        assert events[0].event == Events.create.value
        assert events[0].user == "-"
        assert events[0].target_type == "User"
        assert "name" in events[0].payload
        assert "password" in events[0].payload
        assert events[0].payload["password"] == OBSCURE_VALUE

        mail = self.read_mock_email()
        body = mail.get("body")
        assert body is not None
        assert mail.get("headers") is not None
        # Subject: is a key in the MIMEText
        assert f"Subject: {project_tile} account activation" in mail.get(
            "headers")
        assert f"{proto}://localhost/public/register/" in body

        # This will fail because the user is not active
        _, error = self.do_login(
            client,
            registration_data["email"],
            registration_data["password"],
            status_code=403,
        )
        assert error == "Sorry, this account is not active"

        # Also password reset is not allowed
        data = {"reset_email": registration_data["email"]}
        r = client.post(f"{AUTH_URI}/reset", data=data)
        assert r.status_code == 403
        assert self.get_content(r) == "Sorry, this account is not active"

        events = self.get_last_events(2)
        assert events[0].event == Events.refused_login.value
        assert events[0].payload["username"] == data["reset_email"]
        assert events[0].payload["motivation"] == "account not active"

        assert events[1].event == Events.refused_login.value
        assert events[1].payload["username"] == data["reset_email"]
        assert events[1].payload["motivation"] == "account not active"

        # Activation, missing or wrong information
        r = client.post(f"{AUTH_URI}/profile/activate")
        assert r.status_code == 400
        r = client.post(f"{AUTH_URI}/profile/activate", data=faker.pydict(2))
        assert r.status_code == 400
        # It isn't an email
        invalid = faker.pystr(10)
        r = client.post(f"{AUTH_URI}/profile/activate",
                        data={"username": invalid})
        assert r.status_code == 400

        headers, _ = self.do_login(client, None, None)

        activation_message = "We are sending an email to your email address where "
        activation_message += "you will find the link to activate your account"
        # request activation, wrong username
        r = client.post(f"{AUTH_URI}/profile/activate",
                        data={"username": faker.ascii_email()})
        # return is 200, but no token will be generated and no mail will be sent
        # but it respond with the activation msg and hides the non existence of the user
        assert r.status_code == 200
        assert self.get_content(r) == activation_message

        events = self.get_last_events(1)
        assert events[0].event != Events.activation.value

        assert self.read_mock_email() is None

        # request activation, correct username
        r = client.post(
            f"{AUTH_URI}/profile/activate",
            data={"username": registration_data["email"]},
        )
        assert r.status_code == 200
        assert self.get_content(r) == activation_message

        mail = self.read_mock_email()
        body = mail.get("body")
        assert body is not None
        assert mail.get("headers") is not None
        # Subject: is a key in the MIMEText
        assert f"Subject: {project_tile} account activation" in mail.get(
            "headers")
        assert f"{proto}://localhost/public/register/" in body

        token = self.get_token_from_body(body)
        assert token is not None

        # profile activation
        r = client.put(f"{AUTH_URI}/profile/activate/thisisatoken")
        # this token is not valid
        assert r.status_code == 400

        # profile activation
        r = client.put(f"{AUTH_URI}/profile/activate/{token}")
        assert r.status_code == 200
        assert self.get_content(r) == "Account activated"

        events = self.get_last_events(1)
        assert events[0].event == Events.activation.value
        assert events[0].user == registration_data["email"]
        assert events[0].target_type == "User"

        # Activation token is no longer valid
        r = client.put(f"{AUTH_URI}/profile/activate/{token}")
        assert r.status_code == 400
        assert self.get_content(r) == "Invalid activation token"

        # Token created for another user
        token = self.get_crafted_token("a")
        r = client.put(f"{AUTH_URI}/profile/activate/{token}")
        assert r.status_code == 400
        c = self.get_content(r)
        assert c == "Invalid activation token"

        # Token created for another user
        token = self.get_crafted_token("a", wrong_algorithm=True)
        r = client.put(f"{AUTH_URI}/profile/activate/{token}")
        assert r.status_code == 400
        c = self.get_content(r)
        assert c == "Invalid activation token"

        # Token created for another user
        token = self.get_crafted_token("a", wrong_secret=True)
        r = client.put(f"{AUTH_URI}/profile/activate/{token}")
        assert r.status_code == 400
        c = self.get_content(r)
        assert c == "Invalid activation token"

        headers, _ = self.do_login(client, None, None)
        r = client.get(f"{AUTH_URI}/profile", headers=headers)
        assert r.status_code == 200
        uuid = self.get_content(r).get("uuid")

        token = self.get_crafted_token("x", user_id=uuid)
        r = client.put(f"{AUTH_URI}/profile/activate/{token}")
        assert r.status_code == 400
        c = self.get_content(r)
        assert c == "Invalid activation token"

        # token created for the correct user, but from outside the system!!
        token = self.get_crafted_token("a", user_id=uuid)
        r = client.put(f"{AUTH_URI}/profile/activate/{token}")
        assert r.status_code == 400
        c = self.get_content(r)
        assert c == "Invalid activation token"

        # Immature token
        token = self.get_crafted_token("a", user_id=uuid, immature=True)
        r = client.put(f"{AUTH_URI}/profile/activate/{token}")
        assert r.status_code == 400
        c = self.get_content(r)
        assert c == "Invalid activation token"

        # Expired token
        token = self.get_crafted_token("a", user_id=uuid, expired=True)
        r = client.put(f"{AUTH_URI}/profile/activate/{token}")
        assert r.status_code == 400
        c = self.get_content(r)
        assert c == "Invalid activation token: this request is expired"

        # Testing the following use case:
        # 1 - user registration
        # 2 - user activation using unconventional channel, e.g. by admins
        # 3 - user tries to activate and fails because already active

        registration_data["email"] = faker.ascii_email()
        r = client.post(f"{AUTH_URI}/profile", data=registration_data)
        # now the user is created but INACTIVE, activation endpoint is needed
        assert r.status_code == 200

        mail = self.read_mock_email()
        body = mail.get("body")
        assert body is not None
        assert mail.get("headers") is not None
        assert f"{proto}://localhost/public/register/" in body

        token = self.get_token_from_body(body)
        assert token is not None

        headers, _ = self.do_login(client, None, None)

        r = client.get(f"{API_URI}/admin/users", headers=headers)
        assert r.status_code == 200
        users = self.get_content(r)
        uuid = None
        for u in users:
            if u.get("email") == registration_data["email"]:
                uuid = u.get("uuid")
                break

        assert uuid is not None
        r = client.put(f"{API_URI}/admin/users/{uuid}",
                       data={"is_active": True},
                       headers=headers)
        assert r.status_code == 204

        r = client.put(f"{AUTH_URI}/profile/activate/{token}")
        assert r.status_code == 400
        c = self.get_content(r)
        assert c == "Invalid activation token: this request is no longer valid"

        r = client.get(f"{API_URI}/admin/tokens", headers=headers)
        content = self.get_content(r)

        for t in content:
            if t.get("token") == token:  # pragma: no cover
                pytest.fail(
                    "Token not properly invalidated, still bount to user {}",
                    t.get(id))
Exemplo n.º 21
0
    def test_authentication_abstract_methods(faker: Faker) -> None:

        # Super trick!
        # https://clamytoe.github.io/articles/2020/Mar/12/testing-abcs-with-abstract-methods-with-pytest
        abstractmethods = BaseAuthentication.__abstractmethods__
        BaseAuthentication.__abstractmethods__ = frozenset()

        auth = Connector.get_authentication_instance()
        user = auth.get_user(username=BaseAuthentication.default_user)
        group = auth.get_group(name=DEFAULT_GROUP_NAME)
        role = auth.get_roles()[0]

        auth = BaseAuthentication()  # type: ignore

        assert (auth.get_user(username=faker.ascii_email(),
                              user_id=faker.pystr()) is None)

        assert auth.get_users() is None
        assert auth.save_user(user=user) is None
        assert auth.delete_user(user=user) is None

        assert auth.get_group(group_id=faker.pystr(),
                              name=faker.pystr()) is None

        assert auth.get_groups() is None
        assert auth.get_user_group(user=user) is None

        assert auth.get_group_members(group=group) is None

        assert auth.save_group(group=group) is None

        assert auth.delete_group(group=group) is None

        assert auth.get_tokens(
            user=user, token_jti=faker.pystr(), get_all=True) is None

        assert auth.verify_token_validity(jti=faker.pystr(), user=user) is None

        assert (auth.save_token(user=user,
                                token=faker.pystr(),
                                payload={},
                                token_type=faker.pystr()) is None)

        assert auth.invalidate_token(token=faker.pystr()) is None

        assert auth.get_roles() is None

        assert auth.get_roles_from_user(user=user) is None

        assert auth.create_role(name=faker.pystr(),
                                description=faker.pystr()) is None
        assert auth.save_role(role=role) is None

        assert auth.create_user(userdata={}, roles=[faker.pystr()]) is None

        assert auth.link_roles(user=user, roles=[faker.pystr()]) is None
        assert auth.create_group(groupdata={}) is None

        assert auth.add_user_to_group(user=user, group=group) is None

        assert (auth.save_login(
            username=faker.ascii_email(), user=user, failed=True) is None)
        assert (auth.save_login(
            username=faker.ascii_email(), user=None, failed=True) is None)
        assert (auth.save_login(
            username=faker.ascii_email(), user=user, failed=False) is None)
        assert (auth.save_login(
            username=faker.ascii_email(), user=None, failed=False) is None)

        assert auth.get_logins(username=faker.ascii_email) is None

        assert auth.flush_failed_logins(username=faker.ascii_email) is None

        BaseAuthentication.__abstractmethods__ = abstractmethods
Exemplo n.º 22
0
    def test_tokens_management(self, client: FlaskClient,
                               faker: Faker) -> None:

        auth = Connector.get_authentication_instance()

        # Just to verify that the function works
        verify_token_is_not_valid(auth, faker.pystr())
        verify_token_is_not_valid(auth, faker.pystr(), auth.PWD_RESET)
        verify_token_is_not_valid(auth, faker.pystr(), auth.ACTIVATE_ACCOUNT)

        user = auth.get_user(username=BaseAuthentication.default_user)
        t1, payload1 = auth.create_temporary_token(user, auth.PWD_RESET)
        assert isinstance(t1, str)
        # not valid if not saved
        verify_token_is_not_valid(auth, t1, auth.PWD_RESET)
        auth.save_token(user, t1, payload1, token_type=auth.PWD_RESET)
        verify_token_is_not_valid(auth, t1)
        verify_token_is_not_valid(auth, t1, auth.FULL_TOKEN)
        verify_token_is_valid(auth, t1, auth.PWD_RESET)
        verify_token_is_not_valid(auth, t1, auth.ACTIVATE_ACCOUNT)
        verify_token_is_not_valid(auth, faker.ascii_email(), t1)

        # Create another type of temporary token => t1 is still valid
        t2, payload2 = auth.create_temporary_token(user, auth.ACTIVATE_ACCOUNT)
        assert isinstance(t2, str)
        # not valid if not saved
        verify_token_is_not_valid(auth, t2, auth.ACTIVATE_ACCOUNT)
        auth.save_token(user, t2, payload2, token_type=auth.ACTIVATE_ACCOUNT)
        verify_token_is_not_valid(auth, t2)
        verify_token_is_not_valid(auth, t2, auth.FULL_TOKEN)
        verify_token_is_not_valid(auth, t2, auth.PWD_RESET)
        verify_token_is_valid(auth, t2, auth.ACTIVATE_ACCOUNT)
        verify_token_is_not_valid(auth, faker.ascii_email(), t2)

        EXPIRATION = 3
        # Create another token PWD_RESET, this will invalidate t1
        t3, payload3 = auth.create_temporary_token(user,
                                                   auth.PWD_RESET,
                                                   duration=EXPIRATION)
        assert isinstance(t3, str)
        # not valid if not saved
        verify_token_is_not_valid(auth, t3, auth.PWD_RESET)
        auth.save_token(user, t3, payload3, token_type=auth.PWD_RESET)
        verify_token_is_valid(auth, t3, auth.PWD_RESET)
        verify_token_is_not_valid(auth, t1)
        verify_token_is_not_valid(auth, t1, auth.FULL_TOKEN)
        verify_token_is_not_valid(auth, t1, auth.PWD_RESET)
        verify_token_is_not_valid(auth, t1, auth.ACTIVATE_ACCOUNT)

        # Create another token ACTIVATE_ACCOUNT, this will invalidate t2
        t4, payload4 = auth.create_temporary_token(user,
                                                   auth.ACTIVATE_ACCOUNT,
                                                   duration=EXPIRATION)
        assert isinstance(t4, str)
        # not valid if not saved
        verify_token_is_not_valid(auth, t4, auth.ACTIVATE_ACCOUNT)
        auth.save_token(user, t4, payload4, token_type=auth.ACTIVATE_ACCOUNT)
        verify_token_is_valid(auth, t4, auth.ACTIVATE_ACCOUNT)
        verify_token_is_not_valid(auth, t2)
        verify_token_is_not_valid(auth, t2, auth.FULL_TOKEN)
        verify_token_is_not_valid(auth, t2, auth.PWD_RESET)
        verify_token_is_not_valid(auth, t2, auth.ACTIVATE_ACCOUNT)

        # token expiration is only 3 seconds... let's test it
        time.sleep(EXPIRATION + 1)
        verify_token_is_not_valid(auth, t3, auth.PWD_RESET)
        verify_token_is_not_valid(auth, t4, auth.ACTIVATE_ACCOUNT)

        unpacked_token = auth.verify_token(None, raiseErrors=False)
        assert not unpacked_token[0]

        with pytest.raises(InvalidToken, match=r"Missing token"):
            auth.verify_token(None, raiseErrors=True)

        # Test token validiy
        _, token = self.do_login(client, None, None)

        tokens = auth.get_tokens(get_all=True)
        jti = None
        user = None
        for t in tokens:
            if t["token"] == token:
                jti = t["id"]
                user = t["user"]
                break
        assert jti is not None
        assert user is not None

        assert auth.verify_token_validity(jti, user)

        # Verify token against a wrong user

        another_user = auth.create_user(
            {
                "email": faker.ascii_email(),
                "name": "Default",
                "surname": "User",
                "password": faker.password(strong=True),
                "last_password_change": datetime.now(pytz.utc),
            },
            # It will be expanded with the default role
            roles=[],
        )
        auth.save_user(another_user)

        assert not auth.verify_token_validity(jti, another_user)
Exemplo n.º 23
0
print("AM/PM:\t ", fake.am_pm())
print("This year:\t ", fake.date_this_year())
print("ISBN10:\t ", fake.isbn10())
print("Postal code in state:\t ", fake.postalcode_in_state())
print("Instance:\t ", fake.seed_instance())
print("Android platform token:\t ", fake.android_platform_token())
print("Data time:\t ", fake.date_time())
print("ISBN3:\t ", fake.isbn13())
print("Postal code plus 4:\t ", fake.postalcode_plus4())
print("Sentence:\t ", fake.sentence())
print("Email:\t ", fake.ascii_company_email())
print("Date time add:\t ", fake.date_time_ad())
print("ISO8601:\t ", fake.iso8601())
print("Postcode:\t ", fake.postcode())
print("Sentence:\t ", fake.sentences())
print("ASCII email:\t ", fake.ascii_email())
print("Date time beween:\t ", fake.date_time_between())
print("ITIN:\t ", fake.itin())
print("Postcode in state:\t ", fake.postcode_in_state())
# print("Set formatter:\t ", fake.set_formatter())
print("ASCII free email:\t ", fake.ascii_free_email())
print("Date time between dates:\t ", fake.date_time_between_dates())
print("Fake job:\t ", fake.job())
print("Prefix:\t ", fake.prefix())
print("SHA1:\t ", fake.sha1())
print("ASCII safe email:\t ", fake.ascii_safe_email())
print("Date time this country:\t ", fake.date_time_this_century())
print("Language code:\t ", fake.language_code())
print("Prefix female:\t ", fake.prefix_female())
print("SHA256:\t ", fake.sha256())
print("Bank country:\t", fake.bank_country())
def update_customers(customerFile, fileDate, Delta=False):
    fake2 = Faker('en_AU')
    fake2.seed_instance(43212)

    fake = Faker('en_AU')
    fake.seed_instance(4321)
    with open(str(pathlib.Path(__file__).parent) + '/Data/customer/customer_' +
              fileDate + '.csv',
              'w',
              newline='') as csvfile:
        try:
            custs = read_csv(
                str(pathlib.Path(__file__).parent) +
                './Data/customer/customer_' + customerFile + '.csv')
        except:
            custs = read_csv('./Data/customer/customer_20200101.csv')
        update_count = int(len(custs) * random.randint(1, 20) * 0.001)
        insert_count = int(len(custs) * random.randint(0, 15) * 0.001)
        logging.info("Generating update customer_" + fileDate +
                     ".csv file with " + str(update_count) +
                     " updated customers and " + str(insert_count) +
                     " new customers")
        csvwriter = csv.writer(csvfile,
                               delimiter=',',
                               quotechar='"',
                               quoting=csv.QUOTE_MINIMAL)
        for i in range(update_count):
            whatToChange = random.randint(1, 3)

            random_cust = random.randint(1, len(custs) - 1)
            #print(str(random_cust)+' '+str(whatToChange))
            if (whatToChange == 1):
                #print("hi")

                custs[random_cust][4] = fake2.address().replace("\n", " ")

            if (whatToChange == 2):

                custs[random_cust][2] = fake2.ascii_email()

            if (whatToChange == 3):
                custs[random_cust][5] = fake2.city()
                custs[random_cust][6] = fake2.state()
            if (Delta == True):
                csvwriter.writerow(custs[random_cust])
        #print(custs)
        if (Delta == False):
            for customer in custs:
                csvwriter.writerow(customer)

        for i in range(insert_count):
            person = fake.simple_profile(sex=None)
            csvwriter.writerow([
                fake.bban() + str(random.randint(1, 208888888888888888888)),
                person['name'], person['mail'], person['birthdate'],
                fake.address().replace("\n", " "),
                fake.city(),
                fake.state(),
                fake.postcode(),
                fake.date_between(start_date="-6y", end_date="today")
            ])
Exemplo n.º 25
0
def seed_db():
    from models.User import User
    from models.Store import Store
    from models.Product import Product
    from models.Customer import Customer
    from models.Order import Order
    from main import bcrypt
    from faker import Faker

    faker = Faker()
    users = []
    stores = []
    products = []
    customers = []

    for i in range(5):
        user = User()
        user.email = f"test{i+1}@test.com"
        user.password = bcrypt.generate_password_hash("123456").decode("utf-8")
        user.isAdmin = False
        db.session.add(user)
        users.append(user)

        db.session.commit()

        store = Store()
        store.storename = faker.bs()
        store.firstname = faker.first_name()
        store.lastname = faker.last_name()
        store.user_id = users[i].id
        db.session.add(store)
        stores.append(store)

        db.session.commit()

        for j in range(5):
            product = Product()
            product.title = faker.numerify(text="Duck ###")
            product.price = faker.random_int(min=5, max=200, step=5)
            product.store_id = stores[i].id
            db.session.add(product)
            products.append(product)

        db.session.commit()

        for j in range(5):
            customer = Customer()
            customer.firstname = faker.first_name()
            customer.lastname = faker.last_name()
            customer.email = faker.ascii_email()
            customer.phone = faker.phone_number()
            customer.store_id = stores[i].id
            db.session.add(customer)
            customers.append(customer)

            db.session.commit()

            for k in range(5):
                order = Order()
                order.order_placed = choice([True, False])
                order.customer_id = choice(customers).id
                db.session.add(order)

                db.session.commit()

                for m in range(3):
                    order.orders_products.append(choice(products))

                    db.session.commit()

        customers = []

    db.session.commit()

    print("Tables seeded")
Exemplo n.º 26
0
class Generator:
    _username = set()
    _image_counter = 0

    def _gen_username(self):
        username = self.fake.user_name()
        if username in self._username:
            self._gen_username()
        else:
            self._username.add(username)
        return username

    def __init__(
            self,
            number_of_users=None,
            max_posts_per_user=None,
            max_likes_per_user=None,
            api_sleep=None,
            start_date=None,
            end_date=None,
            max_post_length=None,
            image_generation=None,
            images_chance=None,
            unsplash_key=None,
    ):
        self.data = get_yaml('generator')
        self.fake = Faker()
        self.NUMBER_OF_USERS = number_of_users or hard_get(self.data, 'number_of_users')
        self.MAX_POSTS_PER_USER = max_posts_per_user or hard_get(self.data, 'max_posts_per_user')
        self.MAX_LIKES_PER_USER = max_likes_per_user or hard_get(self.data, 'max_likes_per_user')

        self.API_SLEEP = api_sleep or soft_get(self.data, 'api_sleep', float)

        self.START_DATETIME = start_date or soft_get(self.data, 'start_date', dt.date)
        self.END_DATETIME = end_date or soft_get(self.data, 'end_date', dt.date)

        self.MAX_POST_LENGTH = max_post_length or soft_get(self.data, 'max_post_length', int)

        self.IMAGE_GENERATION = image_generation or soft_get(self.data, 'image_generation', bool)
        if self.IMAGE_GENERATION:
            self.IMAGES_CHANCE = images_chance or soft_get(self.data, 'images_chance', float)
            self.UNSPLASH_KEY = unsplash_key or hard_get(self.data, 'unsplash_key')

    @staticmethod
    def generate_like(user):
        post = choice(Post.objects.all())
        like = Like.objects.get(post=post)
        like.user.add(user)

    def generate_post(self, user):

        date = self.fake.date_time_between(
            start_date=user.date_joined,
            end_date=self.END_DATETIME,
            tzinfo=timezone('Europe/Kiev'),
        )
        title = ' '.join(self.fake.words(
            nb=randint(1, 5),
            ext_word_list=None,
            unique=False
        )
        ).upper()

        text = self.fake.text(max_nb_chars=randint(100, self.MAX_POST_LENGTH), ext_word_list=None)

        post = Post(title=title,
                 text=text,
                 creator=user)
        post.save()

        if self.IMAGE_GENERATION:
            chance = randint(1, 100)
            if chance <= self.IMAGES_CHANCE * 100 and self._image_counter < 50:
                self._image_counter += 1
                response = r.request('GET', rf'http://api.unsplash.com/photos/random/?client_id={self.UNSPLASH_KEY}')
                sleep(self.API_SLEEP)
                content = response.content
                content = content.decode("UTF-8")
                content = json.loads(content)
                url = content['urls']['regular']
                response = r.request('GET', url)
                sleep(self.API_SLEEP)
                image = os.path.join(MEDIA_ROOT, 'posts', f'{post.id}.png')
                with open(image, 'wb') as img:
                    img.write(response.content)
                post.image = image

        post.pub_date = date
        post.save()

        return post

    def generate_user(self):
        username = self._gen_username()
        email = self.fake.ascii_email()
        password = self.fake.ean(length=8)
        first_name = self.fake.first_name()
        last_name = self.fake.last_name()
        date_joined = self.fake.date_time_between(
                start_date=self.START_DATETIME,
                end_date=self.END_DATETIME,
                tzinfo=timezone('Europe/Kiev'),
        )
        profile_info = dict(
            company=self.fake.company(),
            role=self.fake.job(),

            city=self.fake.city(),
            country=self.fake.country(),

            bio=self.fake.text(max_nb_chars=randint(50, 500)),
        )

        user = User(username=username,
                    email=email,
                    first_name=first_name,
                    last_name=last_name,
                    date_joined=date_joined)
        user.set_password(password)
        user.save()

        profile = UserProfile.objects.get(owner=user)
        for key, val in profile_info.items():
            setattr(profile, key, val)
        profile.save()

        return user

    def generation(self):
        for i in range(self.NUMBER_OF_USERS):
            print(f'{i+1} of {self.NUMBER_OF_USERS} user generation!').upper()
            u = self.generate_user()

            posts = randint(0, self.MAX_POSTS_PER_USER)

            for ii in range(posts):
                print(f'Post {ii+1}')
                self.generate_post(u)

        users = User.objects.all()

        for user in users:
            print('Generating Likes!').upper()
            likes = randint(0, self.MAX_LIKES_PER_USER)

            for _ in range(likes):
                self.generate_like(user)
    def test_01_login(self, client: FlaskClient, faker: Faker) -> None:
        """ Check that you can login and receive back your token """

        log.info("*** VERIFY CASE INSENSITIVE LOGIN")
        # BaseAuthentication.load_default_user()
        # BaseAuthentication.load_roles()
        USER = BaseAuthentication.default_user or "just-to-prevent-None"
        PWD = BaseAuthentication.default_password or "just-to-prevent-None"

        # Login by using upper case username
        self.do_login(client, USER.upper(), PWD)

        events = self.get_last_events(1)
        assert events[0].event == Events.login.value
        assert events[0].user == USER

        # Wrong credentials
        # Off course PWD cannot be upper :D
        self.do_login(client, USER, PWD.upper(), status_code=401)

        events = self.get_last_events(1)
        assert events[0].event == Events.failed_login.value
        assert events[0].payload["username"] == USER

        log.info("*** VERIFY valid credentials")
        # Login by using normal username (no upper case)
        headers, _ = self.do_login(client, None, None)

        events = self.get_last_events(1)
        assert events[0].event == Events.login.value
        assert events[0].user == USER

        time.sleep(5)
        # Verify MAX_PASSWORD_VALIDITY, if set
        headers, token = self.do_login(client, None, None)

        events = self.get_last_events(1)
        assert events[0].event == Events.login.value
        assert events[0].user == USER

        self.save("auth_header", headers)
        self.save("auth_token", token)

        # Verify credentials
        r = client.get(f"{AUTH_URI}/status", headers=headers)
        assert r.status_code == 200
        c = self.get_content(r)
        assert isinstance(c, bool) and c

        # this check verifies a BUG with neo4j causing crash of auth module
        # when using a non-email-username to authenticate
        log.info("*** VERIFY with a non-email-username")

        self.do_login(
            client,
            "notanemail",
            "[A-Za-z0-9]+",
            status_code=400,
        )

        # Check failure
        log.info("*** VERIFY invalid credentials")

        random_email = faker.ascii_email()
        self.do_login(
            client,
            random_email,
            faker.password(strong=True),
            status_code=401,
        )

        events = self.get_last_events(1)
        assert events[0].event == Events.failed_login.value
        assert events[0].payload["username"] == random_email
Exemplo n.º 28
0
    def test_sendmail(self, client: FlaskClient, faker: Faker) -> None:

        headers, _ = self.do_login(client, None, None)

        r = client.get(f"{API_URI}/admin/mail", headers=headers)
        assert r.status_code == 405

        r = client.put(f"{API_URI}/admin/mail", headers=headers)
        assert r.status_code == 405

        r = client.patch(f"{API_URI}/admin/mail", headers=headers)
        assert r.status_code == 405

        r = client.delete(f"{API_URI}/admin/mail", headers=headers)
        assert r.status_code == 405

        data: Dict[str, Any] = {"dry_run": False}
        r = client.post(f"{API_URI}/admin/mail", json=data, headers=headers)
        assert r.status_code == 400

        data["subject"] = faker.pystr()
        r = client.post(f"{API_URI}/admin/mail", json=data, headers=headers)
        assert r.status_code == 400

        data["body"] = faker.text()
        r = client.post(f"{API_URI}/admin/mail", json=data, headers=headers)
        assert r.status_code == 400

        data["to"] = faker.pystr()
        r = client.post(f"{API_URI}/admin/mail", json=data, headers=headers)
        assert r.status_code == 400

        data["to"] = faker.ascii_email()
        data["body"] = "TEST EMAIL BODY"
        r = client.post(f"{API_URI}/admin/mail", json=data, headers=headers)
        assert r.status_code == 204

        mail = self.read_mock_email()
        body = mail.get("body", "")
        assert "TEST EMAIL BODY" in body

        data["dry_run"] = True
        r = client.post(f"{API_URI}/admin/mail", json=data, headers=headers)
        assert r.status_code == 200

        response = self.get_content(r)
        assert isinstance(response, dict)
        assert "html_body" in response
        assert "plain_body" in response
        assert "subject" in response
        assert "to" in response
        assert "cc" in response
        assert "bcc" in response

        data["dry_run"] = False

        data["body"] = "TEST EMAIL <b>HTML</b> BODY"
        r = client.post(f"{API_URI}/admin/mail", json=data, headers=headers)
        assert r.status_code == 204
        mail = self.read_mock_email()
        body = mail.get("body", "")
        assert "TEST EMAIL <b>HTML</b> BODY" in body

        data["dry_run"] = True
        r = client.post(f"{API_URI}/admin/mail", json=data, headers=headers)
        assert r.status_code == 200

        response = self.get_content(r)
        assert isinstance(response, dict)
        assert "html_body" in response
        assert "plain_body" in response
        assert "subject" in response
        assert "to" in response
        assert "cc" in response
        assert "bcc" in response

        data["dry_run"] = False

        data["body"] = faker.text()
        data["cc"] = faker.pystr()
        r = client.post(f"{API_URI}/admin/mail", json=data, headers=headers)
        assert r.status_code == 400

        data["cc"] = faker.ascii_email()
        r = client.post(f"{API_URI}/admin/mail", json=data, headers=headers)
        assert r.status_code == 204

        data["cc"] = f"{faker.ascii_email()},{faker.pystr()}"
        r = client.post(f"{API_URI}/admin/mail", json=data, headers=headers)
        assert r.status_code == 400

        data["cc"] = f"{faker.ascii_email()},{faker.ascii_email()}"
        r = client.post(f"{API_URI}/admin/mail", json=data, headers=headers)
        assert r.status_code == 204

        data["bcc"] = faker.pystr()
        r = client.post(f"{API_URI}/admin/mail", json=data, headers=headers)
        assert r.status_code == 400

        data["bcc"] = f"{faker.ascii_email()},{faker.pystr()}"
        r = client.post(f"{API_URI}/admin/mail", json=data, headers=headers)
        assert r.status_code == 400

        data["bcc"] = f"{faker.ascii_email()},{faker.ascii_email()}"
        r = client.post(f"{API_URI}/admin/mail", json=data, headers=headers)
        assert r.status_code == 204

        mail = self.read_mock_email()

        body = mail.get("body", "")
        email_headers = mail.get("headers", "")
        assert body is not None
        assert email_headers is not None
        # Subject: is a key in the MIMEText
        assert f"Subject: {data['subject']}" in email_headers
        ccs = mail.get("cc", [])
        assert ccs[0] == data["to"]
        assert ccs[1] == data["cc"].split(",")
        assert ccs[2] == data["bcc"].split(",")
import mlab
from models.customer import Customer
from faker import Faker
from random import randint, choice
from cFake import *
mlab.connect()

fake = Faker()

for i in range(10):
    print(i, "....")
    g = randint(0, 1)
    if g == 0:
        n = female_name()
    elif g == 1:
        n = male_name()
    customer = Customer(name=n,
                        yob=randint(1990, 2001),
                        gender=g,
                        email=fake.ascii_email(),
                        phone=sdt(),
                        address=tp(),
                        job=job(),
                        company=cty(),
                        contacted=choice([True, False]))
    customer.save()
Exemplo n.º 30
0

print("providers.geo".center(100,"="))

print(fake.coordinate())
print(fake.latitude())
print(fake.latlng())
print(fake.local_latlng())
print(fake.location_on_land())
print(fake.longitude())


print("providers.internet".center(100,"="))

print(fake.ascii_company_email())
print(fake.ascii_email())
print(fake.ascii_free_email())
print(fake.ascii_safe_email())
print(fake.company_email())
print(fake.dga())
print(fake.domain_name())
print(fake.domain_word())
print(fake.email())
print(fake.free_email())
print(fake.free_email_domain())
print(fake.hostname())
print(fake.http_method())
print(fake.image_url())
print(fake.ipv4())
print(fake.ipv4_network_class())
print(fake.ipv4_private())