def test_message_send_later():
    assert get_messages_store()['Messages'][1] == {
        'channel_id': chan_id["channel_id"],
        'message_id': message_id1['message_id'],
        'user_id': hayden_dict['u_id'],
        'message': 'Haydens Message later',
        'reacts': [],
        'time_created': get_messages_store()['Messages'][1]['time_created'],
        'is_pinned': False
    }
示例#2
0
def search(token, query_str):
    # search for all channel ids that the user has joined in message
    # iterate thru message database and append to a new {messages: list} the messages that == user_id
    # remember to reverse the list before returning it
    user = token_check(token)
    message_store = get_messages_store()
    message_list = {'messages': []}
    for user_part in user['channel_id_part']:
        for mem_check in message_store["Messages"]:
            if mem_check['channel_id'] == user_part:
                fullstring = mem_check['message']
                substring = query_str
                if substring in fullstring:
                    message_list['messages'].append({
                        'message_id':
                        mem_check['message_id'],
                        'u_id':
                        mem_check['user_id'],
                        'message':
                        mem_check['message'],
                        'time_created':
                        str(mem_check['time_created']),
                        'reacts':
                        mem_check['reacts'],
                        'is_pinned':
                        mem_check['is_pinned']
                    })
    if len(message_list['messages']) > 1:
        message_list['messages'].reverse()
    return message_list
def test_search_valid():
    ch_id = channels_create(hamish['token'], 'comp', True)
    # Send a message
    new_message_id = message_send(hamish['token'], ch_id['channel_id'], 'yes')
    # Save the time created
    message_store = get_messages_store()
    for id in message_store['Messages']:
        if id['message_id'] == new_message_id['message_id']:
            time_created = id['time_created']
            reacts = id['reacts']
            pin_status = id['is_pinned']
    assert(search(hamish['token'], 'yes') == {
    'messages':
        [
            {
                'message_id': new_message_id['message_id'],
                'u_id': hamish['u_id'],
                'message': 'yes',
                'time_created': str(time_created),
                'reacts': reacts,
                'is_pinned': pin_status,
            }
        ]
                
            
        }
        
        ) # Valid Display 
def message_remove(token, message_id):
    """Removes a message  

    Parameters:
        token (string)
        message_id(int)
    
    """
    message = message_check(message_id)
    if message == None:
        raise InputError
    is_owner = owner_channel_check(token, message['channel_id'])
    user = token_check(token)
    if user == False:
        raise AccessError

    is_sender = False
    #print("message----->",message)
    if user['u_id'] == message['user_id']:
        is_sender = True

    #print('is owner: ',is_owner,'is_sender:', is_sender)
    if (is_owner or is_sender) == False:
        raise AccessError

    message_data = get_messages_store()
    message_data['Messages'].remove(message)
    return {}
def test_message_react():
    assert get_messages_store()['Messages'][2]['reacts'] == [{
        'u_ids': [hayden_dict['u_id']],
        'react_id':
        1,
        'is_this_user_reacted':
        True
    }]
def test_search_message():

    # Call user set up
    get_user = set_up_user1_and_reset()

    ############################################################
    # Storing data
    test_token = get_user['token']
    test_uid = get_user['u_id']
    #########################################################
    # Create channel
    c = requests.post(f"{BASE_URL}/channels/create",
                      json={
                          "token": test_token,
                          "name": "thisIsANewChannel",
                          "is_public": True,
                      })

    payload_2 = c.json()
    assert payload_2["channel_id"] != None
    # Send message
    m = requests.post(f"{BASE_URL}/message/send",
                      json={
                          "token": test_token,
                          "channel_id": payload_2["channel_id"],
                          "message": "The first message",
                      })

    payload_3 = m.json()
    assert payload_3["message_id"] != None
    store = get_messages_store()

    for id in store['Messages']:
        if id['message_id'] == payload_3['message_id']:
            time_created = id['time_created']
            reacts = id['reacts']
            pin_status = id['is_pinned']

            query_search = urllib.parse.urlencode({
                'token': test_token,
                'query_str': 'first'
            })
            search_payload = json.load(
                urllib.request.urlopen(f"{BASE_URL}/search?{query_search}"))
            assert search_payload == {{
                'messages': [{
                    'message_id': payload_3["message_id"],
                    'u_id': test_uid,
                    'message': 'The first message',
                    'time_created': time_created,
                    'reacts': reacts,
                    'is_pinned': pin_status,
                }]
            }}
def workspace_reset():
    store = get_user_store()
    pemrission_store = get_permission_store()
    channel_store = get_channel_store()
    message_store = get_messages_store()
    store = {
        'users': []
    }
    channel_store = {
        'Channels':[]
    }
    message_store = {
        'Messages': []
    }
    pemrission_store = {}
    return None
def message_send_later(token, channel_id, message, time_sent):
    """ Sends a message to the designated channel at a specified time

    Parameters:
        token (string)
        channel_id(int)
        message(string)
        time_sent (datetime)
    
    Returns:
        (dictionary): A dictionary containing the message_id
        of the message that was sent.
    """

    user = token_check(token)
    if user == False:
        raise InputError
    channel = channel_check(channel_id)

    if channel == False:
        raise InputError

    if member_channel_check(token, channel_id) == False:
        raise AccessError
    if (len(message) > 1000):
        raise InputError

    if int(time_sent) < int(
            datetime.datetime.now().replace(tzinfo=timezone.utc).timestamp()):

        raise InputError
    message_store = get_messages_store()

    for member in channel['all_members']:

        if user['u_id'] == member['u_id']:

            wait_time = time_sent - datetime.datetime.now().replace(
                tzinfo=timezone.utc).timestamp()
            time.sleep(wait_time)
            #wait_time = time.mktime(datetime.datetime.now().timetuple()) - time.mktime(time_sent.timetuple())
            message_id = make_message(message, channel_id, user['u_id'], 0)

    return {
        'message_id': message_id,
    }
def channel_messages(token, channel_id, start):
    '''Returns a range of 50 messages in a channel, if user is part of that channel.
   
        Parameters: 
            token (str): authorization hash 
            channel_id (int): channel identification
            start (int): which message wants to start range at 
        
        Returns: 
            (list): returns list of messages from channel 
    '''

    if channel_check(channel_id) == False:
        raise InputError

    if check_if_user_in_channel_member(token, channel_id) == False:
        raise AccessError

    sum_of_messages = 0

    message_store = get_messages_store()

    for x in message_store['Messages']:
        if x['channel_id'] == channel_id:
            sum_of_messages += 1

    if start > sum_of_messages:
        raise InputError

    proto_dict = {'messages': []}

    final_dict = {'messages': []}
    proto_dict = get_messages_store()['Messages']

    counter = 0
    if len(proto_dict) != 0:
        #print('in the if loop aye ')
        for message in reversed(proto_dict):

            if int(message['channel_id']) == int(channel_id):

                if counter >= start:

                    dict_to_app = {
                        'message_id':
                        message['message_id'],
                        'u_id':
                        message['user_id'],
                        'message':
                        message['message'],
                        'time_created':
                        message['time_created'].replace(
                            tzinfo=timezone.utc).timestamp(),
                        'reacts':
                        message['reacts'],
                        'is_pinned':
                        message['is_pinned']
                    }
                    final_dict['messages'].append(dict_to_app)
                counter = counter + 1
            if counter >= 50:
                counter = -1
                break

    final_dict['start'] = start
    final_dict['end'] = counter

    return final_dict
def test_message_remove():
    assert len(get_messages_store()['Messages']) == 9
def test_message_edit2():
    assert get_messages_store(
    )['Messages'][7]['message'] == "Hayden changing robs message"
def test_message_edit():
    assert get_messages_store(
    )['Messages'][6]['message'] == "Rob changing robs message"
def test_message_unpin():
    assert get_messages_store()['Messages'][5]['is_pinned'] == False
def test_message_pin():
    assert get_messages_store()['Messages'][4]['is_pinned'] == True
def test_message_unreact():
    assert get_messages_store()['Messages'][3]['reacts'] == []
    with pytest.raises(AccessError):
        message_send_later(
            rob_dict['token'], chan_id['channel_id'], "Robs message",
            datetime.datetime(2020, 3, 28, 2, 9, 46,
                              184346).replace(tzinfo=timezone.utc).timestamp())


def test_message_send_later_invalid_InputError():
    with pytest.raises(InputError):
        message_send_later(
            hayden_dict['token'], chan_id['channel_id'], "Hayens message",
            datetime.datetime(2020, 3, 28, 2, 9, 46,
                              184346).replace(tzinfo=timezone.utc).timestamp())


print(get_messages_store()['Messages'])


def test_message_react_invalid_InputError1():
    with pytest.raises(InputError):
        message_react(hayden_dict['token'], 1, 1)


def test_message_react_invalid_InputError2():
    with pytest.raises(InputError):
        message_react(hayden_dict['token'], message_id['message_id'], 2)


chan_id_check = channels_create(hayden_dict['token'], 'Hayden', True)
message_id_check = message_send(hayden_dict['token'],
                                chan_id_check['channel_id'],