Exemplo n.º 1
0
def test_channels_list():
    '''
    Tests for channels list
    '''
    clear()
    #Creating users to create channels
    user1 = auth_register("*****@*****.**", "user1pass", "user1", "last1", None)
    user2 = auth_register("*****@*****.**", "user2pass", "user2", "last2", None)
    token1 = user1['token']
    token2 = user2['token']

    #testing function returns an empty list before any channels have been made
    assert channels_list(token1) == {'channels':[]}

    #Creating channels to test channels_list.

    #check for public channels
    channels_create(token1, "aGreatChannel", True)
    #check not public channels
    ch_id2 = channels_create(token2, "yetAnotherChannel", True)['channel_id']
    #check channels with same name
    channels_create(token1, "SameName", True)

    #Test for user2
    assert len(channels_list(token1)['channels']) == 2

    #Test for user1
    assert len(channels_list(token2)['channels']) == 1

    #check once user has joined channel it adds a member
    channel_join(token1, ch_id2)
    assert len(channels_list(token1)['channels']) == 3
Exemplo n.º 2
0
def test_create_valid_channels():
    '''
    Creating valid channels
    '''
    clear()
    # User1 creating 3 channels normally
    user1 = auth_register('*****@*****.**', 'thisisagoodpassword',
                          'Andrew', 'Smith')
    channels_create(user1['token'], "FirstChannel", True)
    channels_create(user1['token'], "UNSW discussion", True)
    channels_create(user1['token'], "Private", False)
    assert len(channels_list(user1['token'])['channels']) == 3
    assert len(channels_listall(user1['token'])['channels']) == 3

    # User2 creating channel
    user2 = auth_register('*****@*****.**', 'khjsdfiowefh2',
                          'Steven', 'Matthewson')
    assert len(channels_list(user2['token'])['channels']) == 0
    channels_create(user2['token'], "Steven land", True)
    assert len(channels_list(user2['token'])['channels']) == 1
    assert len(channels_listall(user1['token'])['channels']) == 4

    # User3 creating no channels
    user3 = auth_register('*****@*****.**', 'dwfwefhf', 'Steven',
                          'Smithson')
    assert len(channels_list(user3['token'])['channels']) == 0
Exemplo n.º 3
0
def test_hidden_channels():
    '''
    Testing if certain channels are hidden to users
    '''
    clear()
    # User1 makes 3 channels
    user1 = auth_register('*****@*****.**', 'ilikeapPlEs', 'Steven',
                          'Stevenson')
    channels_create(user1['token'], 'Private Channel 1', False)
    channels_create(user1['token'], 'Secret Club', False)
    channels_create(user1['token'], 'HIDDEN channel', False)
    assert len(channels_list(user1['token'])['channels']) == 3
    assert len(channels_listall(user1['token'])['channels']) == 3

    # Public channel created, user1 should be able to see all 4
    channels_create(user1['token'], 'Public', True)
    assert len(channels_list(user1['token'])['channels']) == 4

    # New user should only see public channel
    user2 = auth_register('*****@*****.**', 'idontlikeapples',
                          'Matthew', 'Matthewson')
    assert len(channels_list(user2['token'])['channels']) == 0
    assert len(channels_listall(user2['token'])['channels']) == 4

    # User2 has 1 channel
    channels_create(user2['token'], 'matthew lair', False)
    assert len(channels_list(user2['token'])['channels']) == 1

    # User1 can still only see 4
    assert len(channels_list(user1['token'])['channels']) == 4

    # There should be a total of 5 channels
    assert len(channels_listall(user2['token'])['channels']) == 5
Exemplo n.º 4
0
def test_channels_list_one_user_channel():

    clear()
    test_user0 = create_one_test_user()

    # test_user0 creates 1 public channel
    pub_channel0 = channels_create(test_user0['token'], "Public Channel 0", True)

    # check returns 1 authorised channel
    assert(channels_list(test_user0['token']) == {
        'channels': [
            {
                "channel_id": pub_channel0['channel_id'],
                "name": "Public Channel 0",
            },
        ]
    })
    # test_user0 creates 1 private channel
    priv_channel0 = channels_create(test_user0['token'], "Private Channel 0", False)

    # check returns 2 authorised channels
    assert(channels_list(test_user0['token']) == {
        'channels': [
            {
                "channel_id": pub_channel0['channel_id'],
                "name": "Public Channel 0",
            },
            {
                "channel_id": priv_channel0['channel_id'],
                "name": "Private Channel 0"
            },
        ]
    })
Exemplo n.º 5
0
def test_no_channel_in_channels_list(global_variables):
    """
    Trigger non-existent channel error.
    """
    # Not in any channels, so should raise an internal error
    with pytest.raises(Exception):
        channels_list(pytest.global_token_2)
Exemplo n.º 6
0
def test_check_token():
    clear()

    u_id = auth_register('*****@*****.**', '123abc!@#', 'Hayden',
                         'Everest', None)['u_id']

    now = datetime.now()
    timestamp = datetime.timestamp(now)

    fake_token = jwt.encode({
        'u_id': 2,
        'time': timestamp
    },
                            SECRET,
                            algorithm='HS256')

    fake_token2 = jwt.encode({
        'u_id': u_id,
        'time': timestamp
    },
                             FALSE_SECRET,
                             algorithm='HS256')

    with pytest.raises(AccessError):
        channels_list(fake_token2)
        channels_create(fake_token, "name", True)
Exemplo n.º 7
0
def test_invalid_tokens_with_users(auth_fixture):
    """
    Pytest: testing channels_list wiht invalid token
    """
    # make up values for input
    (server_data, auth_fixture) = auth_fixture
    token = "4444451AFA"

    # this should throw AccessError as the token is invalid
    with pytest.raises(AccessError):
        channels_list(server_data, token)
Exemplo n.º 8
0
def test_valid_token_owned_channels(channels_fixture):
    """
    Pytest: testing channels_list wiht owned channels
    """

    (server_data, channels_fixture) = channels_fixture

    #Split up the users:
    user1 = channels_fixture[0]
    user2 = channels_fixture[1]

    #Extract the channel informations from the user
    channel_list1 = user1["channels"]
    channel_list2 = user2["channels"]

    # List channels for user 1
    rt_info = channels_list(server_data, user1["token"])
    channels_user1 = rt_info["channels"]

    # Check if it only contains the channels created by user1
    # user1 created two channels, COMP1531 and COMP2511, both public
    assert does_channel_exist_in_list(channels_user1,
                                      channel_list1[0]["channel_id"],
                                      channel_list1[0]["name"])
    assert does_channel_exist_in_list(channels_user1,
                                      channel_list1[1]["channel_id"],
                                      channel_list1[1]["name"])

    # The channel name should match with the channel ID
    assert not does_channel_exist_in_list(channels_user1,
                                          channel_list1[0]["channel_id"],
                                          channel_list1[1]["name"])
    assert not does_channel_exist_in_list(channels_user1,
                                          channel_list1[1]["channel_id"],
                                          channel_list1[0]["name"])

    # List channels for user 2
    rt_info = channels_list(server_data, user2["token"])
    channels_user2 = rt_info["channels"]

    # Check if it only contains the channels created by user2
    # user2 created one channel, ENG1001 it is private but since user2 is authorized, they should still see it

    assert does_channel_exist_in_list(channels_user2,
                                      channel_list2[0]["channel_id"],
                                      channel_list2[0]["name"])

    # The channel name should match with the channel ID
    assert not does_channel_exist_in_list(
        channels_user2, channel_list2[0]["channel_id"], "something random")
    assert not does_channel_exist_in_list(channels_user2, 99983,
                                          channel_list2[0]["name"])
Exemplo n.º 9
0
def test_invalid_token():
    '''
    Testing when token is invalid.
    '''
    clear()
    user_1 = auth_register("*****@*****.**", "passwordOne", "Firstone",
                           "Lastone")
    user_1_token = user_1.get("token")

    channels_create(user_1_token, "usernameone", True)
    invalid_token = 112312
    with pytest.raises(error.InputError):
        channels_list(invalid_token)
Exemplo n.º 10
0
def test_list_invalid_token(create_users, create_channels):
    """
        Test for AccessError exception thrown by channels_create() when token
        passed in is not a valid token.

        :param create_users: pytest fixture to create two test users 
        :type create_users: pytest fixture

        :param create_channels: pytest fixture to create six test channels 
        :type create_channels: pytest fixture
    """
    # empty
    with pytest.raises(AccessError):
        channels_list('')

    # None
    with pytest.raises(AccessError):
        channels_list(None)

    # Not the correct data type
    with pytest.raises(AccessError):
        channels_list(123)

    # Not an authorised user
    bad_token = 'invalid_token'

    with pytest.raises(AccessError):
        channels_list(bad_token)
Exemplo n.º 11
0
def channels_list():
    '''
    Route that lists the channels a user is a part of
    '''
    token = request.args.get('token')
    dump = channels.channels_list(token)
    return dumps(dump)
Exemplo n.º 12
0
def test_channels_list_2channel():
    #dictionary of token and uid when user logs in and the element removes when he logs out

    helper_functions.clear_data()
    user1_email = '*****@*****.**'
    user1_password = '******'
    user1_firstname = 'USER'
    user1_lastname = '1'

    diction = auth.auth_register(user1_email, user1_password, user1_firstname,
                                 user1_lastname)
    token = diction.get('token')
    ## uid = diction.get('u_id')
    id_dict = channels.channels_create(token, user1_firstname, True)

    channel_id1 = id_dict.get('channel_id')

    id_dict2 = channels.channels_create(token, 'asdfg', True)

    channel_id2 = id_dict2.get('channel_id')

    chan = channels.channels_list(token)
    chan = chan.get('channels')
    assert chan == [{
        'channel_id': channel_id1,
        'name': user1_firstname
    }, {
        'channel_id': channel_id2,
        'name': 'asdfg'
    }]
Exemplo n.º 13
0
def test_channels_list2():

    # uid = tok_uid.get(12334)

    helper_functions.clear_data()
    user1_email = '*****@*****.**'
    user1_password = '******'
    user1_firstname = 'USER'
    user1_lastname = '1'

    diction = auth.auth_register(user1_email, user1_password, user1_firstname,
                                 user1_lastname)
    token = diction.get('token')
    uid = diction.get('u_id')
    ## id_dict = channels.channels_create(token,user1_firstname,True)

    chans = channels.channels_list(token)
    chans = chans.get('channels')

    for i in chans:
        id = i.get('channel_id')
        diction = channel.channel_details(
            token, id)  #also be implemented with handling access error
        diction = diction.get('all_members')
        for j in diction:
            assert j.get('u_id') == uid
Exemplo n.º 14
0
def search(token, query_str):
    """ Given a query string, return a collection of messages in all of the channels that
        the user has joined that match the query.

    Parameters:
        token (str): Authorisation hash for user
        query_str (str): Query string to search through messages for

    Returns:
        Dictionary containing:
            messages (list): List of dictionaries containing messages and their basic details
    """
    # do the lab exercise type thingo
    if not isinstance(token, str):
        raise InputError("Token is not a string")
    if not isinstance(query_str, str):
        raise InputError("Query Str not a string")

    # Will raise AccessError if token is not valid.
    channel_data = channels.channels_list(token)["channels"]
    # channel_data = channel_data["channels"]
    if not bool(channel_data):
        raise InputError("User is not in any channels")

    channel_id_list = list(
        map(lambda channel: channel["channel_id"], channel_data))

    msg_list = list(
        filter(lambda msg: msg["channel_id"] in channel_id_list,
               data["messages"]))

    message_queried = list(
        filter(lambda msg: re.search(query_str, msg["message"]), msg_list))

    return {"messages": message_queried}
Exemplo n.º 15
0
def test_channels_list_owner_channels():

    clear()
    test_user0, test_user1 = create_two_test_users()

    # test_user0 creates 1 public channel
    _ = channels_create(test_user0['token'], "Public Channel 0", True)

    # test_user0 creates 1 private channel
    _ = channels_create(test_user0['token'], "Private Channel 0", False)

    # test_user1 creates 1 public channel
    pub_channel1 = channels_create(test_user1['token'], "Public Channel 1", True)

    # test_user1 creates 1 private channel
    priv_channel1 = channels_create(test_user1['token'], "Private Channel 1", False)

    # check that for user0, return only the 2 channels they created
    assert(channels_list(test_user1['token']) == {
        'channels' : [
            {
                "channel_id": pub_channel1['channel_id'],
                "name": "Public Channel 1",
            },
            {
                "channel_id": priv_channel1['channel_id'],
                "name": "Private Channel 1",
            },
        ]
    })
Exemplo n.º 16
0
def test_list_standard(create_users, create_channels):
    """
        Test for standard functionality of channels_list() according to spec.

        :param create_users: pytest fixture to create two test users 
        :type create_users: pytest fixture

        :param create_channels: pytest fixture to create six test channels 
        :type create_channels: pytest fixture
    """
    # test length of returned channels list, making sure channels of
    # User 2 is not listed
    temp = channels_list(users[0]['token'])
    assert len(temp['channels']) == 3

    # test for accuracy of details of returned channels list
    channel_01_listed = temp['channels'][0]
    channel_02_listed = temp['channels'][1]
    channel_03_listed = temp['channels'][2]
    assert channel_01_listed['channel_id'] == channel_01['channel_id']
    assert channel_01_listed['name'] == 'Channel 01'
    assert channel_02_listed['channel_id'] == channel_02['channel_id']
    assert channel_02_listed['name'] == 'Channel 02'
    assert channel_03_listed['channel_id'] == channel_03['channel_id']
    assert channel_03_listed['name'] == 'Channel 03'
Exemplo n.º 17
0
def search(token, query_str):
    """
    Returns a dictionary containing a list of all users in Flockr

    Parameters:
        token(string): A user authorisation hash

    Returns:
        messages: A dictionary containing a list of all messages that the user has sent 
                  with the corresponding query string
    """
    # Check that token is valid
    validation.check_valid_token(token)

    # Initialises messages to return to user
    messages = []

    # Finds all messages that the user has sent containing the query string

    user_channels = channels.channels_list(token)["channels"]
    print(user_channels)
    for channel in user_channels:
        channel_info = data.get_channel_info(channel["channel_id"])
        for message in channel_info["messages"].values():
            print(message['message'])
            if query_str in message["message"]:
                messages.append(message)

    return {'messages': messages}
Exemplo n.º 18
0
def http_channels_list():
    '''
    Wrapper function for channels_list (retrieves channels user is in)
    GET: JSON containing "token" (str)
    Returns JSON containing "channels" (list of dicts)
    '''
    return dumps(channels_list(request.args.get('token')))
Exemplo n.º 19
0
def test_channels_list_empty():
    reset_data()
    # Creating the user
    user_info = auth_register('*****@*****.**', 'sadsad', 'name', 'lastname')
    assert channels_list(user_info['token']) == {
        'channels': [],
    }
Exemplo n.º 20
0
def test_clear():
    boyu_dict, _ = initialise_data()
    channel_1 = channels_create(boyu_dict['token'], 'channel_1', True)
    id_1 = message_send(boyu_dict['token'], channel_1['channel_id'], '1')
    message_send(boyu_dict['token'], channel_1['channel_id'], '2')
    message_send(boyu_dict['token'], channel_1['channel_id'], '3')
    # clear original data
    clear()
    # initialise data
    boyu_dict, _ = initialise_data()
    users_dict = users_all(boyu_dict['token'])
    # check user details already update
    assert len(users_dict['users']) == 2
    assert users_dict['users'][0]['u_id'] == boyu_dict['u_id']
    assert users_dict['users'][0]['email'] == '*****@*****.**'
    assert users_dict['users'][0]['name_first'] == 'Boyu'
    assert users_dict['users'][0]['name_last'] == 'Cai'
    # check channels list is already update
    channel_1_id = channels_create(boyu_dict['token'], 'channel_1', True)
    assert channels_listall(boyu_dict['token']) == channels_list(
        boyu_dict['token'])
    # send two message in a channel
    id_1 = message_send(boyu_dict['token'], channel_1_id['channel_id'],
                        'hello!')
    message_send(boyu_dict['token'], channel_1_id['channel_id'], 'he_llo')
    message_send(boyu_dict['token'], channel_1_id['channel_id'], 'hi there')
    search_result = search(boyu_dict['token'], "hello")
    # search message order is correct
    assert len(search_result['messages']) == 1
    assert search_result['messages'][0]["message"] == 'hello!'
    assert search_result['messages'][0]["u_id"] == boyu_dict['u_id']
    assert search_result['messages'][0]["message_id"] == id_1['message_id']
Exemplo n.º 21
0
def test_valid_token_member_channel(channels_fixture):
    """
    Pytest: testing channels_list with member channels
    """

    (server_data, channels_fixture) = channels_fixture

    #Split up the users:
    user1 = channels_fixture[0]
    user2 = channels_fixture[1]

    #Extract the channel informations from the user
    channel_list1 = user1["channels"]
    channel_list2 = user2["channels"]

    #Now invite user2 into user1's channel
    channel_invite(server_data, user1["token"], channel_list1[0]["channel_id"],
                   user2["u_id"])

    #Now user 2 should contain 2 channels, one owned, one as member
    rt_info = channels_list(server_data, user2["token"])
    channels_user2 = rt_info["channels"]

    assert does_channel_exist_in_list(channels_user2,
                                      channel_list1[0]["channel_id"],
                                      channel_list1[0]["name"])
    assert does_channel_exist_in_list(channels_user2,
                                      channel_list2[0]["channel_id"],
                                      channel_list2[0]["name"])
Exemplo n.º 22
0
def test_valid_channel_list():
    '''
    Testing if channel_list works.
    '''
    clear()
    user_1 = auth_register("*****@*****.**", "passwordOne", "Firstone",
                           "Lastone")
    user_1_token = user_1.get("token")
    user_2 = auth_register("*****@*****.**", "passwordTwo", "Firsttwo",
                           "Lasttwo")
    user_2_token = user_2.get("token")
    auth_register("*****@*****.**", "passwordTwo", "Firsttwo", "Lasttwo")
    user_3_token = user_2.get("token")
    auth_register("*****@*****.**", "passwordTwo", "Firsttwo", "Lasttwo")
    user_4_token = user_2.get("token")

    channel1 = channels_create(user_1_token, "channel1", True)
    channel2 = channels_create(user_1_token, "channel2", True)
    channel3 = channels_create(user_1_token, "channel3", True)
    channels_create(user_2_token, "channel4", True)
    channels_create(user_3_token, "channel5", True)
    channels_create(user_4_token, "channel6", True)

    channel_list = channels_list(user_1_token)

    assert channel_list.get('channels')[0]["channel_id"] == channel1.get(
        "channel_id")
    assert channel_list.get('channels')[1]["channel_id"] == channel2.get(
        "channel_id")
    assert channel_list.get('channels')[2]["channel_id"] == channel3.get(
        "channel_id")
    assert len(channel_list.get('channels')) == 3
Exemplo n.º 23
0
def channels_list():
    """
    Function channels list route
    """
    token = request.args.get('token')
    channels_dict = channels.channels_list(token)
    return dumps(channels_dict)
Exemplo n.º 24
0
def test_channel_list(global_variables):
    """
    Lists channels user is only in.
    """
    channels_create(pytest.global_token_2['token'], "channel_1", True)
    channels_temp_list = channels_list(pytest.global_token_2['token'])
    assert channels_temp_list['channels'][0]['name'] == "channel_1"
Exemplo n.º 25
0
def test_channels_list_functionality():
    clear()
    user1 = auth_register("*****@*****.**", 'N*B@C*N1@5', 'Britney',
                          'Bakon')
    user2 = auth_register("*****@*****.**", 'OewewrI', 'Angel', 'Kit')

    channel_id1 = channels_create(user1['token'], "channel1", True)
    channel_id2 = channels_create(user1['token'], "channel2", False)
    channel_id3 = channels_create(user1['token'], "channel3", False)
    channel_id4 = channels_create(user1['token'], "channel4", True)

    channel_invite(user1['token'], channel_id1['channel_id'], user2['u_id'])
    channel_invite(user1['token'], channel_id2['channel_id'], user2['u_id'])
    channel_invite(user1['token'], channel_id3['channel_id'], user2['u_id'])
    channel_invite(user1['token'], channel_id4['channel_id'], user2['u_id'])

    output = channels_list(user2['token'])

    check_list = [channel['channel_id'] for channel in output['channels']]
    expected_output = [
        channel_id1['channel_id'], channel_id2['channel_id'],
        channel_id3['channel_id'], channel_id4['channel_id']
    ]
    check_list.sort()
    expected_output.sort()
    assert check_list == expected_output
Exemplo n.º 26
0
def test_channels_listall_functionality():
    clear()
    user1 = auth_register("*****@*****.**", '@JR4slkdN', 'Edgar',
                          'Bronte')
    user2 = auth_register("*****@*****.**", 'D3@d@uthors', 'Kahlil',
                          'Gibran')
    user3 = auth_register("*****@*****.**", 'Intj3234*)2nkB',
                          'Francessa', 'Maroun')

    channel_id1 = channels_create(user1['token'], "channel1", True)
    channel_id2 = channels_create(user1['token'], "channel2", False)
    channel_id3 = channels_create(user2['token'], "channel3", False)
    channel_id4 = channels_create(user2['token'], "channel4", True)

    channel_invite(user1['token'], channel_id1['channel_id'], user2['u_id'])
    channel_invite(user1['token'], channel_id2['channel_id'], user3['u_id'])
    channel_invite(user2['token'], channel_id3['channel_id'], user1['u_id'])
    channel_invite(user2['token'], channel_id4['channel_id'], user3['u_id'])

    output = channels_list(user1['token'])

    check_list = [channel['channel_id'] for channel in output['channels']]
    expected_output = [
        channel_id1['channel_id'], channel_id2['channel_id'],
        channel_id3['channel_id'], channel_id4['channel_id']
    ]
    assert check_list.sort() == expected_output.sort()
Exemplo n.º 27
0
def test_channels_list_private():
    clear()
    user = register_n_users(1)
    token = user["token"]
    name = "channel"
    channel_id = channels_create(token, name, is_public=False)["channel_id"]
    authorised_channels = {"channels": [{"channel_id": channel_id, "name": name}]}
    assert channels_list(token) == authorised_channels
Exemplo n.º 28
0
def test_channels_list_output_nochannels():
    clear()
    user = auth_register("*****@*****.**", 'DZVznKzzuPnjc', 'Alexie',
                         'Evie-Mae')
    output = channels_list(user['token'])
    assert output is not None
    assert output['channels'] is not None
    assert output['channels'] == []
Exemplo n.º 29
0
def channels_list_http():
    """Flask wrap of channels_list"""
    token = check_token_arg()
    if not token:
        return json.dumps("Token not correctly passed in"), 400

    response = channels_list(token)
    return json.dumps(response), 200
Exemplo n.º 30
0
def test_channel_join_valid():
    """
    Testing successful uses of channel_join without any errors
    """
    user_channel_creater = auth.auth_register("*****@*****.**",
                                              "password", "Quick", "Shadow")
    test_user1 = auth.auth_register("*****@*****.**", "password",
                                    "Optimus", "Prime")
    test_user2 = auth.auth_register("*****@*****.**", "password",
                                    "Bumble", "Bee")
    test_user3 = auth.auth_register("*****@*****.**", "password",
                                    "Cliff", "Jumper")
    test_channel_id1 = channels.channels_create(user_channel_creater["token"],
                                                "test", True)

    # Checks a user can join a public channel
    channel.channel_join(test_user1["token"], test_channel_id1["channel_id"])
    channel.channel_join(test_user2["token"], test_channel_id1["channel_id"])
    channel.channel_join(test_user3["token"], test_channel_id1["channel_id"])
    list_result1 = channels.channels_list(test_user1["token"])["channels"]
    list_result2 = channels.channels_list(test_user2["token"])["channels"]
    list_result3 = channels.channels_list(test_user3["token"])["channels"]
    assert list_result1[0]["channel_id"] == test_channel_id1["channel_id"]
    assert list_result2[0]["channel_id"] == test_channel_id1["channel_id"]
    assert list_result3[0]["channel_id"] == test_channel_id1["channel_id"]
    test_public_channel_details = channel.channel_details(
        test_user1["token"], test_channel_id1["channel_id"])

    member1 = None
    for member in test_public_channel_details["all_members"]:
        if member["u_id"] == test_user1["u_id"]:
            member1 = member
    assert member1 is not None
    member2 = None
    for member in test_public_channel_details["all_members"]:
        if member["u_id"] == test_user2["u_id"]:
            member2 = member
    assert member2 is not None
    member3 = None
    for member in test_public_channel_details["all_members"]:
        if member["u_id"] == test_user3["u_id"]:
            member3 = member
    assert member3 is not None

    other.clear()