Esempio n. 1
0
class TestsOther:

    config = read_yaml(os.path.join(const.PROJECT, 'config.yaml'))
    user = config['users']['user1']
    url = ''
    api = API

    def setup_method(self):
        self.url = self.config['api']['url']
        phone = self.user['phone']
        code = self.user['code']
        auth_cookies = auth.login_with_cookies(self.url, phone, code)
        self.api = API(self.url, auth_cookies, is_token_auth=False)

    def teardown_method(self):
        auth.logout(self.url)

    '''    
    Пример для авторизации через токен
    def setup_class(self):
        self.url = self.config['api']['url']
        user = self.config['users']['user1']
        data = {
            'phone': user['phone'],
            'code': user['code'],
            'device_id': user['device_id'],
            'type': user['type']
        }
        token = auth.login_with_token(self.url, data)
        self.api = API(self.url, token)
    '''

    @pytest.mark.positive
    def test_ping_post(self):
        resp = self.api.ping_post()
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result'] == 'pong'

    @pytest.mark.positive
    def test_ping_get(self):
        resp = self.api.ping_get()
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result'] == 'pong'

    @pytest.mark.positive
    def test_ping_post_delay_sec(self):
        delay_sec = 2
        time_now = datetime.datetime.now()
        resp = self.api.ping_post(delay_sec)
        time_then = datetime.datetime.now()
        delta_time = time_then - time_now
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result'] == 'pong'
        assert delta_time.seconds >= delay_sec

    @pytest.mark.positive
    def test_ping_get_delay_sec(self):
        delay_sec = 2
        time_now = datetime.datetime.now()
        resp = self.api.ping_get(delay_sec)
        time_then = datetime.datetime.now()
        delta_time = time_then - time_now
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result'] == 'pong'
        assert delta_time.seconds >= delay_sec

    @pytest.mark.positive
    def test_time(self):
        resp = self.api.time()
        local_date = str(datetime.datetime.today())
        resp = resp.json()
        assert 'error' not in resp
        assert local_date[0:10] in resp['result']

    @pytest.mark.positive
    def test_countries(self):
        resp = self.api.countries()
        path = os.path.join(const.EXPECTED_RESULTS, 'countries.json')
        expected = read_json(path)
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result'] == expected['result']
Esempio n. 2
0
class TestsChat:
    config = read_yaml(os.path.join(const.PROJECT, 'config.yaml'))
    user = config['users']['user1']
    phone = config['users']['user1']['phone']
    code = config['users']['user1']['code']

    user2 = config['users']['user2']
    phone2 = config['users']['user2']['phone']
    code2 = config['users']['user2']['code']

    user3 = config['users']['user3']
    phone3 = config['users']['user3']['phone']
    code3 = config['users']['user3']['code']

    user4 = config['users']['user4']
    phone4 = config['users']['user4']['phone']
    code4 = config['users']['user4']['code']

    url = ''
    api = API
    team_uid = ''
    invalid_user_jid = '00000000-0000-0000-0000-77dc6850e494@xmpp'
    invalid_group_jid = '*****@*****.**'
    invalid_team_uid = '00000000-0000-0000-0000-982d4bac29a1'


    def setup_class(self):
        # Логин и создание команды, далее эта команда используется в тестах
        self.url = self.config['api']['url']
        phone = self.user['phone']
        code = self.user['code']
        auth_cookies = auth.login_with_cookies(self.url, phone, code)
        self.api = API(self.url, auth_cookies, is_token_auth=False)
        resp = func.add_team(self.api)
        self.team_uid = resp['uid']
        resp = func.add_group(self.api, self.team_uid)
        self.group_jid = resp['jid']


    def setup_method(self):
        self.url = self.config['api']['url']
        phone = self.user['phone']
        code = self.user['code']
        auth_cookies = auth.login_with_cookies(self.url, phone, code)
        self.api = API(self.url, auth_cookies, is_token_auth=False)


    def teardown_method(self):
        auth.logout(self.url)


    '''    
    Пример для авторизации через токен
    def setup_class(self):
        self.url = self.config['api']['url']
        user = self.config['users']['user1']
        data = {
            'phone': user['phone'],
            'code': user['code'],
            'device_id': user['device_id'],
            'type': user['type']
        }
        token = auth.login_with_token(self.url, data)
        self.api = API(self.url, token)
    '''


    @pytest.mark.positive
    def test_get_botcommands_admin(self):
        team_uid = func.add_team(self.api)['uid']
        group_jid = func.add_group(self.api, team_uid)['jid']
        resp = self.api.get_botcommands(team_uid, group_jid).json()
        path = os.path.join(const.EXPECTED_RESULTS, 'bot_commands_admin.json')
        expected = read_json(path)
        assert 'error' not in resp
        assert resp['result'] == expected['result']


    @pytest.mark.positive
    def test_get_botcommands_member(self):
        team_uid = func.add_team(self.api)['uid']
        group_jid = func.add_group(self.api, team_uid)['jid']
        user2_jid = func.add_contact(self.api, team_uid, self.phone2)['jid']
        func.add_member_to_group(self.api, team_uid, group_jid, user2_jid, 'member')
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        resp = api2.get_botcommands(team_uid, group_jid).json()
        path = os.path.join(const.EXPECTED_RESULTS, 'bot_commands_member.json')
        expected = read_json(path)
        assert 'error' not in resp
        assert resp['result'] == expected['result']


    @pytest.mark.positive
    def test_linkscheck_dog(self):
        team_uid = func.add_team(self.api)['uid']
        group_jid = func.add_group(self.api, team_uid)['jid']
        dog = '@все'
        text = f'{dog} , привет!'
        resp = self.api.linkscheck(team_uid, group_jid, text).json()
        expected = {
            'pattern': dog,
            'text': dog,
            'url': f'otv://{group_jid}'
        }
        assert 'error' not in resp
        assert resp['result']['links'][0] == expected


    @pytest.mark.positive
    def test_linkscheck_sharp(self):
        team_uid = func.add_team(self.api)['uid']
        group = func.add_group(self.api, team_uid)
        group_jid = group['jid']
        group_name = group['display_name']
        text = f'#{group_name}'
        resp = self.api.linkscheck(team_uid, group_jid, text).json()
        expected = {
            'pattern': text,
            'text': text,
            'url': f'otv://{group_jid}'
        }
        assert 'error' not in resp
        assert resp['result']['links'][0] == expected


    @pytest.mark.positive
    def test_linkscheck_https(self):
        team_uid = func.add_team(self.api)['uid']
        group_jid = func.add_group(self.api, team_uid)['jid']
        text = 'https://www.google.ru/'
        resp = self.api.linkscheck(team_uid, group_jid, text).json()
        assert 'error' not in resp
        resp = resp['result']['links'][0]
        assert resp['pattern'] == text
        assert resp['preview']['title'] == 'Google'
        assert resp['text'] == text
        assert resp['url'] == text


    @pytest.mark.positive
    def test_linkscheck_http(self):
        team_uid = func.add_team(self.api)['uid']
        group_jid = func.add_group(self.api, team_uid)['jid']
        text = 'http://www.yandex.ru/'
        resp = self.api.linkscheck(team_uid, group_jid, text).json()
        assert 'error' not in resp
        resp = resp['result']['links'][0]
        assert resp['pattern'] == text
        assert resp['preview']['title'] == 'Яндекс'
        assert resp['text'] == text
        assert resp['url'] == text


    @pytest.mark.positive
    def test_linkscheck_rus(self):
        team_uid = func.add_team(self.api)['uid']
        group_jid = func.add_group(self.api, team_uid)['jid']
        text = 'http://кто.рф/'
        resp = self.api.linkscheck(team_uid, group_jid, text).json()
        assert 'error' not in resp
        resp = resp['result']['links'][0]
        assert resp['pattern'] == text
        assert resp['preview']['title'] == '.РФ - наш домен'
        assert resp['text'] == text
        assert resp['url'] == 'http://xn--j1ail.xn--p1ai/'


    @pytest.mark.negative
    def test_linkscheck_without_link(self):
        team_uid = func.add_team(self.api)['uid']
        group_jid = func.add_group(self.api, team_uid)['jid']
        text = 'Привет, как дела? !;%:?*()_ How are you'
        resp = self.api.linkscheck(team_uid, group_jid, text).json()
        assert 'error' not in resp
        assert not resp['result']['links']


    @pytest.mark.negative
    def test_send_text_invalid_team_uid(self):
        team_uid = func.add_team(self.api)['uid']
        group_jid = func.add_group(self.api, team_uid)['jid']
        data = {'text': tools.generate_random_string()}
        resp = self.api.send_msg_text(self.invalid_team_uid, group_jid, data).json()
        assert resp['error'] == const.NOT_FOUND


    @pytest.mark.negative
    def test_send_text_invalid_group_jid(self):
        data = {'text': tools.generate_random_string()}
        resp = self.api.send_msg_text(self.team_uid, self.invalid_group_jid, data).json()
        assert resp['error'] == const.NOT_FOUND


    @pytest.mark.positive
    def test_send_text_all_symbols(self):
        # создаем группу
        group_jid = func.add_group(self.api, self.team_uid)['jid']
        data = {'text': '1234\ndgJFОРПорп !@ #$% ^&* ()'}
        resp = self.api.send_msg_text(self.team_uid, group_jid, data).json()
        assert 'error' not in resp['result']
        assert resp['result']['content']['text'] == data['text']


    @pytest.mark.positive
    def test_send_text_8000_symbols(self):
        # создаем группу
        group_jid = func.add_group(self.api, self.team_uid)['jid']
        data = {'text': tools.generate_random_string(8001)}
        resp = self.api.send_msg_text(self.team_uid, group_jid, data).json()
        assert 'error' not in resp['result']
        assert resp['result']['content']['text'] == data['text']


    @pytest.mark.negative
    def test_send_text_8001_symbols(self):
        # создаем группу
        group_jid = func.add_group(self.api, self.team_uid)['jid']
        data = {'text': tools.generate_random_string(8002)}
        resp = self.api.send_msg_text(self.team_uid, group_jid, data).json()
        assert resp['error'] == const.INVALID_DATA
        assert resp['details']['text'] == 'Ошибка отправки'


    @pytest.mark.positive
    def test_send_text_with_message_id(self):
        # создаем группу
        group_jid = func.add_group(self.api, self.team_uid)['jid']
        message_id = str(uuid.uuid4())
        data = {
            'text': 'hello',
            'message_id': message_id,
        }
        resp = self.api.send_msg_text(self.team_uid, group_jid, data).json()
        assert 'error' not in resp
        assert resp['result']['message_id'] == message_id


    @pytest.mark.positive
    def test_send_text_with_nopreview(self):
        # создаем группу
        group_jid = func.add_group(self.api, self.team_uid)['jid']
        data = {
            'text': 'https://github.com/arkuz',
            'nopreview': True,
        }
        resp = self.api.send_msg_text(self.team_uid, group_jid, data).json()
        assert 'error' not in resp
        assert not resp['result']['links']


    @pytest.mark.negative
    def test_send_empty_text(self):
        # создаем группу
        group_jid = func.add_group(self.api, self.team_uid)['jid']
        data = {'text': ''}
        resp = self.api.send_msg_text(self.team_uid, group_jid, data).json()
        assert resp['error'] == const.INVALID_DATA


    @pytest.mark.positive
    def test_send_text_readonly_for_members_false(self):
        # создаем группу с  с readonly_for_members: false
        data = {'display_name': tools.generate_random_string(),
                'public': False,
                'readonly_for_members': False}
        resp = self.api.add_group(self.team_uid, data).json()
        group_jid = resp['result']['jid']
        # добавляем участника в команду и в группу
        user2_jid = func.add_contact(self.api, self.team_uid, self.phone2)['jid']
        func.add_member_to_group(self.api, self.team_uid, group_jid, user2_jid, 'member')
        auth_cookies = auth.login_with_cookies(self.url, self.phone2, self.code2)
        api2 = API(self.url, auth_cookies, is_token_auth=False)
        msg_data = {'text': tools.generate_random_string()}
        resp = api2.send_msg_text(self.team_uid, group_jid, msg_data).json()
        assert 'error' not in resp
        assert resp['result']['content']['text'] == msg_data['text']


    @pytest.mark.negative
    def test_send_text_readonly_for_members_true(self):
        # создаем группу с readonly_for_members: true
        data = {'display_name': tools.generate_random_string(),
                'public': False,
                'readonly_for_members': True}
        resp = self.api.add_group(self.team_uid, data).json()
        group_jid = resp['result']['jid']
        # добавляем участника в команду и в группу
        user2_jid = func.add_contact(self.api, self.team_uid, self.phone2)['jid']
        func.add_member_to_group(self.api, self.team_uid, group_jid, user2_jid, 'member')
        auth_cookies = auth.login_with_cookies(self.url, self.phone2, self.code2)
        api2 = API(self.url, auth_cookies, is_token_auth=False)
        msg_data = {'text': tools.generate_random_string()}
        resp = api2.send_msg_text(self.team_uid, group_jid, msg_data).json()
        assert resp['error'] == const.ACCESS_DENIED


    @pytest.mark.positive
    @pytest.mark.parametrize("filename", [
        'tiger.pdf',
        'word.docx',
        'excel.xlsx',
        'tiger.gif',
        'tiger.PNG',
        'tiger',
        'tiger.bmp',
        'audio.wav'
    ])
    def test_send_file(self, filename):
        resp = self.api.send_msg_file(self.team_uid, self.group_jid, os.path.join(const.TD_FILES, filename)).json()
        assert 'error' not in resp['result']
        assert resp['result']['content']['name'] == filename


    @pytest.mark.positive
    @pytest.mark.parametrize("filename", [
        'audio.wav',
        'audio.m4a',
        'audio.mp3'
    ])
    def test_send_audio(self, filename):
        resp = self.api.send_msg_audio(self.team_uid, self.group_jid, os.path.join(const.TD_FILES, filename)).json()
        assert 'error' not in resp['result']
        assert '.mp3' in resp['result']['content']['mediaURL']
        assert resp['result']['content']['type'] == 'audiomsg'


    @pytest.mark.negative
    @pytest.mark.parametrize("filename", [
        'tiger.pdf',
        'word.docx',
        'excel.xlsx'
    ])
    def test_send_audio_invalid(self, filename):
        resp = self.api.send_msg_audio(self.team_uid, self.group_jid, os.path.join(const.TD_FILES, filename)).json()
        assert resp['error'] == const.INVALID_DATA
        assert 'Ошибка при загрузке. Проверьте тип файла и попробуйте ещё раз. Mime type is' in resp['details']['file']


    # тесты на галерею


    @pytest.mark.positive
    def test_get_messages(self):
        group_jid = func.add_group(self.api, self.team_uid)['jid']
        # добавляем сообщения в цикле
        exp_msg = {}
        for i in range(5):
            # эта магия с i для того, чтобы ключи словаря exp_msg совпадали с ключами в resp т.к. в ответе есть всегда 2 дефолтных сообщения
            i = i + 2
            text = 'msg_{}_{}'.format(tools.generate_random_string(7), i)
            exp_msg[i] = text
            func.send_text(self.api, self.team_uid, group_jid, text)
        resp = self.api.get_messages(self.team_uid, group_jid).json()
        assert 'error' not in resp['result']
        assert len(resp['result']['messages']) == 7
        num = 6
        while num > 1:
            assert resp['result']['messages'][num]['content']['text'] == exp_msg[num]
            num = num - 1


    @pytest.mark.negative
    def test_get_messages_invalid_team_uid(self):
        resp = self.api.get_messages(self.invalid_team_uid, self.group_jid).json()
        assert resp['error'] == const.NOT_FOUND


    @pytest.mark.negative
    def test_get_messages_invalid_chat_jid(self):
        resp = self.api.get_messages(self.team_uid, self.invalid_group_jid).json()
        assert resp['error'] == const.NOT_FOUND


    @pytest.mark.positive
    def test_get_messages_old_from(self):
        group_jid = func.add_group(self.api, self.team_uid)['jid']
        msg_list = []
        # добавляем сообщения в цикле
        for i in range(3):
            text = 'msg_{}_{}'.format(tools.generate_random_string(7), i)
            msg_list.append(func.send_text(self.api, self.team_uid, group_jid, text)['message_id'])
        params = {'old_from': msg_list[-1]}
        resp = self.api.get_messages(self.team_uid, group_jid, params).json()
        assert 'error' not in resp
        assert tools.is_items_exist_in_list_of_dict(
            resp['result']['messages'], 'message_id', msg_list[0])
        assert tools.is_items_exist_in_list_of_dict(
            resp['result']['messages'], 'message_id', msg_list[1])
        assert not tools.is_items_exist_in_list_of_dict(
            resp['result']['messages'], 'message_id', msg_list[-1])


    @pytest.mark.positive
    def test_get_messages_new_from(self):
        group_jid = func.add_group(self.api, self.team_uid)['jid']
        msg_list = []
        # добавляем сообщения в цикле
        for i in range(3):
            text = 'msg_{}_{}'.format(tools.generate_random_string(7), i)
            msg_list.append(func.send_text(self.api, self.team_uid, group_jid, text)['message_id'])
        params = {'new_from': msg_list[0]}
        resp = self.api.get_messages(self.team_uid, group_jid, params).json()
        assert 'error' not in resp
        assert len(resp['result']['messages']) == 2
        assert tools.is_items_exist_in_list_of_dict(
            resp['result']['messages'], 'message_id', msg_list[1])
        assert tools.is_items_exist_in_list_of_dict(
            resp['result']['messages'], 'message_id', msg_list[-1])
        assert not tools.is_items_exist_in_list_of_dict(
            resp['result']['messages'], 'message_id', msg_list[0])


    @pytest.mark.positive
    def test_get_messages_limit(self):
        group_jid = func.add_group(self.api, self.team_uid)['jid']
        # добавляем сообщения в цикле
        for i in range(5):
            text = 'msg_{}_{}'.format(tools.generate_random_string(7), i)
            func.send_text(self.api, self.team_uid, group_jid, text)
        limit = 3
        params = {'limit': limit}
        resp = self.api.get_messages(self.team_uid, group_jid, params).json()
        assert 'error' not in resp['result']
        assert len(resp['result']['messages']) == limit


    @pytest.mark.positive
    def test_get_messages_exact(self):
        group_jid = func.add_group(self.api, self.team_uid)['jid']
        text = tools.generate_random_string(7)
        message_id = func.send_text(self.api, self.team_uid, group_jid, text)['message_id']
        params = {'exact': message_id}
        resp = self.api.get_messages(self.team_uid, group_jid, params).json()
        assert 'error' not in resp['result']
        assert len(resp['result']['messages']) == 1
        assert resp['result']['messages'][0]['content']['text'] == text


    @pytest.mark.positive
    def test_get_messages_unread(self):
        user2_jid = func.add_contact(self.api, self.team_uid, self.phone2)['jid']
        group_jid = func.add_group(self.api, self.team_uid)['jid']
        func.add_member_to_group(self.api, self.team_uid, group_jid, user2_jid, 'admin')
        # добавляем сообщения в цикле
        exp_msg = {}
        for i in range(5):
            # эта магия с i для того, чтобы ключи словаря exp_msg совпадали с ключами в resp т.к. в ответе есть всегда 2 дефолтных сообщения
            i = i + 1
            text = 'msg_{}_{}'.format(tools.generate_random_string(7), i)
            exp_msg[i] = text
            func.send_text(self.api, self.team_uid, group_jid, text)
        auth_cookies = auth.login_with_cookies(self.url, self.phone2, self.code2)
        api2 = API(self.url, auth_cookies, is_token_auth=False)
        params = {'unread': True}
        resp = api2.get_messages(self.team_uid, group_jid, params).json()
        assert 'error' not in resp['result']
        assert len(resp['result']['messages']) == 6
        num = 5
        while num > 0:
            assert resp['result']['messages'][num]['content']['text'] == exp_msg[num]
            num = num - 1


    @pytest.mark.positive
    def test_get_filtered_messages(self):
        team_uid = func.add_team(self.api)['uid']
        group_jid = func.add_group(self.api, team_uid)['jid']
        # добавляем сообщения в цикле
        exp_msg = {}
        count = 5
        for i in range(count):
            # эта магия с i для того, чтобы ключи словаря exp_msg совпадали с ключами в resp т.к. в ответе есть всегда 2 дефолтных сообщения
            i = count - 1
            text = 'msg_{}_{}'.format(tools.generate_random_string(7), i)
            exp_msg[i] = text
            func.send_text(self.api, team_uid, group_jid, text)
        resp = self.api.get_filtered_messages(team_uid).json()
        assert 'error' not in resp['result']
        assert len(resp['result']['objects']) == 7
        num = count
        while num < count:
            assert resp['result']['objects'][num]['content']['text'] == exp_msg[num]
            num = num + 1


    @pytest.mark.negative
    def test_get_filtered_messages_invalid_team_uid(self):
        resp = self.api.get_filtered_messages(self.invalid_team_uid).json()
        assert resp['error'] == const.NOT_FOUND


    @pytest.mark.positive
    def test_get_filtered_messages_limit_offset(self):
        group_jid = func.add_group(self.api, self.team_uid)['jid']
        exp_text = ''
        for i in range(5):
            text = 'msg_{}_{}'.format(tools.generate_random_string(7), i)
            func.send_text(self.api, self.team_uid, group_jid, text)
            # запоминаем текст сообщения
            if i == 0:
                exp_text = text
        params = {
            'limit': 1,
            'offset': 4,
        }
        resp = self.api.get_filtered_messages(self.team_uid, params).json()
        assert 'error' not in resp['result']
        assert len(resp['result']['objects']) == 1
        assert resp['result']['objects'][0]['content']['text'] == exp_text


    @pytest.mark.positive
    def test_get_messages_chat(self):
        group_jid = func.add_group(self.api, self.team_uid)['jid']
        group_jid_2 = func.add_group(self.api, self.team_uid)['jid']
        group_jid_3 = func.add_group(self.api, self.team_uid)['jid']
        # добавляем сообщения
        text = 'msg_{}'.format(tools.generate_random_string(7))
        func.send_text(self.api, self.team_uid, group_jid, text)
        func.send_text(self.api, self.team_uid, group_jid_2, text)
        func.send_text(self.api, self.team_uid, group_jid_3, text)
        params = {
            'chat': f'{group_jid},{group_jid_2}',
        }
        resp = self.api.get_filtered_messages(self.team_uid, params).json()
        assert 'error' not in resp
        assert tools.is_items_exist_in_list_of_dict(
            resp['result']['objects'],
            'chat',
            group_jid,
        )
        assert tools.is_items_exist_in_list_of_dict(
            resp['result']['objects'],
            'chat',
            group_jid_2,
        )
        assert not tools.is_items_exist_in_list_of_dict(
            resp['result']['objects'],
            'chat',
            group_jid_3,
        )


    @pytest.mark.positive
    def test_get_messages_sender(self):
        # создаем команду
        team_uid = func.add_team(self.api)['uid']
        # приглашаем пользователей
        user1_jid = func.get_my_jid(self.api, team_uid)
        user2_jid = func.add_contact(self.api, team_uid, self.phone2)['jid']
        user3_jid = func.add_contact(self.api, team_uid, self.phone3)['jid']
        # добавляем участников к группе
        group_jid = func.add_group(self.api, team_uid)['jid']
        func.add_member_to_group(self.api, team_uid, group_jid, user2_jid, 'member')
        func.add_member_to_group(self.api, team_uid, group_jid, user3_jid, 'admin')
        # добавляем сообщения
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        api3 = auth.login_another_user(self.url, self.phone3, self.code3)
        text = 'msg_{}'.format(tools.generate_random_string(7))
        func.send_text(self.api, team_uid, group_jid, text)
        func.send_text(api2, team_uid, group_jid, text)
        func.send_text(api3, team_uid, group_jid, text)
        params = {
            'sender': f'{user1_jid},{user2_jid}',
        }
        resp = self.api.get_filtered_messages(team_uid, params).json()
        assert 'error' not in resp
        assert tools.is_items_exist_in_list_of_dict(
            resp['result']['objects'],
            'from',
            user1_jid,
        )
        assert tools.is_items_exist_in_list_of_dict(
            resp['result']['objects'],
            'from',
            user2_jid,
        )
        assert not tools.is_items_exist_in_list_of_dict(
            resp['result']['objects'],
            'from',
            user3_jid,
        )


    @pytest.mark.positive
    def test_get_messages_text(self):
        # создаем команду
        team_uid = func.add_team(self.api)['uid']
        # приглашаем пользователей
        user1_jid = func.get_my_jid(self.api, team_uid)
        user2_jid = func.add_contact(self.api, team_uid, self.phone2)['jid']
        user3_jid = func.add_contact(self.api, team_uid, self.phone3)['jid']
        # добавляем участников к группе
        group_jid = func.add_group(self.api, team_uid)['jid']
        func.add_member_to_group(self.api, team_uid, group_jid, user2_jid, 'member')
        func.add_member_to_group(self.api, team_uid, group_jid, user3_jid, 'admin')
        # добавляем сообщения
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        api3 = auth.login_another_user(self.url, self.phone3, self.code3)
        pattern = 'msg'
        text = f'{pattern}_{tools.generate_random_string(7)}'
        msg1 = f'1_{text}'
        msg2 = f'2_{text}'
        msg3 = 'hello'
        func.send_text(self.api, team_uid, group_jid, msg1)
        func.send_text(api2, team_uid, group_jid, msg2)
        func.send_text(api3, team_uid, group_jid, msg3)
        params = {
            'text': pattern,
        }
        resp = self.api.get_filtered_messages(team_uid, params).json()
        assert 'error' not in resp
        assert len(resp['result']['objects']) == 2
        assert resp['result']['objects'][0]['content']['text'] == msg2
        assert resp['result']['objects'][1]['content']['text'] == msg1


    @pytest.mark.positive
    @pytest.mark.parametrize("type,text_filename", [
        ('plain', 'hello'),
        ('image', 'tiger.PNG'),
        ('video', 'video.mp4'),
        ('file', 'word.docx'),
    ])
    def test_get_messages_type(self, type, text_filename):
        # создаем команду
        team_uid = func.add_team(self.api)['uid']
        # приглашаем пользователей
        group_jid = func.add_group(self.api, team_uid)['jid']
        # добавляем сообщения
        func.send_text(self.api, team_uid, group_jid, 'hello')
        self.api.send_msg_file(team_uid, group_jid, os.path.join(const.TD_FILES, 'tiger.PNG'))
        self.api.send_msg_file(team_uid, group_jid, os.path.join(const.TD_FILES, 'video.mp4'))
        self.api.send_msg_file(team_uid, group_jid, os.path.join(const.TD_FILES, 'word.docx'))
        params = {
            'type': type,
        }
        resp = self.api.get_filtered_messages(team_uid, params).json()
        assert 'error' not in resp
        assert len(resp['result']['objects']) == 1
        if type == 'plain':
            assert resp['result']['objects'][0]['content']['text'] == text_filename
        else:
            assert resp['result']['objects'][0]['content']['name'] == text_filename


    @pytest.mark.skip
    @pytest.mark.positive
    def test_get_messages_important(self):
        # создаем команду
        team_uid = func.add_team(self.api)['uid']
        group_jid = func.add_group(self.api, team_uid)['jid']
        func.send_text(self.api, team_uid, group_jid, 'hello')
        msg_data = {'text': 'important_message',
                    'important': True}
        #msg_data = json.dumps(msg_data)
        resp = self.api.send_msg_text(team_uid, group_jid, msg_data).json()
        tools.print_formatted_json(resp, ensure_ascii=False)
        params = {
            'important': 'true',
        }
        resp = self.api.get_filtered_messages(team_uid, params).json()
        tools.print_formatted_json(resp, ensure_ascii=False)
        assert 'error' not in resp
        assert len(resp['result']['objects']) == 1
        assert resp['result']['objects'][0]['important']


    @pytest.mark.positive
    def test_get_messages_chat_type(self):
        # создаем команду
        team_uid = func.add_team(self.api)['uid']
        # приглашаем пользователей
        user2_jid = func.add_contact(self.api, team_uid, self.phone2)['jid']
        # добавляем участников к группе
        group_jid = func.add_group(self.api, team_uid)['jid']
        func.add_member_to_group(self.api, team_uid, group_jid, user2_jid, 'member')
        # добавляем сообщения
        pattern = 'msg'
        text = f'{pattern}_{tools.generate_random_string(7)}'
        msg1 = f'1_{text}'
        msg2 = f'2_{text}'
        func.send_text(self.api, team_uid, group_jid, msg1)
        func.send_text(self.api, team_uid, user2_jid, msg2)
        params = {
            'chat_type': 'direct',
        }
        resp = self.api.get_filtered_messages(team_uid, params).json()
        assert 'error' not in resp
        assert len(resp['result']['objects']) == 1
        assert resp['result']['objects'][0]['chat_type'] == 'direct'
        assert resp['result']['objects'][0]['content']['text'] == msg2


    @pytest.mark.positive
    def test_get_messages_date_from_future(self):
        date_from = datetime.datetime.now() + datetime.timedelta(days=1)
        # создаем команду
        team_uid = func.add_team(self.api)['uid']
        # добавляем участников к группе
        group_jid = func.add_group(self.api, team_uid)['jid']
        # добавляем сообщения
        text = f'msg_{tools.generate_random_string(7)}'
        func.send_text(self.api, team_uid, group_jid, text)
        params = {
            'date_from': date_from,
        }
        resp = self.api.get_filtered_messages(team_uid, params).json()
        assert 'error' not in resp
        assert not resp['result']['objects']


    @pytest.mark.positive
    def test_get_messages_date_to_past(self):
        date_to = datetime.datetime.now() + datetime.timedelta(days=-1)
        # создаем команду
        team_uid = func.add_team(self.api)['uid']
        # добавляем участников к группе
        group_jid = func.add_group(self.api, team_uid)['jid']
        # добавляем сообщения
        text = f'msg_{tools.generate_random_string(7)}'
        func.send_text(self.api, team_uid, group_jid, text)
        params = {
            'date_to': date_to,
        }
        resp = self.api.get_filtered_messages(team_uid, params).json()
        assert 'error' not in resp
        assert not resp['result']['objects']
Esempio n. 3
0
import json
import os
import pytest

import helpers.const as const
from helpers.api import API
from helpers.readers import read_yaml
from helpers.tools import generate_random_string, generate_email


config = read_yaml(os.path.join(const.PROJECT, 'config.yaml'))
api_url = config['api_url']
api = API(api_url)


@pytest.fixture
def add_subscriber_fixture():
    def _method(count=1):
        result_list = []
        for i in range(0, count):
            data = {
                'email': generate_email(),
                'name': generate_random_string(),
                'time': '7d',
            }
            api.add_subscriber(json.dumps(data))
            result_list.append(data)
        return result_list
    return _method

class TestsReactions:
    #logging.basicConfig(level=logging.DEBUG)

    config = read_yaml(os.path.join(const.PROJECT, 'config.yaml'))
    user = config['users']['user1']
    phone = config['users']['user1']['phone']
    code = config['users']['user1']['code']

    user2 = config['users']['user2']
    phone2 = config['users']['user2']['phone']
    code2 = config['users']['user2']['code']

    user3 = config['users']['user3']
    phone3 = config['users']['user3']['phone']
    code3 = config['users']['user3']['code']

    user4 = config['users']['user4']
    phone4 = config['users']['user4']['phone']
    code4 = config['users']['user4']['code']

    url = ''
    api = API
    team_uid = ''
    invalid_user_jid = '00000000-0000-0000-0000-77dc6850e494@xmpp'
    invalid_group_jid = '*****@*****.**'
    invalid_team_uid = '00000000-0000-0000-0000-982d4bac29a1'
    invalid_message_id = '00000000-0000-0000-0000-982d4bac29a3'

    reaction1 = '😀'
    reaction2 = '😽'
    reaction3 = '✋'

    def setup_class(self):
        # Логин и создание команды, далее эта команда используется в тестах
        self.url = self.config['api']['url']
        phone = self.user['phone']
        code = self.user['code']
        auth_cookies = auth.login_with_cookies(self.url, phone, code)
        self.api = API(self.url, auth_cookies, is_token_auth=False)
        resp = func.add_team(self.api)
        self.team_uid = resp['uid']
        resp = func.add_group(self.api, self.team_uid)
        self.group_jid = resp['jid']

    def setup_method(self):
        self.url = self.config['api']['url']
        phone = self.user['phone']
        code = self.user['code']
        auth_cookies = auth.login_with_cookies(self.url, phone, code)
        self.api = API(self.url, auth_cookies, is_token_auth=False)

    def teardown_method(self):
        auth.logout(self.url)

    '''    
    Пример для авторизации через токен
    def setup_class(self):
        self.url = self.config['api']['url']
        user = self.config['users']['user1']
        data = {
            'phone': user['phone'],
            'code': user['code'],
            'device_id': user['device_id'],
            'type': user['type']
        }
        token = auth.login_with_token(self.url, data)
        self.api = API(self.url, token)
    '''

    @pytest.mark.positive
    def test_get_all_exist_reactions(self):
        resp = self.api.get_all_exist_reactions().json()
        path = os.path.join(const.EXPECTED_RESULTS, 'reactions.json')
        expected = read_json(path)
        assert 'error' not in resp
        assert resp['result'] == expected['result']

    @pytest.mark.positive
    def test_add_reaction_owner(self):
        owner_jid = func.get_my_jid(self.api, self.team_uid)
        text = f'Hello, my friend {tools.generate_random_string()}'
        message_id = func.send_text(self.api,
                                    self.team_uid,
                                    self.group_jid,
                                    text=text)['message_id']
        resp = self.api.add_edit_reaction(self.team_uid, message_id,
                                          self.reaction1).json()
        assert 'error' not in resp
        assert resp['result']['name'] == self.reaction1
        assert resp['result']['sender'] == owner_jid

    @pytest.mark.negative
    def test_add_invalid_reaction(self):
        text = f'Hello, my friend {tools.generate_random_string()}'
        message_id = func.send_text(self.api,
                                    self.team_uid,
                                    self.group_jid,
                                    text=text)['message_id']
        resp = self.api.add_edit_reaction(self.team_uid, message_id,
                                          ':-)').json()
        assert resp['error'] == const.NOT_FOUND

    @pytest.mark.positive
    def test_add_reaction_member(self):
        # создаем команду
        team_uid = func.add_team(self.api)['uid']
        # добавляем участника
        member_jid = func.add_contact(self.api, team_uid, self.phone2)['jid']
        # добавляем гуппу
        group_jid = func.add_group(self.api, team_uid)['jid']
        # добавляем участника к группе
        func.add_member_to_group(self.api, team_uid, group_jid, member_jid,
                                 'member')
        text = f'Hello, my friend {tools.generate_random_string()}'
        message_id = func.send_text(self.api, team_uid, group_jid,
                                    text=text)['message_id']
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        resp = api2.add_edit_reaction(team_uid, message_id,
                                      self.reaction1).json()
        assert 'error' not in resp
        assert resp['result']['name'] == self.reaction1
        assert resp['result']['sender'] == member_jid

    @pytest.mark.skip
    @pytest.mark.positive
    def test_add_reaction_member_without_group(self):
        # создаем команду
        team_uid = func.add_team(self.api)['uid']
        # добавляем участника
        member_jid = func.add_contact(self.api, team_uid, self.phone2)['jid']
        # добавляем гуппу
        group_jid = func.add_group(self.api, team_uid)['jid']
        # добавляем участника к группе
        #func.add_member_to_group(self.api, team_uid, group_jid, member_jid, 'member')
        text = f'Hello, my friend {tools.generate_random_string()}'
        message_id = func.send_text(self.api, team_uid, group_jid,
                                    text=text)['message_id']
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        resp = api2.add_edit_reaction(team_uid, message_id,
                                      self.reaction1).json()
        tools.print_formatted_json(resp, ensure_ascii=False)
        # ACCESS DENIED должно быть
        assert 'error' not in resp
        assert resp['result']['name'] == self.reaction1
        assert resp['result']['sender'] == member_jid

    @pytest.mark.positive
    def test_edit_reaction_owner(self):
        owner_jid = func.get_my_jid(self.api, self.team_uid)
        text = f'Hello, my friend {tools.generate_random_string()}'
        message_id = func.send_text(self.api,
                                    self.team_uid,
                                    self.group_jid,
                                    text=text)['message_id']
        resp = self.api.add_edit_reaction(self.team_uid, message_id,
                                          self.reaction1).json()
        resp_edit = self.api.add_edit_reaction(self.team_uid, message_id,
                                               self.reaction2).json()
        assert resp['result']['name'] == self.reaction1
        assert 'error' not in resp_edit
        assert resp_edit['result']['name'] == self.reaction2
        assert resp_edit['result']['sender'] == owner_jid

    @pytest.mark.positive
    def test_edit_reaction_member(self):
        # создаем команду
        team_uid = func.add_team(self.api)['uid']
        # добавляем участника
        member_jid = func.add_contact(self.api, team_uid, self.phone2)['jid']
        # добавляем гуппу
        group_jid = func.add_group(self.api, team_uid)['jid']
        # добавляем участника к группе
        func.add_member_to_group(self.api, team_uid, group_jid, member_jid,
                                 'member')
        text = f'Hello, my friend {tools.generate_random_string()}'
        message_id = func.send_text(self.api, team_uid, group_jid,
                                    text=text)['message_id']
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        resp = api2.add_edit_reaction(team_uid, message_id,
                                      self.reaction1).json()
        resp_edit = api2.add_edit_reaction(team_uid, message_id,
                                           self.reaction2).json()
        assert resp['result']['name'] == self.reaction1
        assert 'error' not in resp_edit
        assert resp_edit['result']['name'] == self.reaction2
        assert resp_edit['result']['sender'] == member_jid

    @pytest.mark.positive
    def test_get_reaction_on_message_owner(self):
        owner_jid = func.get_my_jid(self.api, self.team_uid)
        text = f'Hello, my friend {tools.generate_random_string()}'
        message_id = func.send_text(self.api,
                                    self.team_uid,
                                    self.group_jid,
                                    text=text)['message_id']
        self.api.add_edit_reaction(self.team_uid, message_id,
                                   self.reaction1).json()
        resp = self.api.get_my_reaction_by_name(self.team_uid, message_id,
                                                self.reaction1).json()
        assert 'error' not in resp
        assert resp['result']['name'] == self.reaction1
        assert resp['result']['sender'] == owner_jid

    @pytest.mark.negative
    def test_get_reaction_on_message_owner_not_exist_reaction(self):
        text = f'Hello, my friend {tools.generate_random_string()}'
        message_id = func.send_text(self.api,
                                    self.team_uid,
                                    self.group_jid,
                                    text=text)['message_id']
        self.api.add_edit_reaction(self.team_uid, message_id,
                                   self.reaction1).json()
        resp = self.api.get_my_reaction_by_name(self.team_uid, message_id,
                                                self.reaction3).json()
        assert resp['error'] == const.NOT_FOUND

    @pytest.mark.positive
    def test_delete_reaction_owner(self):
        text = f'Hello, my friend {tools.generate_random_string()}'
        message_id = func.send_text(self.api,
                                    self.team_uid,
                                    self.group_jid,
                                    text=text)['message_id']
        self.api.add_edit_reaction(self.team_uid, message_id,
                                   self.reaction1).json()
        resp = self.api.delete_my_reaction(self.team_uid, message_id,
                                           self.reaction1).json()
        resp2 = self.api.get_my_reactions_on_message(self.team_uid,
                                                     message_id).json()
        assert 'error' not in resp
        assert resp['result'] is None
        assert not resp2['result']

    @pytest.mark.negative
    def test_delete_reaction_owner_message_without_reactions(self):
        text = f'Hello, my friend {tools.generate_random_string()}'
        message_id = func.send_text(self.api,
                                    self.team_uid,
                                    self.group_jid,
                                    text=text)['message_id']
        resp = self.api.delete_my_reaction(self.team_uid, message_id,
                                           self.reaction3).json()
        assert 'error' not in resp
        assert resp['result'] is None

    @pytest.mark.positive
    def test_delete_reaction_member(self):
        # создаем команду
        team_uid = func.add_team(self.api)['uid']
        # добавляем участника
        member_jid = func.add_contact(self.api, team_uid, self.phone2)['jid']
        # добавляем гуппу
        group_jid = func.add_group(self.api, team_uid)['jid']
        # добавляем участника к группе
        func.add_member_to_group(self.api, team_uid, group_jid, member_jid,
                                 'member')
        text = f'Hello, my friend {tools.generate_random_string()}'
        message_id = func.send_text(self.api, team_uid, group_jid,
                                    text=text)['message_id']
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        api2.add_edit_reaction(team_uid, message_id, self.reaction1).json()
        resp = api2.delete_my_reaction(team_uid, message_id,
                                       self.reaction1).json()
        resp2 = api2.get_my_reactions_on_message(team_uid, message_id).json()
        assert 'error' not in resp
        assert resp['result'] is None
        assert not resp2['result']

    @pytest.mark.positive
    def test_get_all_my_reactions_owner(self):
        owner_jid = func.get_my_jid(self.api, self.team_uid)
        reactions = [self.reaction1, self.reaction2, self.reaction3]
        text = f'Hello, my friend {tools.generate_random_string()}'
        message_id = func.send_text(self.api,
                                    self.team_uid,
                                    self.group_jid,
                                    text=text)['message_id']
        for reaction in reactions:
            self.api.add_edit_reaction(self.team_uid, message_id,
                                       reaction).json()
        resp = self.api.get_my_reactions_on_message(self.team_uid,
                                                    message_id).json()
        assert 'error' not in resp
        for reaction in reactions:
            assert tools.is_items_exist_in_list_of_dict(
                resp['result'], 'name', reaction)
        for item in resp['result']:
            assert item['sender'] == owner_jid

    @pytest.mark.positive
    def test_get_all_my_reactions_member(self):
        reactions = [self.reaction1, self.reaction2, self.reaction3]
        # создаем команду
        team_uid = func.add_team(self.api)['uid']
        # добавляем участника
        member_jid = func.add_contact(self.api, team_uid, self.phone2)['jid']
        # добавляем гуппу
        group_jid = func.add_group(self.api, team_uid)['jid']
        # добавляем участника к группе
        func.add_member_to_group(self.api, team_uid, group_jid, member_jid,
                                 'member')
        text = f'Hello, my friend {tools.generate_random_string()}'
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        message_id = func.send_text(api2, team_uid, group_jid,
                                    text=text)['message_id']
        for reaction in reactions:
            api2.add_edit_reaction(team_uid, message_id, reaction).json()
        resp = api2.get_my_reactions_on_message(team_uid, message_id).json()
        assert 'error' not in resp
        for reaction in reactions:
            assert tools.is_items_exist_in_list_of_dict(
                resp['result'], 'name', reaction)
        for item in resp['result']:
            assert item['sender'] == member_jid
Esempio n. 5
0
class TestsMain:
    config = read_yaml(os.path.join(const.PROJECT, 'config.yaml'))
    url = config['site_url']
    api_url = config['api_url']

    driver: webdriver
    driver = None

    def setup_class(self):
        self.api = API(self.api_url)
        self.driver = config_and_run_browser(self.config)

        # для запуска локального браузера
        #self.driver = webdriver.Chrome(executable_path="/Users/arkuz/Repos/subscribe_tests/chromedriver")
        #self.driver.maximize_window()

        self.driver.get(self.url)
        self.main_page = MainPage(self.driver)

    def setup_method(self):
        # чистим БД перед каждым тестом
        self.api.delete_subscribers()
        self.driver.refresh()

    def teardown_class(self):
        self.driver.close()

    # тест проверяет успешную подписку с заполнением всех полей
    @pytest.mark.positive
    def test_add_subscriber_success(self):
        expected_res = {
            'name': 'Ivanov Ivan',
            'email': '*****@*****.**',
            'time': True
        }
        time = '7d'
        self.main_page.subscribe_user(
            email=expected_res['email'],
            name=expected_res['name'],
            time=time,
        )
        actual_res = self.main_page.get_row_data(1)
        assert actual_res == expected_res

    # тест проверяет успешную подписку с заполнением всех полей с невалидной датой подписки
    @pytest.mark.positive
    def test_add_subscriber_invalid_time(self):
        expected_res = {
            'name': 'Ivanov Ivan',
            'email': '*****@*****.**',
            'time': False
        }
        time = 'unknown'
        self.main_page.subscribe_user(
            email=expected_res['email'],
            name=expected_res['name'],
            time=time,
        )
        actual_res = self.main_page.get_row_data(1)
        assert actual_res == expected_res

    # тест проверяет, что подписка НЕ оформилась с незаполненным полем email
    @pytest.mark.negative
    def test_add_subscriber_invalid_email(self):
        data = {'name': 'Ivanov Ivan', 'email': '', 'time': '7d'}
        self.main_page.subscribe_user(
            email=data['email'],
            name=data['name'],
            time=data['time'],
        )
        assert self.main_page.get_rows() is None

    # тест проверяет кнопку рефреша
    @pytest.mark.positive
    def test_refresh_button(self, add_subscriber_fixture):
        row_count = 3
        add_subscriber_fixture(row_count)
        self.main_page.refresh_btn_click()
        assert len(self.main_page.get_rows()) == row_count

    # тест поверяет кнопку удаления
    @pytest.mark.positive
    def test_delete_button(self, add_subscriber_fixture):
        add_subscriber_fixture(7)
        self.main_page.refresh_btn_click()
        self.main_page.delete_btn_click()
        assert self.main_page.get_rows() is None

    # тест проверяет, что таблица отображает 5 последних добавленнх зписей
    @pytest.mark.positive
    def test_last_5_subscribers(self, add_subscriber_fixture):
        api_subscribers_list = add_subscriber_fixture(9)
        self.main_page.refresh_btn_click()
        ui_subscribers_list = self.main_page.get_rows_data()
        assert len(ui_subscribers_list) == 5
        api_subscribers_list.reverse()
        expected_res = []
        actual_res = []
        for i in range(0, len(ui_subscribers_list)):
            expected_res.append({
                'email': api_subscribers_list[i]['email'],
                'name': api_subscribers_list[i]['name'],
            })

            actual_res.append({
                'email': ui_subscribers_list[i]['email'],
                'name': ui_subscribers_list[i]['name'],
            })
        assert actual_res == expected_res
Esempio n. 6
0
class TestsAuth:

    config = read_yaml(os.path.join(const.PROJECT, 'config.yaml'))
    user = config['users']['user1']
    url = ''
    api = API

    def setup_method(self):
        self.url = self.config['api']['url']
        phone = self.user['phone']
        code = self.user['code']
        auth_cookies = auth.login_with_cookies(self.url, phone, code)
        self.api = API(self.url, auth_cookies, is_token_auth=False)

    def teardown_method(self):
        auth.logout(self.url)

    '''    
    Пример для авторизации через токен
    def setup_class(self):
        self.url = self.config['api']['url']
        user = self.config['users']['user1']
        data = {
            'phone': user['phone'],
            'code': user['code'],
            'device_id': user['device_id'],
            'type': user['type']
        }
        token = auth.login_with_token(self.url, data)
        self.api = API(self.url, token)
    '''

    @pytest.mark.positive
    @pytest.mark.parametrize(
        "phone, expected",
        [
            ('+79011111111', '+79011111111'),
            ('+7(901)1111111', '+79011111111'),
            ('+7 901 111 11 11', '+79011111111'),
            ('+7 (901) 111 11-11', '+79011111111'),
            ('7(901) 111 11-11', '+79011111111'),
            ('8 901111 11-11', '+79011111111'),
            # ('+994 000 000 00 00', '+9940000000000'), # падают на новом смс сервисе
            # ('+9940000000000', '+9940000000000')
        ])
    def test_sms_login_valid_phone(self, phone, expected):
        resp = self.api.sms_login(phone)
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result']['phone'] == expected

    @pytest.mark.negative
    @pytest.mark.parametrize("phone", [('+7000000000143554'), ('+7000'),
                                       ('+9940000000000444'),
                                       ('9940000000000')])
    def test_sms_login_invalid_phone(self, phone):
        resp = self.api.sms_login(phone)
        resp = resp.json()
        assert resp['error'] == 'INVALID_DATA'
        assert resp['details']['phone'] == 'Некорректный номер телефона'

    @pytest.mark.positive
    def test_sms_auth_exist_device(self):
        user = self.config['users']['user5']
        self.api.sms_login(user['phone'])
        data = {
            'phone': user['phone'],
            'code': user['code'],
            'device_id': user['device_id'],
            'type': user['type']
        }
        resp = self.api.sms_auth(data)
        resp = resp.json()
        assert tools.is_items_exist_in_list_of_dict(
            resp['result']['me']['devices'], 'device_id', user['device_id'])
        assert len(resp['result']['token']) > 0

    @pytest.mark.positive
    def test_sms_auth_new_device(self):
        user = self.config['users']['user5']
        self.api.sms_login(user['phone'])
        device_id = tools.generate_random_string()
        data = {
            'phone': user['phone'],
            'code': user['code'],
            'device_id': device_id,
            'type': 'web'
        }
        resp = self.api.sms_auth(data)
        resp = resp.json()
        assert tools.is_items_exist_in_list_of_dict(
            resp['result']['me']['devices'], 'device_id', device_id)
        assert len(resp['result']['token']) > 0

    @pytest.mark.positive
    def test_sms_cookieauth_valid(self):
        user = self.config['users']['user5']
        self.api.sms_login(user['phone'])
        resp = self.api.sms_cookieauth(user['phone'], user['code'])
        res = resp.json()
        assert 'otvauth=' in resp.headers['Set-Cookie']
        assert res['result']['me']['devices']

    @pytest.mark.positive
    def test_cookieauth_logout_post(self):
        user = self.config['users']['user1']
        self.api.sms_login(user['phone'])
        self.api.sms_cookieauth(user['phone'], user['code'])
        resp = self.api.cookieauth_logout_post()
        assert '<!DOCTYPE html>' in resp.text
        assert 'Set-Cookie' not in resp.headers

    @pytest.mark.positive
    def test_cookieauth_logout_get(self):
        user = self.config['users']['user1']
        self.api.sms_login(user['phone'])
        self.api.sms_cookieauth(user['phone'], user['code'])
        resp = self.api.cookieauth_logout_get()
        assert '<!DOCTYPE html>' in resp.text
        assert 'Set-Cookie' not in resp.headers
Esempio n. 7
0
class TestsTeam:
    config = read_yaml(os.path.join(const.PROJECT, 'config.yaml'))
    user = config['users']['user1']
    phone = config['users']['user1']['phone']
    code = config['users']['user1']['code']

    user2 = config['users']['user2']
    phone2 = config['users']['user2']['phone']
    code2 = config['users']['user2']['code']

    user3 = config['users']['user3']
    phone3 = config['users']['user3']['phone']
    code3 = config['users']['user3']['code']

    user4 = config['users']['user4']
    phone4 = config['users']['user4']['phone']
    code4 = config['users']['user4']['code']
    url = ''
    api = API
    invalid_team_uid = '00000000-0000-0000-0000-982d4bac29a1'

    def setup_method(self):
        self.url = self.config['api']['url']
        phone = self.user['phone']
        code = self.user['code']
        auth_cookies = auth.login_with_cookies(self.url, phone, code)
        self.api = API(self.url, auth_cookies, is_token_auth=False)

    def teardown_method(self):
        auth.logout(self.url)

    '''    
    Пример для авторизации через токен
    def setup_class(self):
        self.url = self.config['api']['url']
        user = self.config['users']['user1']
        data = {
            'phone': user['phone'],
            'code': user['code'],
            'device_id': user['device_id'],
            'type': user['type']
        }
        token = auth.login_with_token(self.url, data)
        self.api = API(self.url, token)
    '''

    @pytest.mark.negative
    def test_add_team_with_empty_name(self):
        data = {'name': ''}
        resp = self.api.add_team(data)
        resp = resp.json()
        assert const.INVALID_DATA == resp['error']
        assert 'Обязательное поле.' == resp['details']['name']

    @pytest.mark.positive
    def test_add_team_with_name_one_symbol(self):
        name = tools.generate_random_string(2)
        data = {'name': name}
        resp = self.api.add_team(data)
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result']['name'] == name

    @pytest.mark.positive
    def test_add_team_with_name_100_symbols(self):
        name = tools.generate_random_string(101)
        data = {'name': name}
        resp = self.api.add_team(data)
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result']['name'] == name

    @pytest.mark.negative
    def test_add_team_with_name_101_symbols(self):
        data = {'name': tools.generate_random_string(102)}
        resp = self.api.add_team(data)
        resp = resp.json()
        assert const.INVALID_DATA == resp['error']
        assert 'Убедитесь, что это значение содержит не более 100 символов (сейчас 101).' == resp[
            'details']['name']

    @pytest.mark.positive
    @pytest.mark.parametrize("first_symbol", ['1', '@', '#', '_ _', 'а', 'Я'])
    def test_add_team_with_name_start_with(self, first_symbol):
        name = first_symbol + tools.generate_random_string(30)
        data = {'name': name}
        resp = self.api.add_team(data)
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result']['name'] == name

    @pytest.mark.positive
    def test_add_team_invite_user_without_firstname_and_lastname(self):
        name = tools.generate_random_string()
        phone = self.config['users']['user2']['phone']
        data = {'name': name, 'contacts': [{'phone': phone}]}
        data_json = json.dumps(data)
        resp = self.api.add_team(data_json).json()
        assert 'error' not in resp
        assert resp['result']['name'] == name
        assert resp['result']['contacts'][0]['contact_phone'] == phone

    @pytest.mark.positive
    def test_get_teams(self):
        resp = self.api.get_teams()
        resp = resp.json()
        assert 'error' not in resp
        for item in resp['result']:
            assert 'name' in item

    @pytest.mark.positive
    @pytest.mark.parametrize("filename",
                             ['tiger', 'TIGER.JPEG', 'tiger.jpg', 'tiger.PNG'])
    def test_upload_team_icon_valid(self, filename):
        '''
        Пока доступны только PNG и JPG
        'tiger.bmp',
        'tiger.gif',
        'tiger.tiff'
        '''
        resp = func.add_team(self.api)
        resp = self.api.upload_team_icon(
            resp['uid'], os.path.join(const.TD_FILES, filename))
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result']['lg']['url']
        assert resp['result']['sm']['url']

    @pytest.mark.negative
    def test_upload_team_icon_member(self):
        team = func.add_team(self.api)
        team_uid = team['uid']
        func.add_contact(self.api, team_uid, self.phone2, role='member')
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        resp = api2.upload_team_icon(team_uid,
                                     os.path.join(const.TD_FILES, 'tiger.jpg'))
        resp = resp.json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.negative
    def test_upload_team_icon_outsider(self):
        resp = func.add_team(self.api)
        api2 = auth.login_another_user(self.url, self.phone4, self.code4)
        resp = api2.upload_team_icon(resp['uid'],
                                     os.path.join(const.TD_FILES, 'tiger.jpg'))
        resp = resp.json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.negative
    @pytest.mark.parametrize("filename", ['tiger.pdf', 'tiger.ico'])
    def test_upload_team_icon_invalid(self, filename):
        resp = func.add_team(self.api)
        resp = self.api.upload_team_icon(
            resp['uid'], os.path.join(const.TD_FILES, filename))
        resp = resp.json()
        assert const.INVALID_DATA == resp['error']
        assert 'Ошибка при загрузке. Пожалуйста, попробуйте ещё раз' == resp[
            'details']['file']

    @pytest.mark.positive
    @pytest.mark.parametrize("exist", ['icon_exist', 'icon_not_exist'])
    def test_delete_team_icon(self, exist):
        resp = func.add_team(self.api)
        team_uid = resp['uid']
        if exist == 'icon_exist':
            self.api.upload_team_icon(
                team_uid, os.path.join(const.TD_FILES, 'tiger.jpg'))
        resp = self.api.delete_team_icon(team_uid)
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result']['lg'] == None
        assert resp['result']['sm'] == None

    @pytest.mark.negative
    def test_delete_team_icon_member(self):
        team_uid = func.add_team(self.api)['uid']
        func.add_contact(self.api, team_uid, self.phone2, role='member')
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        resp = api2.delete_team_icon(team_uid).json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.negative
    def test_delete_team_icon_outsider(self):
        resp = func.add_team(self.api)
        team_uid = resp['uid']
        api2 = auth.login_another_user(self.url, self.phone4, self.code4)
        resp = api2.delete_team_icon(team_uid)
        resp = resp.json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.positive
    def test_get_team_valid_uid(self):
        resp = func.add_team(self.api)
        team_uid = resp['uid']
        name = resp['name']
        resp = self.api.get_team(team_uid)
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result']['uid'] == team_uid
        assert resp['result']['name'] == name

    @pytest.mark.negative
    def test_get_team_invalid_uid(self):
        resp = self.api.get_team(self.invalid_team_uid)
        resp = resp.json()
        assert resp['error'] == 'NOT_FOUND'

    @pytest.mark.positive
    def test_get_team_member(self):
        team = func.add_team(self.api)
        team_uid = team['uid']
        name = team['name']
        func.add_contact(self.api, team_uid, self.phone2, role='member')
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        resp = api2.get_team(team_uid).json()
        assert 'error' not in resp
        assert resp['result']['uid'] == team_uid
        assert resp['result']['name'] == name

    @pytest.mark.negative
    def test_get_team_valid_uid_outsider(self):
        resp = func.add_team(self.api)
        team_uid = resp['uid']
        api2 = auth.login_another_user(self.url, self.phone4, self.code4)
        resp = api2.delete_team(team_uid)
        resp = resp.json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.positive
    def test_edit_team_name_valid(self):
        resp = func.add_team(self.api)
        team_uid = resp['uid']
        new_name = 'new_' + tools.generate_random_string()
        data = {'name': new_name}
        resp = self.api.edit_team(team_uid, data)
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result']['uid'] == team_uid
        assert resp['result']['name'] == new_name

    @pytest.mark.negative
    def test_edit_team_name_member(self):
        team = func.add_team(self.api)
        team_uid = team['uid']
        func.add_contact(self.api, team_uid, self.phone2, role='member')
        new_name = 'new_' + tools.generate_random_string()
        data = {'name': new_name}
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        resp = api2.edit_team(team_uid, data).json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.negative
    def test_edit_team_name_outsider(self):
        resp = func.add_team(self.api)
        team_uid = resp['uid']
        new_name = 'new_' + tools.generate_random_string()
        data = {'name': new_name}
        api2 = auth.login_another_user(self.url, self.phone4, self.code4)
        resp = api2.edit_team(team_uid, data)
        resp = resp.json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.negative
    def test_edit_team_name_empty(self):
        resp = func.add_team(self.api)
        team_uid = resp['uid']
        data = {'name': ''}
        resp = self.api.edit_team(team_uid, data)
        resp = resp.json()
        assert resp['error'] == const.INVALID_DATA
        assert resp['details']['name'] == 'Обязательное поле.'

    @pytest.mark.positive
    def test_delete_exist_team(self):
        resp = func.add_team(self.api)
        team_uid = resp['uid']
        resp = self.api.delete_team(team_uid)
        resp = resp.json()
        resp2 = self.api.get_teams()
        resp2 = resp2.json()
        assert 'error' not in resp
        assert resp['result']['is_archive']
        assert resp['result']['uid'] == team_uid
        for item in resp2['result']:
            assert team_uid != item['uid']

    @pytest.mark.negative
    def test_delete_exist_team_member(self):
        team = func.add_team(self.api)
        team_uid = team['uid']
        func.add_contact(self.api, team_uid, self.phone2, role='member')
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        resp = api2.delete_team(team_uid).json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.negative
    def test_delete_exist_team_outsider(self):
        resp = func.add_team(self.api)
        team_uid = resp['uid']
        api2 = auth.login_another_user(self.url, self.phone4, self.code4)
        resp = api2.delete_team(team_uid)
        resp = resp.json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.negative
    def test_delete_not_exist_team(self):
        resp = self.api.delete_team(self.invalid_team_uid)
        resp = resp.json()
        assert resp['error'] == 'NOT_FOUND'

    @pytest.mark.positive
    def test_get_usage_exist_team(self):
        resp = func.add_team(self.api)
        team_uid = resp['uid']
        resp = self.api.get_team_usage(team_uid)
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result']['uploads_size'] == 0
        assert resp['result']['uploads_size_limit'] == 1073741824

    @pytest.mark.negative
    def test_get_usage_exist_team_member(self):
        team = func.add_team(self.api)
        team_uid = team['uid']
        func.add_contact(self.api, team_uid, self.phone2, role='member')
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        resp = api2.get_team_usage(team_uid).json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.negative
    def test_get_usage_not_exist_team(self):
        resp = self.api.get_team_usage(self.invalid_team_uid)
        resp = resp.json()
        assert resp['error'] == 'NOT_FOUND'

    @pytest.mark.negative
    def test_get_usage_exist_team_outsider(self):
        resp = func.add_team(self.api)
        team_uid = resp['uid']
        api2 = auth.login_another_user(self.url, self.phone4, self.code4)
        resp = api2.get_team_usage(team_uid)
        resp = resp.json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.positive
    def test_send_help(self):
        team = func.add_team(self.api)
        team_uid = team['uid']
        email = '*****@*****.**'
        text = 'I need help'
        resp = self.api.send_help(team_uid, email, text).json()
        assert 'error' not in resp
        assert resp['result'] == 'OK'

    @pytest.mark.positive
    def test_send_help_member(self):
        team = func.add_team(self.api)
        team_uid = team['uid']
        func.add_contact(self.api, team_uid, self.phone2, role='member')
        email = '*****@*****.**'
        text = 'I need help. This is member of team.'
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        resp = api2.send_help(team_uid, email, text).json()
        assert 'error' not in resp
        assert resp['result'] == 'OK'

    @pytest.mark.negative
    def test_send_help_outsider(self):
        team = func.add_team(self.api)
        team_uid = team['uid']
        email = '*****@*****.**'
        text = 'I need help, outsider'
        api4 = auth.login_another_user(self.url, self.phone4, self.code4)
        resp = api4.send_help(team_uid, email, text).json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.positive
    def test_send_help_upload(self):
        team = func.add_team(self.api)
        team_uid = team['uid']
        filename = 'tiger.jpg'
        resp = self.api.send_help_upload(
            team_uid, os.path.join(const.TD_FILES, filename)).json()
        assert 'error' not in resp
        assert resp['result']['name'] == filename
        assert filename in resp['result']['url']
        assert resp['result']['size'] == 456822

    @pytest.mark.positive
    def test_send_help_upload_member(self):
        team = func.add_team(self.api)
        team_uid = team['uid']
        func.add_contact(self.api, team_uid, self.phone2, role='member')
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        filename = 'word.docx'
        resp = api2.send_help_upload(team_uid,
                                     os.path.join(const.TD_FILES,
                                                  filename)).json()
        assert 'error' not in resp
        assert resp['result']['name'] == filename
        assert filename in resp['result']['url']
        assert resp['result']['size'] == 11573

    @pytest.mark.negative
    def test_send_help_upload_outsider(self):
        team = func.add_team(self.api)
        team_uid = team['uid']
        api4 = auth.login_another_user(self.url, self.phone4, self.code4)
        filename = 'word.docx'
        resp = api4.send_help_upload(team_uid,
                                     os.path.join(const.TD_FILES,
                                                  filename)).json()
        assert resp['error'] == const.ACCESS_DENIED
Esempio n. 8
0
class TestsContact:
    config = read_yaml(os.path.join(const.PROJECT, 'config.yaml'))
    user = config['users']['user1']
    phone = config['users']['user1']['phone']
    code = config['users']['user1']['code']

    user2 = config['users']['user2']
    phone2 = config['users']['user2']['phone']
    code2 = config['users']['user2']['code']

    user3 = config['users']['user3']
    phone3 = config['users']['user3']['phone']
    code3 = config['users']['user3']['code']

    user4 = config['users']['user4']
    phone4 = config['users']['user4']['phone']
    code4 = config['users']['user4']['code']

    url = ''
    api = API
    team_uid = ''
    invalid_section_uid = '00000000-0000-0000-0000-982d4bac29a1'
    invalid_user_jid = '00000000-0000-0000-0000-77dc6850e494@xmpp'

    def setup_class(self):
        # Логин и создание команды, далее эта команда используется в тестах
        self.url = self.config['api']['url']
        phone = self.user['phone']
        code = self.user['code']
        auth_cookies = auth.login_with_cookies(self.url, phone, code)
        self.api = API(self.url, auth_cookies, is_token_auth=False)
        resp = func.add_team(self.api)
        self.team_uid = resp['uid']

    def setup_method(self):
        self.url = self.config['api']['url']
        phone = self.user['phone']
        code = self.user['code']
        auth_cookies = auth.login_with_cookies(self.url, phone, code)
        self.api = API(self.url, auth_cookies, is_token_auth=False)

    def teardown_method(self):
        auth.logout(self.url)

    '''    
    Пример для авторизации через токен
    def setup_class(self):
        self.url = self.config['api']['url']
        user = self.config['users']['user1']
        data = {
            'phone': user['phone'],
            'code': user['code'],
            'device_id': user['device_id'],
            'type': user['type']
        }
        token = auth.login_with_token(self.url, data)
        self.api = API(self.url, token)
    '''

    @pytest.mark.negative
    def test_add_section_with_empty_name(self):
        data = {'name': ''}
        resp = self.api.add_section(self.team_uid, data)
        resp = resp.json()
        assert const.INVALID_DATA == resp['error']
        assert 'Обязательное поле.' == resp['details']['name']

    @pytest.mark.positive
    def test_add_section_with_name_one_symbol(self):
        name = tools.generate_random_string(2)
        data = {'name': name}
        resp = self.api.add_section(self.team_uid, data)
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result']['name'] == name

    @pytest.mark.positive
    def test_add_section_with_name_200_symbols(self):
        name = tools.generate_random_string(201)
        data = {'name': name}
        resp = self.api.add_section(self.team_uid, data)
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result']['name'] == name

    @pytest.mark.negative
    def test_add_team_with_name_201_symbols(self):
        data = {'name': tools.generate_random_string(202)}
        resp = self.api.add_section(self.team_uid, data)
        resp = resp.json()
        assert const.INVALID_DATA == resp['error']
        assert 'Убедитесь, что это значение содержит не более 200 символов (сейчас 201).' == resp[
            'details']['name']

    @pytest.mark.positive
    @pytest.mark.parametrize("first_symbol", ['1', '@', '#', '_ _', 'а', 'Я'])
    def test_add_section_with_name_start_with(self, first_symbol):
        name = first_symbol + tools.generate_random_string(30)
        data = {'name': name}
        resp = self.api.add_section(self.team_uid, data)
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result']['name'] == name

    @pytest.mark.negative
    @pytest.mark.parametrize("move", ['move_after', 'move_before'])
    def test_add_section_move_after_before_invalid(self, move):
        data = {'name': 'hello', move: self.invalid_section_uid}
        resp = self.api.add_section(self.team_uid, data)
        resp = resp.json()
        assert const.INVALID_DATA == resp['error']
        assert 'Секция не найдена' == resp['details'][move]

    @pytest.mark.positive
    def test_add_section_move_after(self):
        resp = self.api.get_sections(self.team_uid).json()
        after_uid = resp['result'][-1]['uid']
        name = 'after_' + tools.generate_random_string(10)
        data = {'name': name, 'move_after': after_uid}
        resp = self.api.add_section(self.team_uid, data).json()
        current_uid = resp['result']['uid']
        resp = self.api.get_sections(self.team_uid)
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result'][-2]['uid'] == after_uid
        assert resp['result'][-1]['uid'] == current_uid

    @pytest.mark.positive
    def test_add_section_move_before(self):
        resp = self.api.get_sections(self.team_uid).json()
        before_uid = resp['result'][0]['uid']
        name = 'before_' + tools.generate_random_string(10)
        data = {'name': name, 'move_before': before_uid}
        resp = self.api.add_section(self.team_uid, data).json()
        current_uid = resp['result']['uid']
        resp = self.api.get_sections(self.team_uid)
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result'][1]['uid'] == before_uid
        assert resp['result'][0]['uid'] == current_uid

    @pytest.mark.positive
    def test_get_sections(self):
        resp = self.api.get_sections(self.team_uid)
        resp = resp.json()
        assert 'error' not in resp
        for item in resp['result']:
            assert 'name' in item

    @pytest.mark.positive
    def test_get_sections_member(self):
        team_uid = func.add_team(self.api)['uid']
        func.add_contact(self.api, team_uid, self.phone2, 'member')['jid']
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        resp = api2.get_sections(team_uid)
        resp = resp.json()
        assert 'error' not in resp
        for item in resp['result']:
            assert 'name' in item

    @pytest.mark.negative
    def test_get_sections_outsider(self):
        api2 = auth.login_another_user(self.url, self.phone4, self.code4)
        resp = api2.get_sections(self.team_uid)
        resp = resp.json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.negative
    @pytest.mark.parametrize("move", ['move_after', 'move_before'])
    def test_move_section_invalid(self, move):
        section_uid = func.add_section(self.api, self.team_uid)['uid']
        if move == 'move_after':
            resp = self.api.set_section_move_after(self.team_uid,
                                                   self.invalid_section_uid,
                                                   section_uid)
        else:
            resp = self.api.set_section_move_before(self.team_uid, section_uid,
                                                    self.invalid_section_uid)
        resp = resp.json()
        assert resp['error'] == const.ACCESS_DENIED
        assert 'section "{uid}" not found'.format(
            uid=self.invalid_section_uid) == resp['details']

    @pytest.mark.positive
    def test_move_section_move_after(self):
        resp = self.api.get_sections(self.team_uid).json()
        after_uid = resp['result'][-1]['uid']
        name = 'after_' + tools.generate_random_string(10)
        data = {'name': name, 'move_after': after_uid}
        resp = self.api.add_section(self.team_uid, data).json()
        current_uid = resp['result']['uid']
        self.api.set_section_move_after(self.team_uid, current_uid, after_uid)
        resp = self.api.get_sections(self.team_uid)
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result'][-2]['uid'] == after_uid
        assert resp['result'][-1]['uid'] == current_uid

    @pytest.mark.positive
    def test_move_section_move_before(self):
        resp = self.api.get_sections(self.team_uid).json()
        before_uid = resp['result'][0]['uid']
        name = 'before_' + tools.generate_random_string(10)
        data = {'name': name, 'move_after': before_uid}
        resp = self.api.add_section(self.team_uid, data).json()
        current_uid = resp['result']['uid']
        self.api.set_section_move_before(self.team_uid, current_uid,
                                         before_uid)
        resp = self.api.get_sections(self.team_uid)
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result'][1]['uid'] == before_uid
        assert resp['result'][0]['uid'] == current_uid

    @pytest.mark.positive
    def test_move_section_move_before_admin(self):
        team_uid = func.add_team(self.api)['uid']
        func.add_contact(self.api, team_uid, self.phone2, 'admin')
        resp = self.api.get_sections(team_uid).json()
        before_uid = resp['result'][0]['uid']
        name = 'before_' + tools.generate_random_string(10)
        data = {'name': name, 'move_after': before_uid}
        resp = self.api.add_section(team_uid, data).json()
        current_uid = resp['result']['uid']
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        resp = api2.set_section_move_before(team_uid, current_uid,
                                            before_uid).json()
        resp = self.api.get_sections(team_uid)
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result'][1]['uid'] == before_uid
        assert resp['result'][0]['uid'] == current_uid

    @pytest.mark.negative
    def test_move_section_move_before_member(self):
        team_uid = func.add_team(self.api)['uid']
        func.add_contact(self.api, team_uid, self.phone2, 'member')
        resp = self.api.get_sections(team_uid).json()
        before_uid = resp['result'][0]['uid']
        name = 'before_' + tools.generate_random_string(10)
        data = {'name': name, 'move_after': before_uid}
        resp = self.api.add_section(team_uid, data).json()
        current_uid = resp['result']['uid']
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        resp = api2.set_section_move_before(team_uid, current_uid,
                                            before_uid).json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.negative
    def test_move_section_move_before_outsider(self):
        team_uid = func.add_team(self.api)['uid']
        resp = self.api.get_sections(team_uid).json()
        before_uid = resp['result'][0]['uid']
        name = 'before_' + tools.generate_random_string(10)
        data = {'name': name, 'move_after': before_uid}
        resp = self.api.add_section(team_uid, data).json()
        current_uid = resp['result']['uid']
        api4 = auth.login_another_user(self.url, self.phone4, self.code4)
        resp = api4.set_section_move_before(team_uid, current_uid,
                                            before_uid).json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.positive
    def test_edit_section_without_param(self):
        data = {'name': tools.generate_random_string()}
        exp_dict = self.api.add_section(self.team_uid, data).json()
        section_uid = exp_dict['result']['uid']
        data = {}
        resp = self.api.edit_section(self.team_uid, section_uid, data).json()
        assert 'error' not in resp
        assert resp['result'] == exp_dict['result']

    @pytest.mark.negative
    def test_edit_section_invalid(self):
        data = {}
        resp = self.api.edit_section(self.team_uid, self.invalid_section_uid,
                                     data).json()
        assert resp['error'] == const.ACCESS_DENIED
        assert 'section "{uid}" not found'.format(
            uid=self.invalid_section_uid) == resp['details']

    @pytest.mark.negative
    def test_edit_section_with_empty_name(self):
        data = {'name': tools.generate_random_string()}
        exp_dict = self.api.add_section(self.team_uid, data).json()
        section_uid = exp_dict['result']['uid']
        data = {'name': ''}
        resp = self.api.edit_section(self.team_uid, section_uid, data).json()
        assert resp['error'] == const.INVALID_DATA
        assert 'Обязательное поле.' == resp['details']['name']

    @pytest.mark.positive
    def test_edit_section_with_name(self):
        data = {'name': tools.generate_random_string()}
        exp_dict = self.api.add_section(self.team_uid, data).json()
        section_uid = exp_dict['result']['uid']
        new_name = 'edit_' + tools.generate_random_string()
        data = {'name': new_name}
        resp = self.api.edit_section(self.team_uid, section_uid, data).json()
        assert 'error' not in resp
        assert resp['result']['uid'] == section_uid
        assert resp['result']['name'] == new_name

    @pytest.mark.positive
    def test_edit_section_with_name_admin(self):
        team_uid = func.add_team(self.api)['uid']
        func.add_contact(self.api, team_uid, self.phone2, 'admin')
        data = {'name': tools.generate_random_string()}
        exp_dict = self.api.add_section(team_uid, data).json()
        section_uid = exp_dict['result']['uid']
        new_name = 'edit_' + tools.generate_random_string()
        data = {'name': new_name}
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        resp = api2.edit_section(team_uid, section_uid, data).json()
        assert 'error' not in resp
        assert resp['result']['uid'] == section_uid
        assert resp['result']['name'] == new_name

    @pytest.mark.negative
    def test_edit_section_with_name_member(self):
        team_uid = func.add_team(self.api)['uid']
        func.add_contact(self.api, team_uid, self.phone2, 'member')
        data = {'name': tools.generate_random_string()}
        exp_dict = self.api.add_section(team_uid, data).json()
        section_uid = exp_dict['result']['uid']
        new_name = 'edit_' + tools.generate_random_string()
        data = {'name': new_name}
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        resp = api2.edit_section(team_uid, section_uid, data).json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.negative
    def test_edit_section_with_name_outsider(self):
        team_uid = func.add_team(self.api)['uid']
        data = {'name': tools.generate_random_string()}
        exp_dict = self.api.add_section(team_uid, data).json()
        section_uid = exp_dict['result']['uid']
        new_name = 'edit_' + tools.generate_random_string()
        data = {'name': new_name}
        api4 = auth.login_another_user(self.url, self.phone4, self.code4)
        resp = api4.edit_section(team_uid, section_uid, data).json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.positive
    def test_delete_exist_section(self):
        data = {'name': tools.generate_random_string()}
        exp_dict = self.api.add_section(self.team_uid, data).json()
        section_uid = exp_dict['result']['uid']
        resp = self.api.delete_section(self.team_uid, section_uid).json()
        resp2 = self.api.get_sections(self.team_uid).json()
        assert 'error' not in resp
        assert resp['result'] is None
        for item in resp2['result']:
            assert section_uid != item['uid']

    @pytest.mark.negative
    def test_delete_not_exist_section(self):
        resp = self.api.delete_section(self.team_uid,
                                       self.invalid_section_uid).json()
        assert resp['error'] == const.ACCESS_DENIED
        assert 'section "{uid}" not found'.format(
            uid=self.invalid_section_uid) == resp['details']

    @pytest.mark.negative
    def test_delete_exist_section_member(self):
        team_uid = func.add_team(self.api)['uid']
        func.add_contact(self.api, team_uid, self.phone2, 'member')
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        data = {'name': tools.generate_random_string()}
        exp_dict = self.api.add_section(team_uid, data).json()
        section_uid = exp_dict['result']['uid']
        resp = api2.delete_section(team_uid, section_uid).json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.negative
    def test_delete_section_outsider(self):
        data = {'name': tools.generate_random_string()}
        exp_dict = self.api.add_section(self.team_uid, data).json()
        section_uid = exp_dict['result']['uid']
        api2 = auth.login_another_user(self.url, self.phone4, self.code4)
        resp = api2.delete_section(self.team_uid, section_uid).json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.negative
    def test_invite_one_contact_empty(self):
        resp = func.add_team(self.api)
        team_uid = resp['uid']
        data = {}
        resp = self.api.add_contacts(team_uid, data).json()
        assert resp['error'] == const.INVALID_DATA
        assert 'Обязательное поле.' == resp['details']['phone']

    @pytest.mark.positive
    def test_invite_one_contact_only_phone(self):
        resp = func.add_team(self.api)
        team_uid = resp['uid']
        data = {'phone': self.phone2}
        resp = self.api.add_contacts(team_uid, data).json()
        resp2 = self.api.get_contacts(team_uid).json()
        assert 'error' not in resp
        assert self.phone2 == resp['result']['contact_phone']
        assert self.phone2 == resp2['result'][0]['contact_phone']

    @pytest.mark.positive
    def test_invite_one_contact_all_params(self):
        team_uid = func.add_team(self.api)['uid']
        section_uid = func.add_section(self.api, team_uid)['uid']
        data = {
            'family_name': 'Фамилия',
            'given_name': 'Имя',
            'phone': self.phone2,
            'role': 'пресс-секретарь',
            'section': section_uid,
            'status': 'admin'
        }
        resp = self.api.add_contacts(team_uid, data).json()
        resp2 = self.api.get_contacts(team_uid).json()
        resp2 = resp2['result'][0]
        exp_data = {
            'family_name': resp2['family_name'],
            'given_name': resp2['given_name'],
            'phone': resp2['contact_phone'],
            'role': resp2['role'],
            'section': resp2['section_uid'],
            'status': resp2['status']
        }
        assert 'error' not in resp
        assert self.phone2 == resp['result']['contact_phone']
        assert exp_data == data

    @pytest.mark.negative
    def test_invite_one_contact_section_invalid(self):
        resp = func.add_team(self.api)
        team_uid = resp['uid']
        data = {"phone": self.phone2, "section": self.invalid_section_uid}
        resp = self.api.add_contacts(team_uid, data).json()
        assert resp['error'] == const.INVALID_DATA
        assert "Некорректная секция: '{uid}'".format(
            uid=self.invalid_section_uid) == resp['details']['section']

    @pytest.mark.positive
    def test_invite_2_contacts_only_phone(self):
        resp = func.add_team(self.api)
        team_uid = resp['uid']
        data = {'contacts': [{'phone': self.phone2}, {'phone': self.phone3}]}
        data_json = json.dumps(data)
        resp = self.api.add_contacts(team_uid, data_json).json()
        assert 'error' not in resp
        assert self.phone2 == resp['result']['contacts'][0]['contact_phone']
        assert self.phone3 == resp['result']['contacts'][1]['contact_phone']

    @pytest.mark.positive
    def test_invite_2_contacts_all_params(self):
        team_uid = func.add_team(self.api)['uid']
        section_uid = func.add_section(self.api, team_uid)['uid']
        data = {
            'contacts': [
                {
                    'family_name': 'Первов',
                    'given_name': 'Первый',
                    'phone': self.phone2,
                    'role': 'пресс-секретарь',
                    'section': section_uid,
                    'status': 'admin'
                },
                {
                    'family_name': 'Второв',
                    'given_name': 'Второй',
                    'phone': self.phone3,
                    'role': 'член КПСС',
                    'section': section_uid,
                    "status": 'member'
                },
            ]
        }
        data_json = json.dumps(data)
        resp = self.api.add_contacts(team_uid, data_json).json()
        data1 = data['contacts'][0]
        data2 = data['contacts'][1]
        cont1 = resp['result']['contacts'][0]
        cont2 = resp['result']['contacts'][1]
        assert 'error' not in resp
        assert data1['family_name'] == cont1['family_name']
        assert data1['given_name'] == cont1['given_name']
        assert data1['phone'] == cont1['contact_phone']
        assert data1['role'] == cont1['role']
        assert data1['section'] == cont1['section_uid']
        assert data1['status'] == cont1['status']
        assert data2['family_name'] == cont2['family_name']
        assert data2['given_name'] == cont2['given_name']
        assert data2['phone'] == cont2['contact_phone']
        assert data2['role'] == cont2['role']
        assert data2['section'] == cont2['section_uid']
        assert data2['status'] == cont2['status']

    @pytest.mark.negative
    def test_invite_2_contacts_with_invalid_section_uid(self):
        team_uid = func.add_team(self.api)['uid']
        data = {
            'contacts': [{
                'phone': self.phone2,
                'section': self.invalid_section_uid,
            }, {
                'phone': self.phone3,
                'section': self.invalid_section_uid,
            }]
        }
        data_json = json.dumps(data)
        resp = self.api.add_contacts(team_uid, data_json).json()
        assert resp['error'] == const.INVALID_DATA
        assert "Некорректная секция: '{uid}'".format(
            uid=self.invalid_section_uid
        ) == resp['details']['contacts'][0]['section']
        assert "Некорректная секция: '{uid}'".format(
            uid=self.invalid_section_uid
        ) == resp['details']['contacts'][1]['section']

    @pytest.mark.positive
    def test_invite_2_contacts_with_different_section(self):
        team_uid = func.add_team(self.api)['uid']
        section_uid1 = func.add_section(self.api, team_uid)['uid']
        section_uid2 = func.add_section(self.api, team_uid)['uid']
        data = {
            'contacts': [{
                'phone': self.phone2,
                'section': section_uid1,
            }, {
                'phone': self.phone3,
                'section': section_uid2,
            }]
        }
        data_json = json.dumps(data)
        resp = self.api.add_contacts(team_uid, data_json).json()
        data1 = data['contacts'][0]
        data2 = data['contacts'][1]
        assert 'error' not in resp
        assert data1['phone'] == resp['result']['contacts'][0]['contact_phone']
        assert data1['section'] == resp['result']['contacts'][0]['section_uid']
        assert data2['phone'] == resp['result']['contacts'][1]['contact_phone']
        assert data2['section'] == resp['result']['contacts'][1]['section_uid']

    @pytest.mark.positive
    def test_invite_contact_member_admin(self):
        team_uid = func.add_team(self.api)['uid']
        data = {'phone': self.phone2, 'status': 'admin'}
        self.api.add_contacts(team_uid, data)
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        data = {'phone': self.phone3}
        resp = api2.add_contacts(team_uid, data).json()
        resp2 = self.api.get_contacts(team_uid).json()
        assert 'error' not in resp
        assert self.phone3 == resp['result']['contact_phone']
        assert self.phone3 == resp2['result'][0]['contact_phone']

    @pytest.mark.negative
    def test_invite_contact_member_not_admin(self):
        team_uid = func.add_team(self.api)['uid']
        data = {'phone': self.phone2, 'status': 'member'}
        self.api.add_contacts(team_uid, data)
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        data = {'phone': self.phone3}
        resp = api2.add_contacts(team_uid, data).json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.negative
    def test_invite_contact_outsider(self):
        team_uid = func.add_team(self.api)['uid']
        data = {'phone': self.phone2, 'status': 'member'}
        self.api.add_contacts(team_uid, data)
        api2 = auth.login_another_user(self.url, self.phone4, self.code4)
        data = {'phone': self.phone3}
        resp = api2.add_contacts(team_uid, data).json()
        assert resp['error'] == const.ACCESS_DENIED

    @pytest.mark.positive
    def test_get_contacts(self):
        resp = self.api.get_contacts(self.team_uid)
        resp = resp.json()
        assert 'error' not in resp
        for item in resp['result']:
            assert 'contact_phone' in item

    @pytest.mark.positive
    @pytest.mark.parametrize("filename", [
        'tiger',
        'TIGER.JPEG',
        'tiger.jpg',
        'tiger.PNG',
    ])
    def test_upload_contact_icon_valid(self, filename):
        '''
        Пока доступны только PNG и JPG
        'tiger.bmp',
        'tiger.gif',
        'tiger.tiff'
        '''
        resp = self.api.get_contacts(self.team_uid).json()
        contact_jid = resp['result'][0]['jid']
        resp = self.api.upload_contact_icon(
            self.team_uid, contact_jid, os.path.join(const.TD_FILES, filename))
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result']['lg']['url']
        assert resp['result']['sm']['url']

    @pytest.mark.negative
    @pytest.mark.parametrize("filename", ['tiger.pdf', 'tiger.ico'])
    def test_upload_contact_icon_invalid(self, filename):
        resp = self.api.get_contacts(self.team_uid).json()
        contact_jid = resp['result'][0]['jid']
        resp = self.api.upload_contact_icon(
            self.team_uid, contact_jid, os.path.join(const.TD_FILES, filename))
        resp = resp.json()
        assert const.INVALID_DATA == resp['error']
        assert 'Ошибка при загрузке. Пожалуйста, попробуйте ещё раз' == resp[
            'details']['file']

    @pytest.mark.negative
    def test_upload_contact_icon_another_user(self):
        resp = self.api.get_contacts(self.team_uid).json()
        contact_jid = resp['result'][0]['jid']
        api2 = auth.login_another_user(self.url, self.phone4, self.code4)
        resp = api2.upload_contact_icon(
            self.team_uid, contact_jid,
            os.path.join(const.TD_FILES, 'tiger.jpg'))
        resp = resp.json()
        assert const.ACCESS_DENIED == resp['error']

    @pytest.mark.positive
    @pytest.mark.parametrize("exist", ['icon_exist', 'icon_not_exist'])
    def test_delete_contact_icon(self, exist):
        team_uid = func.add_team(self.api)['uid']
        resp = self.api.get_contacts(self.team_uid).json()
        contact_jid = resp['result'][0]['jid']
        if exist == 'icon_exist':
            self.api.upload_contact_icon(
                team_uid, contact_jid, os.path.join(const.TD_FILES,
                                                    'tiger.jpg'))
        resp = self.api.delete_contact_icon(self.team_uid, contact_jid)
        resp = resp.json()
        assert 'error' not in resp
        assert resp['result']['lg'] == None
        assert resp['result']['sm'] == None

    @pytest.mark.negative
    def test_delete_contact_icon_another_user(self):
        team_uid = func.add_team(self.api)['uid']
        resp = self.api.get_contacts(team_uid).json()
        contact_jid = resp['result'][0]['jid']
        api2 = auth.login_another_user(self.url, self.phone4, self.code4)
        resp = api2.delete_contact_icon(self.team_uid, contact_jid)
        resp = resp.json()
        assert const.ACCESS_DENIED == resp['error']

    @pytest.mark.positive
    def test_get_contact_valid_jid(self):
        resp = self.api.get_contacts(self.team_uid).json()
        contact_jid = resp['result'][0]['jid']
        phone = resp['result'][0]['contact_phone']
        resp = self.api.get_contact(self.team_uid, contact_jid).json()
        assert 'error' not in resp
        assert contact_jid == resp['result']['jid']
        assert phone == resp['result']['contact_phone']

    @pytest.mark.negative
    def test_get_contact_invalid_jid(self):
        resp = self.api.get_contact(self.team_uid,
                                    self.invalid_user_jid).json()
        assert const.NOT_FOUND == resp['error']

    @pytest.mark.positive
    @pytest.mark.parametrize("role", ['admin', 'member'])
    def test_get_contact_another_user_role(self, role):
        team_uid = func.add_team(self.api)['uid']
        data = {'phone': self.phone2, 'status': role}
        self.api.add_contacts(team_uid, data)
        resp = self.api.get_contacts(team_uid).json()
        contact_jid = resp['result'][1]['jid']
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        resp = api2.get_contact(team_uid, contact_jid).json()
        assert 'error' not in resp
        assert contact_jid == resp['result']['jid']

    @pytest.mark.negative
    def test_get_contact_outsider(self):
        team_uid = func.add_team(self.api)['uid']
        resp = self.api.get_contacts(team_uid).json()
        contact_jid = resp['result'][0]['jid']
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        resp = api2.get_contact(team_uid, contact_jid).json()
        assert const.ACCESS_DENIED == resp['error']

    @pytest.mark.positive
    def test_edit_contact_valid(self):
        team_uid = func.add_team(self.api)['uid']
        data = {'phone': self.phone2}
        self.api.add_contacts(team_uid, data)
        resp = self.api.get_contacts(team_uid).json()
        contact_jid = resp['result'][0]['jid']
        data = {
            'family_name': 'Brown',
            'given_name': 'Jack',
            'contact_phone': '+70000000000',
            'role': 'Secret Agent',
            'status': 'admin',
            'contact_email': '*****@*****.**'
        }
        res = self.api.edit_contact(team_uid, contact_jid, data).json()
        resp = res['result']
        exp_data = {
            'family_name': resp['family_name'],
            'given_name': resp['given_name'],
            'contact_phone': resp['contact_phone'],
            'role': resp['role'],
            'status': resp['status'],
            'contact_email': resp['contact_email']
        }
        assert 'error' not in res
        assert data == exp_data

    @pytest.mark.positive
    def test_edit_contact_with_empty_data(self):
        team_uid = func.add_team(self.api)['uid']
        data = {'phone': self.phone2}
        self.api.add_contacts(team_uid, data)
        resp = self.api.get_contacts(team_uid).json()
        contact_jid = resp['result'][0]['jid']
        act_data = {
            'family_name': resp['result'][0]['family_name'],
            'given_name': resp['result'][0]['given_name'],
            'contact_phone': resp['result'][0]['contact_phone'],
            'role': resp['result'][0]['role'],
            'status': resp['result'][0]['status'],
            'contact_email': resp['result'][0]['contact_email']
        }
        data = {}
        res = self.api.edit_contact(team_uid, contact_jid, data).json()
        resp = res['result']
        exp_data = {
            'family_name': resp['family_name'],
            'given_name': resp['given_name'],
            'contact_phone': resp['contact_phone'],
            'role': resp['role'],
            'status': resp['status'],
            'contact_email': resp['contact_email']
        }
        assert 'error' not in res
        assert act_data == exp_data

    @pytest.mark.positive
    def test_edit_contact_another_user_admin(self):
        # создаем команду
        team_uid = func.add_team(self.api)['uid']
        # добавляем контакт с правами админа
        data = {'phone': self.phone2, 'status': 'admin'}
        self.api.add_contacts(team_uid, data)
        # получаем jid овнера команды
        resp = self.api.get_contacts(team_uid).json()
        contact_jid = resp['result'][1]['jid']
        # изменяем контакт овнера вторым узером админом
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        data = {'family_name': 'Test'}
        resp = api2.edit_contact(team_uid, contact_jid, data).json()
        assert 'error' not in resp
        assert data['family_name'] == resp['result']['family_name']

    @pytest.mark.negative
    def test_edit_contact_another_user_not_admin(self):
        # создаем команду
        team_uid = func.add_team(self.api)['uid']
        # добавляем контакт с правами админа
        data = {'phone': self.phone2, 'status': 'member'}
        self.api.add_contacts(team_uid, data)
        # получаем jid овнера команды
        resp = self.api.get_contacts(team_uid).json()
        contact_jid = resp['result'][1]['jid']
        # изменяем контакт овнера вторым узером админом
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        data = {'family_name': 'Test'}
        resp = api2.edit_contact(team_uid, contact_jid, data).json()
        assert const.ACCESS_DENIED == resp['error']

    @pytest.mark.negative
    def test_edit_contact_outsider(self):
        # создаем команду
        team_uid = func.add_team(self.api)['uid']
        # получаем jid овнера команды
        resp = self.api.get_contacts(team_uid).json()
        contact_jid = resp['result'][0]['jid']
        # изменяем контакт овнера пользователем не состоящим в команде
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        data = {'family_name': 'Test'}
        resp = api2.edit_contact(team_uid, contact_jid, data).json()
        assert const.ACCESS_DENIED == resp['error']

    @pytest.mark.positive
    def test_delete_exist_contact(self):
        # создаем команду
        team_uid = func.add_team(self.api)['uid']
        # добавляем контакт с правами админа
        data = {'phone': self.phone2, 'status': 'admin'}
        self.api.add_contacts(team_uid, data)
        # получаем jid нового контакта команды
        resp = self.api.get_contacts(team_uid).json()
        contact_jid = resp['result'][0]['jid']
        resp = self.api.delete_contact(team_uid, contact_jid).json()
        resp2 = self.api.get_contacts(team_uid).json()
        assert 'error' not in resp
        assert resp['result']['is_archive']
        assert resp2['result'][0]['is_archive']
        assert contact_jid == resp2['result'][0]['jid']

    @pytest.mark.negative
    def test_delete_not_exist_contact(self):
        team_uid = func.add_team(self.api)['uid']
        resp = self.api.delete_contact(team_uid, self.invalid_user_jid).json()
        assert const.NOT_FOUND == resp['error']

    @pytest.mark.positive
    def test_delete_contact_another_user_admin(self):
        # создаем команду
        team_uid = func.add_team(self.api)['uid']
        # добавляем контакт с правами админа
        data = {'phone': self.phone2, 'status': 'admin'}
        self.api.add_contacts(team_uid, data)
        # добавляем контакт с обычными правами
        data = {'phone': self.phone3, 'status': 'member'}
        self.api.add_contacts(team_uid, data)
        # получаем jid последнего добавленного участника
        resp = self.api.get_contacts(team_uid).json()
        contact_jid = resp['result'][0]['jid']
        # удаляем контакт вторым узером админом
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        resp = api2.delete_contact(team_uid, contact_jid).json()
        resp2 = api2.get_contacts(team_uid).json()
        assert 'error' not in resp
        assert resp['result']['is_archive']
        assert resp2['result'][0]['is_archive']
        assert contact_jid == resp2['result'][0]['jid']

    @pytest.mark.negative
    def test_delete_contact_outsider(self):
        # создаем команду
        team_uid = func.add_team(self.api)['uid']
        # получаем jid овнера команды
        resp = self.api.get_contacts(team_uid).json()
        contact_jid = resp['result'][0]['jid']
        # пытаемся удалить контакт овнера пользователем из другой команды
        api2 = auth.login_another_user(self.url, self.phone2, self.code2)
        resp = api2.delete_contact(team_uid, contact_jid).json()
        assert const.ACCESS_DENIED == resp['error']
Esempio n. 9
0
class TestsSubscribe:
    config = read_yaml(os.path.join(const.PROJECT, 'config.yaml'))
    api_url = config['api_url']

    def setup_class(self):
        self.api = API(self.api_url)

    def setup_method(self):
        # чистим БД перед каждым тестом
        self.api.delete_subscribers()

    # тест проверяет невозможность добавления подписчика без указния параметров
    @pytest.mark.negative
    def test_add_subscriber_empty_params(self):
        data = {}
        data = json.dumps(data)
        resp = self.api.add_subscriber(data)
        assert resp.status_code == STATUS_BAD
        assert resp.json()['message'] == 'Internal Server Error'

    # тест проверяет невозможность добавления подписчика с некорректным email
    @pytest.mark.negative
    def test_add_subscriber_email_invalid(self):
        email = tools.generate_random_string()
        data = {'email': email, 'name': 'Ivan', 'time': '7d'}
        data = json.dumps(data)
        resp = self.api.add_subscriber(data)
        assert resp.status_code == STATUS_OK
        assert resp.json(
        )['error'] == f"ValidationError (SubscriptionModel:None) (Invalid email address: {email}: ['email'])"

    # тест проверяет добавление подписчика при валидном email и остальных параметрах (пустых или заполненных, в том числе с длиной строки = 1000)
    @pytest.mark.positive
    @pytest.mark.parametrize("email,name,time,comment", [
        (tools.generate_email(), '', '', ''),
        (tools.generate_email(), tools.generate_random_string(), '7d',
         tools.generate_random_string()),
        (tools.generate_email(), tools.generate_random_string(1000),
         tools.generate_random_string(1000),
         tools.generate_random_string(1000)),
    ])
    def test_add_subscriber_with_email_and_any_params(self, email, name, time,
                                                      comment):
        data = {
            'email': email,
            'name': name,
            'time': time,
            'comment': comment,
        }
        data = json.dumps(data)
        resp = self.api.add_subscriber(data)
        assert resp.status_code == STATUS_OK
        resp = resp.json()
        assert resp['id'] == self.api.get_subscribers().json()[0]['id']

    # тест проверяет удаление подписчиков
    @pytest.mark.positive
    def test_delete_subscribers(self, add_subscriber_fixture):
        count = 5
        add_subscriber_fixture(count)
        resp = self.api.delete_subscribers()
        assert resp.status_code == STATUS_OK
        resp = resp.json()
        assert resp['removed'] == count
        assert not self.api.get_subscribers().json()

    # тест проверяет получение списка подписчиков
    @pytest.mark.positive
    def test_get_subscribers(self, add_subscriber_fixture):
        expected_subs = add_subscriber_fixture(5)
        expected_keys = expected_subs[0]
        resp = self.api.get_subscribers()
        assert resp.status_code == STATUS_OK
        actual_subs = resp.json()
        assert len(actual_subs) == len(expected_subs)
        # проверяем, что ключи и значения добавленных подписчиков есть в актуальном ответе сервера
        for item in actual_subs:
            for k, v in item.items():
                if k in expected_keys:
                    assert tools.is_items_exist_in_list_of_dict(
                        expected_subs, k, v)

    # тест проверяет корректность сроков подписки
    # невалидные параметры устанавливают expired_at == created_at
    @pytest.mark.positive
    @pytest.mark.parametrize("time,delta_sec", [
        ('unknown', 0.0),
        ('6y', 0.0),
        ('23', 0.0),
        ('1D', 0.0),
        ('22H', 0.0),
        ('105M', 0.0),
        ('50S', 0.0),
        ('1d', 86400.0),
        ('22h', 79200.0),
        ('105m', 6300.0),
        ('50s', 50.0),
    ])
    def test_check_subscribe_time(self, time, delta_sec):
        data = {
            'email': tools.generate_email(),
            'name': tools.generate_random_string(),
            'time': time,
        }
        data = json.dumps(data)
        self.api.add_subscriber(data)
        resp = self.api.get_subscribers().json()[0]
        created_at = isoparser.parse(resp['created_at'])
        expired_at = isoparser.parse(resp['expired_at'])
        # вычисляем срок подписки в секундах и допускаем разницу между датами в 0.5 секунды
        delta = expired_at - created_at
        acceptable_delta = abs(delta.total_seconds() - delta_sec)
        assert 0 <= acceptable_delta <= 0.5
Esempio n. 10
0
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

from helpers.readers import read_yaml
from helpers.writers import write_yaml
import helpers.const as const

config_path = os.path.join(const.PROJECT, 'config.yaml')
config = read_yaml(config_path)

config['users']['user1'] = config['users']['user8']
config['users']['user2'] = config['users']['user9']
config['users']['user3'] = config['users']['user10']
config['users']['user4'] = config['users']['user11']

try:
    write_yaml(config_path, config)
    print('Users changed')
    exit(0)
except Exception:
    print('Error')
    exit(1)