コード例 #1
0
def return_new_users_correctly():
    new_users_correct = [User(name='Edoardo', surname='Casiraghi', birth_date='25/04/1993', birth_place='Merate',
                              instruction_level='University'),
                         User(name='Veronica', surname='Lanzi', birth_date='01/05/1994', birth_place='Lecco',
                              instruction_level='University'),
                         User(name='Danilo', surname='Casiraghi', birth_date='11/10/1961', birth_place='Vimercate',
                              instruction_level='High School'),
                         User(name='Daniela', surname='Bonalume', birth_date='18/02/1963', birth_place='Merate',
                              instruction_level='Middle School')]

    return new_users_correct
コード例 #2
0
def test_step1_empty_checkbox():
    with allure.step('Переход на страницу регистрации'):
        Header().open_register_page().title_text.should(have.exact_text('Регистрация'))
    with allure.step('Ввод корректного незарегистрированного номера 1й чекбокс не отмечен'):
        RegisterPage().register_step1(
            User(phone='9201239746', approve1=0, approve2=1), browser.driver())
    with allure.step('Проверка отсутствия перехода на второй шаг'):
        RegisterPage().code_input.should_not(be.visible)
    with allure.step("Ввод корректного незарегистрированного номера 2й чекбокс не отмечен"):
        RegisterPage().register_step1(
            User(phone='9201239746', approve1=0, approve2=1), browser.driver())
    with allure.step('Проверка отсутствия перехода на второй шаг'):
        RegisterPage().code_input.should_not(be.visible)
コード例 #3
0
ファイル: test_register.py プロジェクト: alpikin63/mir
    def test_step3_uncorrect_email(self):
        with allure.step('Переход на страницу регистрации'):
            Header().open_register_page().title_text.should(
                have.exact_text('Регистрация'))
        with allure.step('Корректно заполненные поля и невалидная почты'):
            RegisterPage().register_step3(
                User(phone='9241239742',
                     approve1=1,
                     approve2=1,
                     sms='1111',
                     email="alpikin",
                     fio="test",
                     data_day="4",
                     data_month="10",
                     data_year="1993",
                     sex="male",
                     password="******",
                     confirm_password="******"), browser.driver())
        with allure.step('Проверка валидации поля e-mail'):
            RegisterPage().email_error.should(
                have.exact_text('Введите корректный email'))

        with allure.step(
                "Проверка отсутствие перехода на сраницу зарегистрированного пользователя"
        ):
            RegisterPage().title_text.should_not(
                have.exact_text('Добро пожаловать!'))
        RegisterPage().check_email('a`lpikin@')
        RegisterPage().check_email('@alpikin')
        RegisterPage().check_email('asd@alpikin')
        RegisterPage().check_email('lpikin.ru')
        RegisterPage().check_email('@lpikin.ru')
        RegisterPage().check_email('asd@lpikin.')
コード例 #4
0
def create() -> Tuple[str, int]:
    """
    create user
    :return:
    """
    data = request.json
    id = data.get("id")
    email = data.get("email")

    user = User.query.filter_by(id=id).first()

    if not user:
        try:
            user = User(id, email)
            user.save()
            response = jsonify(message="User created")
            response.headers["location"] = f"user/{user.id}"
            return response, 201

        except Exception as e:
            response = jsonify(message=str(e))
            return response, 401

    else:
        response = jsonify(message="This user already exists.")
        return response, 422
コード例 #5
0
    def handle_add(self, username: str):
        """
        Handle adding of the user record.

        :param username:
        :return:
        """
        user = db.session.query(User).filter(
            User.username == username).one_or_none()

        if isinstance(user, User):
            return user

        response, userdata = BggApi().get_json('user?name=' + username)

        if not userdata['user']['@id']:
            return {"status": 404}

        user = User(username=userdata['user']['@name'],
                    bgg_id=userdata['user']['@id'])

        user_exists = db.session.query(User).filter(
            User.username == user.username).one_or_none()

        if user_exists:
            return user

        db.session.add(user)
        db.session.commit()

        return user
コード例 #6
0
ファイル: user_test.py プロジェクト: fbritez/consorcio-unido
    def test_initialization(self):
        email = '*****@*****.**'
        name = 'some name'
        user = User(email, name)

        self.assertEqual(user.get_name(), name)
        self.assertEqual(user.get_email(), email)
コード例 #7
0
    def __init__(self):
        global code
        code = 1

        try:

            while code == 1:
                print('\nNew user registration\n')

                name = str(input('Name: '))
                last_name = str(input('Last name: '))

                print('1: admin')
                print('2: common')
                option = str(input('Type of account[admin or common user: '******'1':
                    tp = 'admin'
                else:
                    tp = 'common'

                login = str(input('Login: '******'Password: '******'Email: '))

                new_user = User(name, last_name, tp, email, login, password)

                query = ("INSERT INTO USER (LOGADO, TYPE, LOGIN, PASSWORD, NAME, LASTNAME, EMAIL) VALUES(0, '%s', '%s',"
                         "'%s', '%s', '%s','%s')" % (str(new_user.tp), str(new_user.login), str(new_user.password),
                                                     str(new_user.name), str(new_user.last_name), str(new_user.email)))

                con.insert_data(query)
                code = 0

        except KeyboardInterrupt:
            code = 0
コード例 #8
0
ファイル: user.py プロジェクト: andreugallofre/foodlord
def post():
    body = request.json
    required_parameters = [
        'first_name', 'last_name', 'email', 'username', 'password'
    ]
    if not all(x in body for x in required_parameters):
        return response.build(
            error=True,
            error_message='All request body parameters are required.')

    user = db_session().query(User).filter_by(
        username=body['username']).first()
    if user:
        return response.build(error=True,
                              error_message='The user already exists.')

    user = User(username=body['username'],
                first_name=body['first_name'],
                last_name=body['last_name'],
                email=body['email'],
                password=body['password'])
    db_session().add(user)
    db_session().commit()

    return response.build(error=False, response=user.username)
コード例 #9
0
ファイル: test_register.py プロジェクト: alpikin63/mir
 def test_step3_differents_passwords(self):
     with allure.step('Переход на страницу регистрации'):
         Header().open_register_page().title_text.should(
             have.exact_text('Регистрация'))
     with allure.step(
             'Корректно заполненные поля с разными данными в полях с паролем'
     ):
         RegisterPage().register_step3(
             User(approve1=1,
                  approve2=1,
                  sms='1111',
                  email="*****@*****.**",
                  fio="test",
                  data_day="4",
                  data_month="10",
                  data_year="1993",
                  sex="male",
                  password="******",
                  confirm_password="******",
                  rand=True), browser.driver())
     with allure.step("Проверка вализации поля Повторите пароль"):
         RegisterPage().confirm_password_error.should(
             have.exact_text(
                 'Новый пароль и подтверждение пароля должны совпадать'))
     with allure.step(
             "Проверка отсутствие перехода на сраницу зарегистрированного пользователя"
     ):
         RegisterPage().title_text.should_not(
             have.exact_text('Добро пожаловать!'))
コード例 #10
0
ファイル: mobile_route.py プロジェクト: legendnoz002/fv_flask
def login():
    req_data = request.get_json()

    msg = ""

    if not req_data['username'] or not req_data['password']:
        msg = {"status": {"type": "failure", "message": "somethings is wrong"}}
        return jsonify(msg), 200

    user = User(req_data['username'], req_data['password'], None, None, None)

    if user.check_username():
        if user.check_password(req_data['password']):
            token_data = {'username': user.username, 'admin': user.admin}

            token = jwt.encode(token_data, app.config['SECRET_KEY'])

            return jsonify({
                'token': token.decode('UTF-8'),
                "username": user.username,
                "status": {
                    "type": "success"
                }
            }), 200
        else:
            msg = {"status": {"type": "failure", "message": "wrong password"}}
            return jsonify(msg), 200
    else:
        msg = {"status": {"type": "failure", "message": "user not found"}}
        return jsonify(msg), 200
コード例 #11
0
ファイル: test_register.py プロジェクト: alpikin63/mir
 def test_step3_empty_fieldes(self):
     with allure.step('Переход на страницу регистрации'):
         Header().open_register_page().title_text.should(
             have.exact_text('Регистрация'))
     with allure.step('Ввод корректного номера'):
         RegisterPage().register_step3(
             User(phone='9231239747', approve1=1, approve2=1, sms='1111'),
             browser.driver())
     with allure.step("Проверка валидации поля ИМЯ"):
         RegisterPage().name_error.should(
             have.exact_text('Обязательное поле'))
     with allure.step("Проверка валидации поля E-mail"):
         RegisterPage().email_error.should(
             have.exact_text('Обязательное поле'))
     with allure.step("Проверка валидации поля Придумайте пароль"):
         RegisterPage().password_error.should(
             have.exact_text('Обязательное поле'))
     with allure.step("Проверка валидации поля Повторите пароль"):
         RegisterPage().confirm_password_error.should(
             have.exact_text('Обязательное поле'))
     with allure.step("Проверка валидации поля День"):
         RegisterPage().data_day_error.should(
             have.exact_text('Обязательное поле'))
     with allure.step("Проверка валидации поля Месяц"):
         RegisterPage().data_month_error.should(
             have.exact_text('Обязательное поле'))
     with allure.step("Проверка валидации поля Год"):
         RegisterPage().data_year_error.should(
             have.exact_text('Обязательное поле'))
     with allure.step("Проверка валидации поля Пол"):
         RegisterPage().sex_error.should(
             have.exact_text('Обязательное поле'))
コード例 #12
0
ファイル: test_lk_settings.py プロジェクト: alpikin63/mir
 def test_change_number(self):
     LkMenu().open_settings()
     LkSettingsPage().change_phone_button.click()
     phone = User().phone_generate()
     phone_text = '+7 (' + str(phone)[0:3] + ') ' + str(phone)[3:6] + '-' + str(phone)[6:8]+'-' + str(phone)[8:10]
     ChangePhonePage().change_phone(user=tru_user, phone=phone).user_phone_text.should(have.text(phone_text))
     LkSettingsPage().change_phone_button.click()
     ChangePhonePage().change_phone(user=tru_user, phone=tru_user.phone)
コード例 #13
0
def test_step1_empty_number():
    with allure.step('Переход на страницу регистрации'):
        Header().open_register_page().title_text.should(have.exact_text('Регистрация'))
    with allure.step('Ввод пустого номера'):
        RegisterPage().register_step1(
            User(phone='', approve1=1, approve2=1), browser.driver()).phone_error.should(
            have.exact_text('Введите корректный номер телефона'))
    with allure.step('Проверка отсутствия перехода на второй шаг'):
        RegisterPage().code_input.should_not(be.visible)
コード例 #14
0
def test_step2_uncorrect_code():
    with allure.step('Переход на страницу регистрации'):
        Header().open_register_page().title_text.should(have.exact_text('Регистрация'))
    with allure.step('Ввод корректного номера'):
        RegisterPage().register_step2(
            User(phone='9211239746', approve1=1, approve2=1, sms='q123'), browser.driver()).code_error.should(
            have.exact_text('Введите не менее 4 символов'))
    with allure.step('Проверка отсутствия перехода на третий шаг'):
        RegisterPage().name_input.should_not(be.visible)
コード例 #15
0
def test_init_user_correctly(user):
    name, surname, birth_date, birth_place, instruction_level = user
    u = User(name=name, surname=surname, birth_date=birth_date,
             birth_place=birth_place, instruction_level=instruction_level)
    assert(u.name == name)
    assert(u.surname == surname)
    assert(u.birth_place == birth_place)
    assert(u.birth_date == birth_date)
    assert(u.instruction_level == instruction_level)
    assert(u.age == 27)
コード例 #16
0
ファイル: test_register.py プロジェクト: alpikin63/mir
 def test_step2_empty_code(self):
     with allure.step('Переход на страницу регистрации'):
         Header().open_register_page().title_text.should(
             have.exact_text('Регистрация'))
     with allure.step('Ввод корректного номера'):
         RegisterPage().register_step2(
             User(phone='9221239746', approve1=1, approve2=1, sms=''),
             browser.driver()).code_error.should(
                 have.exact_text('Обязательное поле'))
     with allure.step('Проверка отсутствия перехода на третий шаг'):
         RegisterPage().name_input.should_not(be.visible)
コード例 #17
0
def test_compute_age_from_birth_date(input_birth_date, expected_age):
    user = User(name='Edoardo', surname='Casiraghi', birth_date=input_birth_date,
                birth_place='Merate', instruction_level='University')

    if isinstance(expected_age, int):
        # Compute the age given the birth date of a user
        computed_age = user.compute_age_from_birth_date(birth_date=input_birth_date)
        assert( computed_age == expected_age )
    elif isinstance(expected_age, Exception):
        with pytest.raises(ValueError):
            # Compute the age given the birth date of a user
            user.compute_age_from_birth_date(birth_date=input_birth_date)
コード例 #18
0
def test_convert_date_to_standard_format(input_birth_date, expected_birth_date):
    user = User(name='Edoardo', surname='Casiraghi', birth_date='25/04/1993',
                birth_place='Merate', instruction_level='University')

    if isinstance(expected_birth_date, str):
        # Compute the age given the birth date of a user
        computed_birth_date = user.convert_date_to_standard_format(birth_date=input_birth_date)
        assert(computed_birth_date == expected_birth_date)
    else:
        with pytest.raises(ValueError):
            # Compute the age given the birth date of a user
            _ = user.convert_date_to_standard_format(birth_date=input_birth_date)
コード例 #19
0
ファイル: mobile_route.py プロジェクト: legendnoz002/fv_flask
def register():
    username = request.form.get('username')
    password = request.form.get('password')
    firstname = request.form.get('firstname')
    lastname = request.form.get('lastname')
    ext = request.form.get('ext')
    admin = False

    msg = ""

    if not username or not password:
        msg = {"status": {"type": "failure", "message": "somethings is wrong"}}
        return jsonify(msg), 201

    if 'file' not in request.files:
        msg = {"status": {"type": "failure", "message": "no file part"}}
        return jsonify(msg), 201

    user = User(username=username,
                password=password,
                admin=admin,
                firstname=firstname,
                lastname=lastname)
    file = request.files['file']

    if file.filename == '':
        return jsonify({"msg": "no file selected"}), 201

    found = user.check_username()

    if not found:
        os.chdir(app.config['UPLOAD_FOLDER'])
        msg = {"status": {"type": "success", "message": "username available"}}
        user.set_password(password)
        user.insert()
        try:
            os.mkdir("{foldername}".format(foldername=username))
        except OSError:
            print("fail")

        if file and allowed_file(file.filename):
            _dir = os.path.join(app.config['UPLOAD_FOLDER'],
                                "{foldername}".format(foldername=username))
            file_count = len(os.listdir(_dir)) + 1

            filename = "{0}_{1}.{2}".format(username, file_count, ext)
            file.save(os.path.join(_dir, filename))

        return jsonify(msg), 200
    else:
        msg = {"status": {"type": "failure", "message": "user already exist"}}
        return jsonify(msg), 404
コード例 #20
0
    def test_get_user_data(self):
        mock_dao = Mock()
        email = '*****@*****.**'
        name = 'some name'

        mock_dao.get_all.return_value = User(email, name)

        service = UserService(mock_dao)

        user = service.get_user(email)

        self.assertEqual(user.get_email(), email)
        self.assertEqual(user.get_name(), name)
コード例 #21
0
ファイル: test_register.py プロジェクト: alpikin63/mir
 def test_step1_registred_number(self):
     with allure.step('Переход на страницу регистрации'):
         Header().open_register_page().title_text.should(
             have.exact_text('Регистрация'))
     with allure.step(
             "Проверка повления уведомления о использовании текущего номера"
     ):
         RegisterPage().register_step1(
             User(phone='3777777777', approve1=1, approve2=1),
             driver=browser.driver()).master_error.should(
                 have.exact_text('Такой телефон уже используется'))
     with allure.step('Проверка отсутствия перехода на второй шаг'):
         RegisterPage().code_input.should_not(be.visible)
         allure.attach.file('', attachment_type=allure.attachment_type.PNG)
コード例 #22
0
 def post(self):
     try:
         body = request.get_json()
         user = User(**body)
         user.hash_password()
         user.save()
         id = user.id
         return {'id': str(id)}, 200
     except FieldDoesNotExist:
         raise SchemaValidationError
     except NotUniqueError:
         raise EmailAlreadyExistsError
     except Exception as e:
         raise InternalServerError
コード例 #23
0
 def test_login_password_empty(self):
     with allure.step('Переход на страницу авторизации'):
         Header().open_login_page().title_name.should(
             have.exact_text('Вход'))
     with allure.step('Ввод несуществующего номера и пароля'):
         LoginPage().login(User())
     with allure.step('Проверка валидации поля Телефон'):
         LoginPage().input_error_blocks[0].element(
             LoginPage().error_text).should(
                 have.exact_text('Обязательное поле'))
     with allure.step('Проверка валидации поля Пароль'):
         LoginPage().input_error_blocks[1].element(
             LoginPage().error_text).should(
                 have.exact_text('Обязательное поле'))
     with allure.step('Проверка неавторизованности пользователя'):
         Header().user_name_button.should_not(be.enabled)
         browser.driver().refresh()
         Header().user_name_button.should_not(be.enabled)
コード例 #24
0
def add_user():
    # Get a connection to the test SQLite database
    dao_handler = _get_dao_handler()

    # Get the data received by HTTP POST request
    request_data = json.loads(request.data)
    if len(request_data) == 0:
        raise ValueError('ERROR: no data have been received.')

    # Create a User object with the information about him/her passed by HTTP request
    u = User(name=request_data['name'],
             surname=request_data['surname'],
             birth_date=request_data['birth_date'],
             birth_place=request_data['birth_place'],
             instruction_level=request_data['instruction_level'])

    # Add the user to the SQLite database and retrieve the ID automatically assigned to him/her
    user_id = dao_handler.add_row_into_table(object=u, table_name='users')

    return jsonify({'text': 'The user has been added to SQLite database with ID auto-generated' +\
                            ' equal to "{}".'.format(user_id)}), 201
コード例 #25
0
def register():
    req_data = request.get_json()
    username = req_data['username']
    password = req_data['password']
    admin = False

    msg = ""

    if not username or not password:
        msg = {"status": {"type": "failure", "message": "somethings is wrong"}}
        return jsonify(msg), 200

    user = User(username=username, password=password, admin=admin)

    found = user.check_username()

    if not found:
        msg = {"status": {"type": "success", "message": "username available"}}
        user.set_password(password)
        user.insert()
        return jsonify(msg), 200
    else:
        msg = {"status": {"type": "failure", "message": "user already exist"}}
        return jsonify(msg), 401
コード例 #26
0
ファイル: user.py プロジェクト: felixarpa/unstuckoverflow
def post():
    try:
        body = request.json
        required_parameters = [
            'full_name', 'email', 'password', 'phone_number'
        ]
        if not all(x in body for x in required_parameters):
            return jsonify(
                error=True,
                message='All request body parameters are required.'), 400

        username, domain = body['email'].lower().split('@')
        company = domain.split('.')[0]
        if company in NO_COMPANY_EMAILS:
            return jsonify(
                error=True,
                message='Specified email is not a company email.'), 400

        user = db_session().query(User).filter_by(username=username,
                                                  company=company).first()
        if user:
            return jsonify(error=True, message='The user already exists.'), 400

        user = User(username=username,
                    company=company,
                    full_name=body['full_name'],
                    email=body['email'],
                    password=body['password'],
                    phone_number=body['phone_number'])
        db_session().add(user)
        db_session().commit()

        return jsonify(error=False, response=user.serialize()), 200
    except Exception as e:
        log.error('Unexpected error in POST/user: {}'.format(e))
        return jsonify(error=True, message='Unexpected error.'), 400
コード例 #27
0
ファイル: mongo_DAO.py プロジェクト: fbritez/consorcio-unido
 def create_model(self, element):
     return User(element.get('email'), element.get('name'))
コード例 #28
0
 def addUsers(self):
     user = User('John Doe', '*****@*****.**')
     db.session.add(user)
     db.session.commit()
コード例 #29
0
def fill_database():
    with open(args.input_file, newline='') as f:
        trips = [row[1] for row in enumerate(csv.reader(f))][1:]
    log.info('Trips: {}'.format(len(trips)))

    trips = [
        trip for trip in tqdm.tqdm(trips, total=len(trips))
        if trip[8] == args.system_name
    ]
    log.info('Trips of Barcelona: {}'.format(len(trips)))

    input_dict = {}
    for trip in tqdm.tqdm(trips, total=len(trips)):
        user_id = trip[7]
        if user_id not in input_dict:
            input_dict[user_id] = []
        input_dict[user_id].append(trip)
    log.info('Users of Barcelona: {}'.format(len(input_dict)))

    input_dict_items = input_dict.items()
    for user_id, trips in tqdm.tqdm(input_dict_items,
                                    total=len(input_dict_items)):
        user_id = int(user_id)
        user = db_session().query(User).filter_by(id=user_id).first()
        if not user:
            random_personality = random_api.get_random_personality()
            if random_personality:
                try:
                    full_name = '{} {}'.format(
                        random_personality['name']['first'],
                        random_personality['name']['last'])
                    image_url = random_personality['picture']['large']
                    user = User(id=user_id,
                                full_name=full_name,
                                image_url=image_url,
                                points=0)
                    db_session().add(user)
                    db_session().flush()
                    db_session().commit()
                    success = True
                except Exception as e:
                    log.warn('Skipping user creation due to: [{}]'.format(e))
                    success = False
                if success:
                    for t in trips:
                        try:
                            trip = Trip(
                                id=int(t[0]),
                                start_point_lat=float(t[1]),
                                start_point_lon=float(t[2]),
                                end_point_lat=float(t[3]),
                                end_point_lon=float(t[4]),
                                started_at=date.to_string(t[5]),
                                ended_at=date.to_string(t[6]),
                                system_name=t[8],
                                vehicle_external_id=t[9],
                                duration_in_seconds=float(t[10]),
                                billable_duration_in_seconds=int(t[11]),
                                first_checkout_attempt_at=date.to_string(
                                    t[12]),
                                first_checkout_attempt_error=None
                                if not t[13] else t[13],
                                first_checkout_attempt_error_details=None
                                if not t[14] else t[14],
                                first_checkout_attempt_id=int(t[15]),
                                first_checkout_attempt_state=t[16],
                                last_checkout_attempt_at=date.to_string(t[17]),
                                last_checkout_attempt_error=None
                                if not t[18] else t[18],
                                last_checkout_attempt_error_details=None
                                if not t[19] else t[19],
                                last_checkout_attempt_id=int(t[20]),
                                last_checkout_attempt_state=t[21],
                                first_odometer_in_meters=int(t[22]),
                                last_odometer_in_meters=int(t[24]),
                                pause_duration_in_seconds=float(t[27]),
                                reservation_at=date.to_string(t[28]),
                                user_id=user_id)
                            db_session().add(trip)
                            db_session().flush()
                        except Exception as e:
                            log.warn(
                                'Skipping trip creation due to: [{}]'.format(
                                    e))
                            db_session().rollback()
                    db_session().commit()
                else:
                    db_session().rollback()
            else:
                log.warn(
                    'Skipping user creation for user_id: {}'.format(user_id))
コード例 #30
0
ファイル: conftest.py プロジェクト: alpikin63/mail_test
def data_users():
    tru_user = User(login='******', password='******', domain=1)
    return tru_user