Ejemplo n.º 1
0
    def create_request_2(self):
        # for now create the request_id manually here
        desc = "I need someone to talk to ASAP"
        req = RequestService.create_request(
            "*****@*****.**", ["OPC", "OQC"], "Chat", desc)

        self.assertEqual(req.requester_email, "*****@*****.**")
        self.assertEqual(req.request_type, ["OPC", "OQC"])
        self.assertEqual(req.name, "Chat")
        self.assertEqual(req.description, desc)
Ejemplo n.º 2
0
    def create_request(self):
        # for now create the request_id manually here
        desc = "I need to borrow a Macbook charger for 30 minutes"
        req = RequestService.create_request(
            "*****@*****.**", ["OQE"], "Charger", desc)

        self.assertEqual(req.requester_email, "*****@*****.**")
        self.assertEqual(req.request_type, ["OQE"])
        self.assertEqual(req.name, "Charger")
        self.assertEqual(req.description, desc)

        return req
    def test_cancel_request_by_email(self):

        RequestModel.Request(requester_email="*****@*****.**",
                             request_type=["OPC"],
                             name="Robinson",
                             description="need a ship",
                             time_created=datetime.utcnow).save()

        req4a = RequestService.cancel_request_by_email(
            "*****@*****.**")
        #        req4b = RequestService.cancel_request_by_email("*****@*****.**")

        self.assertTrue(req4a)
    def test_get_request_by_email(self):

        RequestModel.Request(requester_email="*****@*****.**",
                             request_type=["OPC"],
                             name="Humphrey",
                             description="need a movie role",
                             time_created=datetime.utcnow).save()

        req3a = RequestService.get_request_by_email(
            "*****@*****.**")
        #        req3b = RequestService.get_request_by_email("*****@*****.**")

        self.assertEqual(req3a.requester_email, "*****@*****.**")
    def test_i_registered(self):

        UserModel.Profile(email="*****@*****.**",
                          first_name="Amadeus",
                          last_name="Motzart",
                          date_of_birth="1961-01-01",
                          age=59,
                          gender="Male",
                          image_url="abc",
                          description="Musician").save()

        reqaa = RequestService.is_registered("*****@*****.**")
        #        reqab = RequestService.isRegistered("*****@*****.**")

        self.assertTrue(reqaa)
    def test_get_all_user_preferences(self):
        allusers = RequestService.get_all_user_preferences()

        allusers2 = [
            allusers[0].email, allusers[1].email, allusers[2].email,
            allusers[3].email, allusers[4].email, allusers[5].email
        ]
        allusers2.sort()

        self.assertEqual(allusers2[0], "*****@*****.**")
        self.assertEqual(allusers2[1], "*****@*****.**")
        self.assertEqual(allusers2[2], "*****@*****.**")
        self.assertEqual(allusers2[3], "*****@*****.**")
        self.assertEqual(allusers2[4], "*****@*****.**")
        self.assertEqual(allusers2[5], "*****@*****.**")
    def test_complete_request(self):

        RequestModel.Request(requester_email="*****@*****.**",
                             request_type=["OPC"],
                             name="George Foreman",
                             description="need a fight",
                             time_created=datetime.utcnow).save()

        req5a = RequestService.complete_request("*****@*****.**",
                                                "*****@*****.**")

        req5b = RequestModel.Request.objects.get(
            requester_email="*****@*****.**")

        self.assertTrue(req5a)
        self.assertEqual(req5b.acceptor_email, "*****@*****.**")
Ejemplo n.º 8
0
def perform_preference_match():
    data = request.get_json()
    if data is None:
        return jsonify({"warning": "please at least send a json..."})
    try:
        allPrefs = r_service.get_all_user_preferences()
        approach = data["request_type"]
        approach = service_to_pref[approach]
        bonus_list = sort_pref(allPrefs, approach, data["location"])
        # print(bonus_list)
        # TODO: return the corresponding json on Friday
        returned_list = [y for x, y in bonus_list]
        print("bonus")
        print(returned_list)
        new_dict = {
            "email": data["email"],
            "request_type": approach,
            "location": data["location"]
        }
        inv_a_maps = {v: k for k, v in a_maps.items()}
        # print(inv_a_maps)
        # print(sub)
        for key, constraint in sub_category.items():
            print("key: {}, approach: {}".format(key, approach))
            if key == approach:
                for way in constraint:
                    new_dict[inv_a_maps[way]] = True
            else:
                for way in constraint:
                    new_dict[inv_a_maps[way]] = False
        print("new dictionary!")
        print(new_dict)
        returned_list = [
            x for x in returned_list if x["email"] != data["email"]
        ]
        service.update_user_settings(new_dict)
        return jsonify(returned_list[:10]), 200
    except (KeyError, ValueError) as e:
        print("the following key has issue")
        print(e)
        if "location" not in data:
            return jsonify({"warn": "You need a location for matching!"})
        return jsonify([]), 400
    def test_create_request(self):
        # for now create the request_id manually here

        UserModel.Profile(email="*****@*****.**",
                          first_name="Fred",
                          last_name="Arrow",
                          date_of_birth="1960-01-01",
                          age=60,
                          gender="Male",
                          image_url="abc",
                          description="human being").save()

        desc = "I need to borrow a Macbook charger for 30 minutes"
        req1 = RequestService.create_request("*****@*****.**", ["OPC"],
                                             "Fred Arrow", desc,
                                             datetime.utcnow)

        self.assertEqual(req1.requester_email, "*****@*****.**")
        self.assertEqual(req1.request_type, ["OPC"])
        self.assertEqual(req1.name, "Fred Arrow")
        self.assertEqual(req1.description, desc)
    def test_accept_request(self):

        UserModel.Profile(email="*****@*****.**",
                          first_name="Henry",
                          last_name="Eighth",
                          date_of_birth="1961-01-01",
                          age=59,
                          gender="Male",
                          image_url="abc",
                          description="from a movie").save()

        req2 = RequestModel.Request(requester_email="*****@*****.**",
                                    request_type=["OPC"],
                                    name="Zohan",
                                    description="i need audience",
                                    time_created=datetime.utcnow).save()

        req2a = RequestService.accept_request(
            acceptor_user="******",
            request=req2,
            time_accepted=datetime.utcnow)

        self.assertEqual(req2a.acceptor_email, "*****@*****.**")
Ejemplo n.º 11
0
def create_app(test_config=None):
    class Services:
        pass

    app = Flask(__name__)

    CORS(app)

    app.config.from_pyfile("config.py")

    # 테스트 데이터 베이스 업데이트
    if test_config:
        app.config.update(test_config)
    database = create_engine(app.config['DB_URL'],
                             encoding='utf-8',
                             max_overflow=0)
    app.database = database
    # 에러 처리
    app.register_error_handler(KeyError, handle_key_error)
    app.register_error_handler(ValidationError, handle_validation_error)
    app.register_error_handler(LoginError, handle_login_error)

    ## Persistenace Layer
    user_dao = UserDao(database)
    company_dao = CompanyDao(database)
    request_dao = RequestDao(database)
    car_dao = CarDao(database)
    suggestion_dao = SuggestionDao(database)

    ## Business Layer
    services = Services
    services.user_service = UserService(user_dao, company_dao, config,
                                        database)
    services.company_service = CompanyService(company_dao)
    services.request_service = RequestService(request_dao, database)
    services.suggestion_service = SuggestionService(suggestion_dao,
                                                    request_dao, database)

    ## 엔드포인트들을 생성
    create_endpoints(app, services)

    ## 채팅을 위한 socket생성
    socketio = SocketIO(app, cors_allowed_origins='*')

    @socketio.on('connect')
    def connect():
        print('Client connected')
        messages = database.execute("""
        SELECT *
        FROM chats
        """).fetchall()

        messages = [dict(message) for message in messages]

        for message in messages:
            message['created_at'] = str(message['created_at'])

        socketio.emit('message', messages)

    @socketio.on('send_message')
    def handle_message(message):
        request_id = message['request_id']
        name = message['name']
        text = message['text']

        try:
            connection = database.connect()
            trans = connection.begin()

            connection.execute(
                """
            INSERT INTO chats (
                request_id,
                name,
                text
            ) VALUES (
                %s,
                %s,
                %s
                )
            """, (request_id, name, text))

            trans.commit()

        except:
            trans.rollback()

        chat_messages = database.execute("""
        SELECT *
        FROM chats
        """).fetchall()

        messages = [dict(chat_message) for chat_message in chat_messages]

        for msg in messages:
            msg['created_at'] = str(msg['created_at'])

        socketio.emit('message', messages)

    return app
Ejemplo n.º 12
0
def main(repo_name):
    logger.debug('init config')

    config = init_config(repo_name)

    environment = config['environments'][env_name]

    env_key = environment['env_key'][repo_name]

    today = datetime.date.today().strftime('%Y%m%d')

    logger.debug('get today is ' + today)

    git_path = git_folder_path + repo_name

    logger.info('git path is ' + git_path)

    logger.debug('init repo')

    repo = git.Repo.init(path=git_path)

    # Need prune for branch is deleted then created with same name.
    repo.git.fetch('--prune')

    logger.debug('get remote tags')

    all_tag = repo.git.ls_remote('--tags')

    tags = get_tags(all_tag)

    logger.debug('find latest tag')

    tag_re_patten = config['tag_re_patten']

    tag_re_patten = tag_re_patten.format(env_key, today)

    tag_name = find_latest_tag(tag_re_patten, tags)

    if tag_name is None:
        raise TagNotFoundException()

    logger.info('latest tag is ' + tag_name)

    logger.debug('find latest branch')

    branches = repo.git.branch('-r').split('\n')

    merged_branch_name_re_patten = config[
        'merged_branch_name_re_patten'].format(env_key, today)

    latest_branch = find_latest_branch(merged_branch_name_re_patten, branches)

    branch_index = get_branch_index(latest_branch)

    new_branch_name = config['new_branch_name_patten'].format(
        env_key, today, branch_index)

    logger.info('new branch is ' + new_branch_name)

    logger.debug('check branch is exists or not')

    is_exists = some(branches, lambda b: new_branch_name in b)

    if is_exists:
        raise BranchIsExistException(new_branch_name)
    else:
        logger.debug('branch is not exists')

    logger.debug('create branch')

    repo.git.checkout(tag_name, '-b', new_branch_name)

    logger.debug('push branch')

    repo.git.push('origin', new_branch_name)

    logger.debug('checkout to dev')

    repo.git.checkout(source_branch)

    logger.debug('get branch diff commit')

    all_log = repo.git.log(
        'origin/{}..origin/{}'.format(config['uat_branch'], new_branch_name),
        '--oneline', '--no-merges')

    logger.debug('build pull request desc')

    pr_desc = build_pr_desc(all_log)

    logger.debug('create request service')

    request_service = RequestService(config['host'], config['headers'], auth)

    logger.debug('get reviewers')

    uat_branch = config['uat_branch']

    default_reviewers_api = config['default_reviewers_api'].format(repo_name)

    reviewers = get_reviewers(request_service, default_reviewers_api,
                              uat_branch, new_branch_name)

    logger.debug('build pull request obj')

    pr_obj = build_pr_obj(new_branch_name, uat_branch, pr_desc, reviewers)

    logger.debug('post to create pull request')

    pull_requests_api = config['pull_requests_api'].format(repo_name)

    rs = post_pr(request_service, pull_requests_api, pr_obj)

    if rs.status_code != 201:
        logger.error('{} {} create pull request failed.'.format(
            repo_name, new_branch_name))
        status_code = rs.status_code
        result = json.loads(rs.text, encoding='utf-8')
        message = result['errors'][0]['message']
        raise BitbucketException(status_code, message, new_branch_name)

    logger.info('create pull request success.')
    logger.info('finish')
    def test_get_open_requests(self):

        listlen = RequestService.get_open_requests()

        self.assertEqual(len(listlen), 4)