def create_group():
    payload = request.get_json()
    new_group = Group(description=payload.get('description',None),
                      company_id=payload.get('companyId',None))
    #TODO: Add validation of request before hitting the database
    created_group = Group.add(db.session, new_group)
    return jsonify(created_group.serialize)
Example #2
0
def test_get_groups_from_user(app, test_client, api_headers_bearer, insert_tokens):
    password = "******"

    user = User(first_name="Max",
                last_name="Muster",
                email="*****@*****.**",
                password=password)

    user = insert_user(user)
    tokens = insert_tokens(user.email)

    group1_member = GroupMember(user=user)

    group1 = Group(name="group1", group_members=[group1_member])
    insert_group(group1)

    group2_member = GroupMember(user=user)

    group2 = Group(name="group2", group_members=[group2_member])
    insert_group(group2)

    response = test_client.get("/groups",
                               headers=api_headers_bearer(
                                   tokens["access_token"]["token"]))
    json_respone = json.loads(response.get_data(as_text=True))

    assert response.status_code == 200

    assert json_respone["message"] == "Returned groups"

    assert len(json_respone["groups"]) == 2
    assert json_respone["groups"][0]["name"] == group1.name
    assert json_respone["groups"][1]["name"] == group2.name
def get_groups(group_id=None):
    if group_id is not None:
        group = Group.get(db.session, group_id)
        return jsonify(group.serialize) if group is not None else {}
    else:
        groups = Group.get(db.session, group_id)
        return jsonify([group.serialize for group in groups])
Example #4
0
 def add_route(gid, routes):
     with db.auto_commit():
         Group.get_or_404(id=gid, msg='无指定权限组')
         for route_id in routes:
             Route.get_or_404(id=route_id, msg='无指定路由节点')
             Menu.abort_repeat(group_id=gid, route_id=route_id)
             Menu.create(group_id=gid, route_id=route_id)
Example #5
0
def initial_fill(application):

    user1 = UserProfile(name="Darya", email="*****@*****.**", password_hash="qwerty")
    user1.hash_password("qwerty")

    user2 = UserProfile(name="user2", email="*****@*****.**", password_hash="cat")
    user2.hash_password("cat")

    application.session.add_all([user1, user2])


    group1 = Group(name="latexfauna",
                   description="""Once upon a time, Kievskie Hipstery zatsenili our
                    music and Latexfauna became a popular band, despite of its 
                    zaunylaya and odnotipnaya musica. Ha-ha-ha we thought.
                    Nihuya sebe we thought.""",
                   official_site="https://www.facebook.com/latexfauna")

    group2 = Group(name="IAMX",
                   description="""IAMX is the solo musical project of Chris Corner,
                    formerly of the band Sneaker Pimps. Founded in 2004 in London,
                     it is an independent music project which also focuses on and 
                     experiments with visual art.[1] Musically, IAMX spans multiple
                      genres from electronic rock and dance music to 
                      burlesque-influenced songs and emotional ballads. Corner's 
                      striking and wide-ranging voice, and his way of programming 
                      sounds and beats, make up the obvious characteristic of the 
                      IAMX sound.""",
                   official_site="http://iamxmusic.com/")

    application.session.add_all([group1, group2])

    song1 = Song(title="LIME",
                 text="""Мене в тобі всьо устраює\nОсобливо липень\nОсобливо липень\nБасейн клоне на сон\nЯ багато випив\nЯ багато випив\nІ лайм\nІ лаймові небеса\nІ лайм\nІ лаймові небеса\nМене всьо устраює\nШо ти людина\nНайнебезпечніший в світі звір\nНаші теплі новини\nНалежать лише мені\nЛа-ла-ла\nЛа-ла-ла\nІ ми крісіві\nУ світлі лаймових небес\nІ нас розум\nЯдерний процес\nМене в тобі всьо устраює\nОсобливо липень\nОсобливо липень\nБасейн клоне на сон\nЯ багато випив\nЯ багато випив\nІ лайм\nІ лаймові небеса\nІ лайм\nІ лаймові небеса\nМене всьо устраює\nШо я людина\nНайбезпорадніший в світі звір\nЯ безсмертна дитина\nІ я багато чого хотів\nІ мав, мав, мав\nЛав, лав, лав\nОдна й та сама штука\nПозаду твоїх і моїх очей\nДивиться на вічність\nТрогатєльних речей\nМене в тобі всьо устраює\nОсобливо липень\nОсобливо липень\nБасейн клоне на сон\nЯ багато випив\nЯ багато випив\nІ лайм\nІ лаймові небеса\nІ лайм\nІ лаймові небеса\nМене всьо устраює\nОсобливо липень\nОсобливо липень""",
                 year="2017",
                 youtube_link="https://www.youtube.com/watch?v=-UqKwEEkX2s",
                 group_id=1)

    song2 = Song(title="Exit",
                 text="""Hold me like you mean it\nTonight I need to feel your skin on my skin\nOften I forget you’re this being\nI get lost alone online, stalking humanity\nThe world is collapsing\nThe world is indifferent\nCan you feel it\nThe communication\nInside this room?\nWe are infinite\nSo let the hurricane come blow me down\nDown to the mountain where I will scream to be found\nThe sky has opened up and now I’m overcome\nWith all the information, the universe, the atom""",
                 year="2018",
                 youtube_link="https://www.youtube.com/watch?v=m35fDh_3Ay4",
                 group_id=1)

    application.session.add_all([song1, song2])
    application.session.commit()


# "You know I love it when you're down on your knees\nAnd I'm a junkie for the way that you please\nYou shut me up when you swallow me down\nMy back to the wall you're going to town\nI almost told you that I loved you\nThank God I didn't 'cause it would have been a lie\nI say the damnedest things when you're on top of me\nI almost told you that I loved you\nI hate to say it but it has to be said\nYou look so fragile as I f**k with your head\nI know it shouldn't but it's getting me on\nIf sex is the drug then what is the cost?\nI almost told you that I loved you\nThank God I didn't 'cause it would have been a lie\nI say the damnedest things when you're on top of me\nI almost told you that I loved you\nI'm not the one that you want\nNot the one that you need\nMy love…"
#
# "I tear my heart open\nI sew myself shut\nMy weakness is\nThat I care too much\nMy scars remind us\nThat the past is real\nI tear my heart open\nJust to feel\nDrunk and I'm feeling down\nAnd I just want to be alone\nI'm pissed cause you came around\nWhy don't you just go home\n'Cause you channel all your pain\nAnd I can't help you go fix yourself\nYour making me insane\nAll I can say is\nI tear my heart open\nI sew myself shut\nMy weakness is\nThat I care too much\nOur scars remind us\nThat the past is real\nI tear my heart\nOpen just to feel\nI tried to help you once\nAgainst my own advice\nI saw you going down\nBut you never realized\nThat your drowning in the water\nSo I offered you my hand\nCompassion's in my nature\nTonight is our last stand\nI tear my heart open\nI sew myself shut\nMy weakness is\nThat I…"
#
# "Salute the sun, I've been sitting here all night long\nHauling rock over Buddha with the Longhorn\nGot a hole, rip a pocket off my uniform\nWith the Blackwatch Boys get your heads down\nDuty calls but it is way too late I'm too far gone\nWaiting for Godot, hell with my pants down\nCracked the stash sent me crying in the midday sun\nI miss my dog and I miss my freedom\nI don't know why they are calling on the radio\nThey know I'm here just out of sight\nI don't know why they're calling on the radio\nHe's by my side and I know I'm right\nI don't know why they are calling on the radio\nThey know I'm here just out of sight\nI don't know why they're calling on the radio\nHe's by my side and I know I'm right\nI hate the things I think about you when I'm all alone\nI know you're tough but I've been gone for so long\nI play the memories of you inside my head\nSo all those pictures of us burn and radiate\nWatch the clouds and I'm falling, falling through the cracks\nHead beats and the heart is pounding fast\nOff the ground into the starry dark\nInto your arms I'm falling\nI'm falling, I'm falling\nI don't know why they are calling on the radio\nThey know I'm here just out of sight\nI don't know why they're calling on the radio\nHe's by my side and I know I'm right\nI don't know why they are calling on the radio\nThey know I'm here just out of sight\nI don't know why they're calling on the radio\nHe's by my side and I know I'm right\nMy brain, my body's fried\nI've got to stay alive\nI've got to take a chance and keep on moving\nKeep on moving\nI don't know why they are calling on the radio\nThey know I'm here just out of sight\nDon't know why they're calling on the radio\nHe's by my side and I know I'm right\nDon't know why they are calling on the radio\nIt's on my side and I know I'm right\nI don't know why they are calling on the radio\nIt's on my side and I know I'm alright\nI see your light from miles away\nI see your light from miles away"
#
# "I'm only happy when it rains\nI'm only happy when it's complicated\nAnd though I know you can't appreciate it\nI'm only happy when it rains\nYou know I love it when the news is bad\nWhy it feels so good to feel so sad?\nI'm only happy when it rains\nPour your misery down\nPour your misery down on me\nPour your misery down\nPour your misery down on me\nI'm only happy when it rains\nI feel good when things are goin' wrong\nI only listen to the sad, sad songs\nI'm only happy when it rains\nI only smile in the dark\nMy only comfort is the night gone black\nI didn't accidentally tell you that\nI'm only happy when it rains\nYou'll get the message by the time I'm through\nWhen I complain about me and you\nI'm only happy when it rains\nPour your misery down (Pour your misery down)\nPour your misery down on me\nPour your misery down (Pour your misery down)\nPour your misery down on me\nPour your misery down (Pour your misery down)\nPour your misery down on me\nPour your misery down\nYou can keep me company\nAs long as you don't care\nI'm only happy when it rains\nYou wanna hear about my new obsession?\nI'm riding high upon a deep depression\nI'm only happy when it rains\nPour some misery down on me\nI'm only happy when it rains\nPour some misery down on me\nI'm only happy when it rains\nPour some misery down on me\nI'm only happy when it rains\nPour some misery down on me\nI'm only happy when it rains\nPour some misery down on me\nPour some misery down on me\nPour some misery down on me\nPour some misery down on me\nPour some misery down on me\nPour some misery down on me"
#
# "Ми наробили кіборгів\nУ красівому бункері\nІ пишемо про них книжки\nБо ми дослідники\nА ти дослідниця\nПротирай очки\nА я зломав олівця\nТак собі факт\nНо ти мені нравишся\nТи мені нравишся\nТи мені нравишся\nТи мені нравишся\nТи закидаєш волоси\nТи откриваєшся\nА я усе січу\nСвою напарніцу\nТи така умніца\nУ тебе всьо схвачено\nА я нахуячений\nТак собі факт\nНо ти мені нравишся\nТи мені нравишся\nТи мені нравишся\nТи мені нравишся\nМи наробили кіборгів\nУ красівому бункері\nІ пишемо про них книжки\nБо ми дослідники\nМи наробили кіборгів\nУ красівому бункері\nІ пишемо про них книжки\nБо ми дослідники\nА ти дослідниця"
Example #6
0
def add_group(name):
    gr = Group.select().where(Group.groupname == name)
    if len(gr) == 0:
        row = Group(groupname=name)
        row.save()
        req = (f'Создана группа {name}')
        return req
    else:
        req = (f'Группа {name} уже создана')

    return req
Example #7
0
  def groups_to_model(self, groups):
    data = self.prepare_json_from(groups)
    groups = []

    for groupJson in data:
      group = Group()
      group.id = int(groupJson['id'])
      group.name = groupJson['name']
      group.faculty = groupJson['faculty']
      groups.append(group)

    return groups
Example #8
0
    def groups_to_model(self, groups):
        data = self.prepare_json_from(groups)
        groups = []

        for groupJson in data:
            group = Group()
            group.id = int(groupJson['id'])
            group.name = groupJson['name']
            group.faculty = groupJson['faculty']
            groups.append(group)

        return groups
Example #9
0
def test_get_all_groups(app):
    g1 = Group(name="G1")
    g2 = Group(name="G2")

    insert_group(g1)
    insert_group(g2)

    groups = get_all_groups()

    assert len(groups) == 2
    assert groups[0].name == g1.name
    assert groups[1].name == g2.name
Example #10
0
def init_auth_group(app):
    '''
    默认的权限组,必须存在于数据库, 项目启动后自动导入。
    '''
    from app.models.group import Group as GroupModel
    auth_groups = app.config['AUTH_GROUPS']
    for key, value in auth_groups.items():
        group = GroupModel.get(name=value.name)
        if not group:
            group = GroupModel.create(name=value.name, info=value.info)
        value = value._replace(id=str(group.id))
        app.config['AUTH_GROUPS'][key] = value
Example #11
0
def create_group(name, label):
    """
    设置用户分组
    :param name:
    :param label:
    :return:
    """
    with db.auto_commit():
        group = Group()
        group.name = name
        group.label = label
        db.session.add(group)
    print("成功创建用户分组:%s " % (name, ))
Example #12
0
def test_get_just_groups_from_user(app, test_client, api_headers_bearer, insert_tokens):
    password = "******"

    user1 = User(first_name="Max",
                 last_name="Muster",
                 email="*****@*****.**",
                 password=password)
    user1 = insert_user(user1)
    user1_tokens = insert_tokens(user1.email)

    user2 = User(first_name="Max",
                 last_name="Muster",
                 email="*****@*****.**",
                 password=password)
    user2 = insert_user(user2)
    user2_tokens = insert_tokens(user2.email)

    group1_member1 = GroupMember(user=user1)
    group1 = Group(name="group1",
                   group_members=[group1_member1])

    group2_member1 = GroupMember(user=user1)
    group2_member2 = GroupMember(user=user2)
    group2 = Group(name="group2",
                   group_members=[group2_member1, group2_member2])

    group3_member2 = GroupMember(user=user2)
    group3 = Group(name="group3",
                   group_members=[group3_member2])

    group1 = insert_group(group1)
    group2 = insert_group(group2)
    group3 = insert_group(group3)

    response = test_client.get("/groups",
                               headers=api_headers_bearer(
                                   user1_tokens["access_token"]["token"]))
    json_respone = json.loads(response.get_data(as_text=True))

    assert len(json_respone["groups"]) == 2
    assert json_respone["groups"][0]["name"] == group1.name
    assert json_respone["groups"][1]["name"] == group2.name

    response = test_client.get("/groups",
                               headers=api_headers_bearer(
                                   user2_tokens["access_token"]["token"]))
    json_respone = json.loads(response.get_data(as_text=True))

    assert len(json_respone["groups"]) == 2
    assert json_respone["groups"][0]["name"] == group2.name
    assert json_respone["groups"][1]["name"] == group3.name
Example #13
0
def create_group():
    jsonData = request.get_json()
    with db.auto_commit():
        group = Group()
        group.group_name = jsonData['group_name']
        group.league_id = jsonData['league_id']
        db.session.add(group)
        for gt in jsonData['group_team']:
            db.session.flush()
            group_team = Group_team()
            group_team.group_id = group.group_id
            group_team.league_id = jsonData['league_id']
            group_team.team_id = gt['team_id']
            db.session.add(group_team)
    return Success(msg='新增小组成功')
def test_dont_add_user_if_user_id_missing(test_client, api_headers_bearer,
                                          insert_tokens):
    password = "******"

    user = User(first_name="Max",
                last_name="Muster",
                email="*****@*****.**",
                password=password)
    user = insert_user(user)
    user_tokens = insert_tokens(user.email)

    group = Group(name="Group")
    insert_group(group)

    group_add_user_data = {"bla": "bla"}

    response = test_client.post("/groups/{}/members".format(group.id),
                                headers=api_headers_bearer(
                                    user_tokens["access_token"]["token"]),
                                data=json.dumps(group_add_user_data))
    json_response = json.loads(response.get_data(as_text=True))

    assert response.status_code == 400
    assert json_response["message"] == "Missing attribute email"
    assert len(group.group_members) == 0
Example #15
0
def test_change_name_of_existing_group(test_client, api_headers_bearer, insert_tokens):
    password = "******"
    user = User(first_name="Max",
                last_name="Muster",
                email="*****@*****.**",
                password=password)
    insert_user(user)
    tokens = insert_tokens(user.email)
    group = Group(name="Name", group_members=[GroupMember(user=user)])
    insert_group(group)

    data = {
        "id": group.id,
        "name": "Changed",
        "members": [{"id": user.id}]
    }

    response = test_client.put("/groups/{}".format(group.id),
                               headers=api_headers_bearer(
                                   tokens["access_token"]["token"]),
                               data=json.dumps(data))
    json_response = json.loads(response.get_data(as_text=True))

    assert response.status_code == 200
    assert json_response["message"] == "Edited group"
    assert group.name == data["name"]
def test_add_not_registered_user_to_group_if_user_already_created(
        test_client, api_headers_bearer, insert_tokens):
    password = "******"

    user1 = User(first_name="Max",
                 last_name="Muster",
                 email="*****@*****.**",
                 password=password)
    user1 = insert_user(user1)
    user1_tokens = insert_tokens(user1.email)

    new_user_email = "*****@*****.**"
    insert_user(User(email=new_user_email))

    group_member1 = GroupMember(user=user1)
    group = Group(name="Muster", group_members=[group_member1])
    insert_group(group)

    group_add_user_data = {"email": new_user_email}

    response = test_client.post("/groups/{}/members".format(group.id),
                                headers=api_headers_bearer(
                                    user1_tokens["access_token"]["token"]),
                                data=json.dumps(group_add_user_data))
    json_response = json.loads(response.get_data(as_text=True))

    assert response.status_code == 201
    assert json_response["message"] == "Added user to group"

    group = get_group_by_id(group.id)

    assert len(group.group_members) == 2
def test_dont_add_user_if_user_not_exist(test_client, api_headers_bearer,
                                         insert_tokens):
    password = "******"

    user = User(first_name="Max",
                last_name="Muster",
                email="*****@*****.**",
                password=password)
    user = insert_user(user)
    tokens = insert_tokens(user.email)

    group_member = GroupMember(user=user)
    group = Group(name="Group", group_members=[group_member])
    insert_group(group)

    group_add_user_data = {
        "user_id": 2,
    }

    response = test_client.post("/groups/{}/members".format(group.id),
                                headers=api_headers_bearer(
                                    tokens["access_token"]["token"]),
                                data=json.dumps(group_add_user_data))
    json_response = json.loads(response.get_data(as_text=True))

    assert response.status_code == 400
    assert json_response["message"] == "User does not exist"
    assert len(get_all_users()) == 1
Example #18
0
def delete_group(arg_id):
    gr = Group.get_by_id(arg_id)
    oldname = gr.groupname
    stud_in_gr = Student.stud_select(arg_id)
    if len(stud_in_gr) == 1 and stud_in_gr[0][0] == 0:
        result = Group.delete_by_id(arg_id)
        if result != 0:
            req = f'группа {oldname} успешно удалена'
    else:
        req = 'Невозможно удалить группу т.к. в ней есть студенты: '
        st = ''
        for s in stud_in_gr:
            if s[0] != 0:
                st = f'{st} {s[1]}; '
        req = f'{req} {st} '
    return req
Example #19
0
def studentform():
    gr = Group.gr_select()
    arg_id = request.args.get('id')
    if arg_id is not None:
        stud = Student.get_by_id(arg_id)
        form = StudentForm(request.form or None, obj=stud)
        form.group.choices = gr
        form.group.data = stud.group.id
    else:
        form = StudentForm(request.form or None)
        form.group.choices = gr

    if request.method == 'POST' and form.validate():
        studinfo = get_stud_info(form)
        if arg_id is not None:
            req = update_stud(stud, studinfo)
        else:
            req = add_student(studinfo)
        flash(req)
        return redirect(url_for('students.get_students'))
    else:
        elsereq = render_template('studentform.html',
                                  form=form,
                                  title='Изменить студента')
        return elsereq
Example #20
0
def groupform():
    arg_id = request.args.get('id')
    if arg_id is not None:
        group = Group.get_by_id(arg_id)
        form = GroupForm(request.form or None, obj=group)
        stud = Student.stud_select(arg_id)
        form.star.choices = stud
        if group.starosta is not None:
            form.star.data = group.starosta.id
        else:
            form.star.data = 0
        title = 'Изменить группу'
    else:
        group = None
        form = GroupForm(request.form or None)
        #без этого не отрабатывала валидация. ругалость, что не выбран староста
        form.star.choices = [(0,'')]
        form.star.data = 0
        #
        title = 'Добавить группу'
    
    if request.method == 'POST' and form.validate():
        if arg_id is not None:
            req = update_group(group, form.groupname.data, form.star.data)
        else:
            req = add_group(form.groupname.data)
        flash(req)
        return redirect(url_for('groups.get_groups'))
    else:
        return render_template('groupform.html', group=group, 
                    form=form, title=title)
Example #21
0
 def test_formats_group_data(self):
     data = {'group_name': 'bob', 'group_color': 'red'}
     user = Mock()
     user.data = {}
     message = Clue(text='Hello {group_name}, you like {group_color}?')
     response = format_message(message, user, Group(data=data))
     self.assertEqual('Hello bob, you like red?', response.text)
Example #22
0
    def get_routes(gid: int) -> dir:
        id2route_node = {
            route.id: dict(route)
            for route in Group.get_or_404(id=gid).route
        }
        id2route_node_clone = id2route_node.copy()

        def add_parent_node(cur_route_node):
            if cur_route_node['parent_id'] == cur_route_node['id'] == 0:
                pass
            else:
                if not (cur_route_node['parent_id'] in id2route_node.keys()
                        or cur_route_node['parent_id'] == 0):
                    parent_route = Route.get_or_404(
                        id=cur_route_node['parent_id'])
                    id2route_node_clone[parent_route.id] = dict(parent_route)
                    add_parent_node(dict(parent_route))

        for route_node in id2route_node.values():
            add_parent_node(route_node)

        t = RouteTree(RouteNode)
        t.generate_by_list(
            [route_node for route_node in id2route_node_clone.values()])
        return t.serialize()['children']
Example #23
0
def test_error_on_user_not_member_of_group(test_client, api_headers_bearer, insert_tokens):
    password = "******"
    user1 = User(first_name="Max",
                 last_name="Muster",
                 email="*****@*****.**",
                 password=password)
    insert_user(user1)

    user2 = User(first_name="Max",
                 last_name="Muster",
                 email="*****@*****.**",
                 password=password)
    insert_user(user2)
    user2_tokens = insert_tokens(user2.email)
    group = Group(name="Name", group_members=[GroupMember(user=user1)])
    insert_group(group)

    data = {
        "id": group.id,
        "name": "Changed",
        "members": [{"id": user1.id}]
    }

    response = test_client.put("/groups/{}".format(group.id),
                               headers=api_headers_bearer(
                                   user2_tokens["access_token"]["token"]),
                               data=json.dumps(data))
    json_response = json.loads(response.get_data(as_text=True))

    assert response.status_code == 401
    assert json_response["message"] == "Group does not exist"
    assert group.name == "Name"
def test_dont_delete_user_if_not_in_group(test_client, api_headers_bearer,
                                          insert_tokens):
    password = "******"

    user1 = User(first_name="Max",
                 last_name="Muster",
                 email="*****@*****.**",
                 password=password)
    user1 = insert_user(user1)
    user1_tokens = insert_tokens(user1.email)

    user2 = User(first_name="Max",
                 last_name="Muster",
                 email="*****@*****.**",
                 password=password)
    user2 = insert_user(user2)

    group_member1 = GroupMember(user=user1)
    group = Group(name="Muster", group_members=[group_member1])
    insert_group(group)

    response = test_client.delete(
        "/groups/{}/members/{}".format(group.id, user2.id),
        headers=api_headers_bearer(user1_tokens["access_token"]["token"]))
    json_response = json.loads(response.get_data(as_text=True))

    assert response.status_code == 401
    assert json_response["message"] == "Group does not exist"
    assert group_member1.valid == 1
    assert len(group.group_members) == 1
Example #25
0
    def create_new_group(self, user, **kwargs):
        logging.info(
            "Creating a group for user {user_id}".format(user_id=user.id))
        name = kwargs.get("name")
        if len(name) > 25:
            e = GROUP_NAME_TOO_LONG_500
            return e, 500
        pic_url = kwargs.get("pic_url", "")
        description = kwargs.get("description", "")

        group = Group(user, name, pic_url, description)

        db.session.add(group)
        db.session.commit()

        user_group = UserGroup(user, group)
        db.session.add(user_group)
        db.session.commit()

        d = dict()
        d['group_id'] = group.id
        d['name'] = group.name
        d['pic_url'] = group.pic_url
        d['description'] = group.description
        d['creator_id'] = group.creator_id
        d['creator_fb_id'] = str(user.fb_id)

        return d, 200
def add_group(group_name, group_de):
    session = baseDao.get_session()
    g = Group()
    g.group_uuid = uuid.uuid4()
    g.group_name = group_name
    g.group_de = group_de
    g.created_ts = datetime.now()
    g.private_fl = False
    g.group_type_cd = 'SP'
    return groupDao.add_group(session, g)
Example #27
0
def test_group_member_is_allowed_to_modify_bill(test_client,
                                                api_headers_bearer,
                                                insert_tokens):
    password = "******"
    now = datetime.datetime.utcnow()

    user1 = User(first_name="Max",
                 last_name="Muster",
                 email="*****@*****.**",
                 confirmed=True,
                 password=password)
    insert_user(user1)

    user2 = User(first_name="Max",
                 last_name="Muster",
                 email="*****@*****.**",
                 confirmed=True,
                 password=password)
    insert_user(user2)

    user3 = User(first_name="Max",
                 last_name="Muster",
                 email="*****@*****.**",
                 confirmed=True,
                 password=password)
    insert_user(user3)
    user3_tokens = insert_tokens(user3.email)

    group = Group(
        name="Group",
        group_members=[GroupMember(user=user1),
                       GroupMember(user=user3)])
    insert_group(group)

    bill_member1 = BillMember(user_id=user1.id, amount="5.00")
    bill_member2 = BillMember(user_id=user2.id, amount="-5.00")

    bill1 = Bill(description="Bill",
                 date=now,
                 date_created=now,
                 group=group,
                 members=[bill_member1, bill_member2])
    bill_id = insert_bill(bill1).id

    data = {"description": "New"}

    response = test_client.put("/bills/{}".format(bill_id),
                               headers=api_headers_bearer(
                                   user3_tokens["access_token"]["token"]),
                               data=json.dumps(data))
    json_response = json.loads(response.get_data(as_text=True))

    bill = get_bill_by_id(bill_id)

    assert response.status_code == 200
    assert json_response["message"] == "Updated bill"
    assert bill.description == data["description"]
Example #28
0
 def update_group(id, name, info):
     '''
     :param id: 权限组id
     :param name: 权限组名
     :param info: 权限组名描述
     :return:
     '''
     group = Group.get_or_404(id=id, msg='分组不存在,更新失败')
     group.update(name=name, info=info)
Example #29
0
def test_add_bill_in_group(app, test_client, api_headers_bearer,
                           insert_tokens):
    password = "******"
    now = datetime.datetime.utcnow()

    user1 = User(first_name="Max",
                 last_name="Muster",
                 email="*****@*****.**",
                 password=password)
    insert_user(user1)
    user1_tokens = insert_tokens(user1.email)

    user2 = User(first_name="Max",
                 last_name="Muster",
                 email="*****@*****.**",
                 password=password)
    insert_user(user2)

    group = Group(
        name="Name",
        group_members=[GroupMember(user=user1),
                       GroupMember(user=user2)])
    insert_group(group)

    bill_data = {
        "description":
        "Important bill",
        "date":
        now,
        "date_created":
        now,
        "group_id":
        group.id,
        "members": [{
            "user_id": user1.id,
            "amount": 200
        }, {
            "user_id": user2.id,
            "amount": -200
        }]
    }

    response = test_client.post("/bills",
                                headers=api_headers_bearer(
                                    user1_tokens["access_token"]["token"]),
                                data=json.dumps(bill_data,
                                                default=json_data_encoder))
    json_response = json.loads(response.get_data(as_text=True))

    assert response.status_code == 201
    assert json_response["message"] == "Created new bill"
    assert len(get_bills_by_user_id(user1.id)) == 1
    assert len(get_bills_by_user_id(user2.id)) == 1

    bill = get_bills_by_user_id(user1.id)[0]
    assert bill.group == group
Example #30
0
def delete_group(id):
    '''删除权限组'''
    group = GroupModel.get_or_404(id=id, msg='分组不存在,删除失败')
    if UserModel.get(group_id=id):
        raise ForbiddenException(msg='分组下存在用户,不可删除')

    # 删除group拥有的权限
    AuthModel.objects.filter(group_id=id).delete()
    group.delete()
    return Success()
Example #31
0
    def test_add_group(self):
        session = baseDao.get_session()
        g = Group()
        g.group_uuid = uuid.uuid4()
        g.group_name = "Group_" + randomUtil.random_string(10, 10)
        g.group_de = "Group Description: " + randomUtil.random_string(10, 10)
        g.group_type_cd = 'SP'
        g.created_ts = datetime.now()
        g.private_fl = False
        new_group = groupDao.add_group(session, g)

        self.assertTrue(new_group.group_id > 0)
Example #32
0
def edit(group_id):
    group = Group.by_id(group_id)

    form = init_form(EditGroupForm, obj=group)

    if form.validate_on_submit():
        name = form.name.data.strip()
        mailtype = form.mailtype.data
        maillist = form.maillist.data.strip().lower()

        valid_form = True

        if Group.query.filter(Group.name == name,
                              Group.id != group_id).count() > 0:
            form.name.errors.append(
                _('There is already another group with this name.'))
            valid_form = False

        if mailtype != 'none' and Group.query.filter(
                Group.maillist == maillist,
                Group.id != group_id).count() > 0:
            form.maillist.errors.append(
                _('There is already another group with this e-mail address.'))
            valid_form = False

        if valid_form:
            group.name = name
            group.maillist = maillist
            if maillist == '' or mailtype == 'none':
                group.maillist = None
                group.mailtype = 'none'
            else:
                group.maillist = maillist
                group.mailtype = mailtype

            db.session.commit()

            # Only automatically create mailing lists
            if mailtype == 'mailinglist':
                google.create_group_if_not_exists(name, maillist)

            group.add_members_to_maillist()

            flash(_('The group has been edited.'), 'success')

            if mailtype == 'mailbox':
                flash(_('Ask the board to create the mailbox for this'
                        ' group (if needed)'))

            return redirect(url_for('group.view'))

    return render_template('group/edit.htm', title=_('Edit group'),
                           form=form, group=group)
Example #33
0
    def test_can_lookup_messages_by_story_or_group(self):
        start_message = 'start {}'.format(self.story_code.word_string)
        send_message(start_message)
        group = Group.query().get()

        answer_text = 'my answer is 42'
        status, response = send_message(answer_text)
        self.assertEqual(200, status)
        self.maxDiff = None
        self.assertIn(self.next_clue.text, response)
        expected_messages = [start_message, INTRO_INSTRUCTIONS.text, self.start_clue.text,
                             answer_text, self.next_clue.text]
        self.assertItemsEqual(expected_messages, [m.text for m in Message.for_story(self.story.uid)])
        self.assertItemsEqual(expected_messages, [m.text for m in Message.for_group(group.uid)])
Example #34
0
 def test_completion_sets_group_completed_time(self):
     status, response = send_message('start {}'.format(self.story_code.word_string))
     status, response = send_message('my answer is 42')
     group = Group.query().get()
     self.assertIsNotNone(group.completed_at)