コード例 #1
0
ファイル: test_main.py プロジェクト: dzionek/channels
 def wrapper(*args, **kwargs) -> None:
     """Wrapper of the decorator."""
     db.session.add(
         User(username='******',
              password=hash_password('testPassword'),
              email='*****@*****.**'))
     db.session.add(
         User(username='******',
              password=hash_password('testPassword2'),
              email='*****@*****.**'))
     db.session.add(Channel(name='channel', password='******'))
     db.session.add(ChannelAllowList(channel_id=1, user_id=1))
     func(*args, **kwargs)
コード例 #2
0
ファイル: utils.py プロジェクト: dzionek/channels
def process_add_channel_form(form: AddChannelForm) -> Response:
    """Get the validated form to add a channel. Hash the given password of the channel.
    Set the current user admin role on this channel. Save all of that in the database.

    Args:
        form: The filled form to add a channel.

    """
    hashed_password = hash_password(form.password.data)

    db.session.add(Channel(
        name=form.name.data, password=hashed_password
    ))

    channel_id = Channel.query.filter_by(password=hashed_password).first().id

    db.session.add(ChannelAllowList(
        channel_id=channel_id, user_id=current_user.id, user_role=UserRole.ADMIN.value
    ))

    db.session.commit()

    flash(f'You have successfully added the channel "{form.name.data}"!', 'success')

    return redirect(url_for('main.setup_app'))
コード例 #3
0
ファイル: test_main.py プロジェクト: dzionek/channels
    def test_channel_settings(self) -> None:
        db.session.add(
            User(username='******',
                 password=hash_password('testPassword'),
                 email='*****@*****.**'))
        db.session.add(Channel(name='channel', password='******'))
        db.session.add(ChannelAllowList(channel_id=1, user_id=1))

        with app.test_client() as c:
            rv = c.get('/channel/channel', follow_redirects=True)
            assert 'Please log in to access this page' in str(rv.data)

            rv = login(c, '*****@*****.**', 'testPassword')
            assert 'Log out' in str(rv.data)

            rv = c.get('/channel/channel', follow_redirects=True)
            assert 'Number of users:' not in str(rv.data)
            assert "you don't have necessary permission" in decode_bytecode_single_quote(
                rv.data)

            ChannelAllowList.query.first().user_role = UserRole.ADMIN.value

            rv = c.get('/channel/channel', follow_redirects=True)
            assert 'Number of users:' in str(rv.data)

            rv = c.get('/channel/channel_second', follow_redirects=True)
            assert 'Number of users:' not in str(rv.data)
            assert "channel doesn't exist" in decode_bytecode_single_quote(
                rv.data)
コード例 #4
0
ファイル: test_main.py プロジェクト: dzionek/channels
    def test_is_admin_ajax(self) -> None:
        db.session.add(
            User(username='******',
                 password=hash_password('testPassword'),
                 email='*****@*****.**'))
        db.session.add(Channel(name='channel', password='******'))
        db.session.add(ChannelAllowList(channel_id=1, user_id=1))

        with app.test_client() as c:
            rv = c.post('/is-admin',
                        data={'channelName': 'channel'},
                        follow_redirects=True)
            assert 'response' not in str(rv.data)

            rv = login(c, '*****@*****.**', 'testPassword')
            assert 'Log out' in str(rv.data)

            # User is not admin of the channel.
            rv = c.post('/is-admin',
                        data={'channelName': 'channel'},
                        follow_redirects=True)
            assert 'response' in str(rv.data)

            json = eval(
                rv.data.decode('utf8').replace('false', 'False').replace(
                    'true', 'True'))
            assert not json['response']

            ChannelAllowList.query.first().user_role = UserRole.ADMIN.value

            # User is admin of the channel
            rv = c.post('/is-admin',
                        data={'channelName': 'channel'},
                        follow_redirects=True)
            assert 'response' in str(rv.data)

            json = eval(
                rv.data.decode('utf8').replace('false', 'False').replace(
                    'true', 'True'))
            assert json['response']

            # No channel given in the form
            rv = c.post('/is-admin', follow_redirects=True)
            assert 'response' in str(rv.data)

            json = eval(
                rv.data.decode('utf8').replace('false', 'False').replace(
                    'true', 'True'))
            assert not json['response']

            # Channel given in the form doesn't exist
            rv = c.post('/is-admin',
                        data={'channelName': 'channel_second'},
                        follow_redirects=True)
            assert 'response' in str(rv.data)

            json = eval(
                rv.data.decode('utf8').replace('false', 'False').replace(
                    'true', 'True'))
            assert not json['response']
コード例 #5
0
ファイル: test_main.py プロジェクト: dzionek/channels
    def test_get_initial_counter_ajax(self) -> None:
        db.session.add(
            User(username='******',
                 password=hash_password('testPassword'),
                 email='*****@*****.**'))
        db.session.add(Channel(name='channel', password='******'))

        with app.test_client() as c:
            rv = c.post('/get-messages',
                        data={'channelName': 'channel'},
                        follow_redirects=True)
            assert 'counter' not in str(rv.data)

            rv = login(c, '*****@*****.**', 'testPassword')
            assert 'Log out' in str(rv.data)

            rv = c.post('/initial-counter',
                        data={'channelName': 'channel'},
                        follow_redirects=True)
            assert 'counter' in str(rv.data)
            json = eval(rv.data.decode('utf8'))
            assert json['counter'] == 0

            for _ in range(20):
                db.session.add(
                    Message(content='&',
                            target_channel=1,
                            author_id=1,
                            time=datetime.utcnow()))

            rv = c.post('/initial-counter',
                        data={'channelName': 'channel'},
                        follow_redirects=True)
            json = eval(rv.data.decode('utf8'))
            assert json['counter'] == 20
コード例 #6
0
    def test_channel(self) -> None:
        db.session.add(
            User(username='******',
                 password=hash_password('testPassword'),
                 email='*****@*****.**'))
        db.session.add(Channel(name='channel', password=hash_password('pass')))
        db.session.add(ChannelAllowList(user_id=1, channel_id=1))
        db.session.add(
            Channel(name='channel other', password=hash_password('pass')))

        token = User.query.get(1).generate_api_token()

        with app.test_client() as c:
            rv = c.post('/api/channels/channel', follow_redirects=True)
            assert rv.status_code == 404
            assert 'Token not found' in str(rv.data)

            rv = c.post('/api/channels/channel',
                        data=dict(token='invalid'),
                        follow_redirects=True)
            assert rv.status_code == 403
            assert 'The token is either invalid or expired' in str(rv.data)

            rv = c.post('/api/channels/channel',
                        data=dict(token=token),
                        follow_redirects=True)
            assert rv.status_code == 200
            json_res = json.loads(rv.data.decode('utf8'))
            assert json_res['name'] == 'channel'

            rv = c.post('/api/channels/channel other',
                        data=dict(token=token),
                        follow_redirects=True)
            assert rv.status_code == 404
            assert 'you do not have permission' in str(rv.data)

            rv = c.post('/api/channels/this does not exist',
                        data=dict(token=token),
                        follow_redirects=True)
            assert rv.status_code == 404
            assert 'does not exist' in str(rv.data)
コード例 #7
0
ファイル: utils.py プロジェクト: dzionek/channels
def add_user(form: RegistrationForm) -> None:
    """Add user (whose data is given in the registration form) to the database.

    Args:
        form: The filled registration form.

    """
    hashed_password = hash_password(form.password.data)
    db.session.add(
        User(username=form.username.data,
             email=form.email.data,
             password=hashed_password))
    db.session.commit()
コード例 #8
0
    def test_channels(self) -> None:
        db.session.add(
            User(username='******',
                 password=hash_password('testPassword'),
                 email='*****@*****.**'))
        db.session.add(Channel(name='channel', password=hash_password('pass')))
        db.session.add(ChannelAllowList(user_id=1, channel_id=1))
        db.session.add(
            Message(content='hello world',
                    time=datetime.utcnow(),
                    author_id=1,
                    target_channel=1))

        token = User.query.get(1).generate_api_token()

        with app.test_client() as c:
            rv = c.post('/api/channels', follow_redirects=True)
            assert rv.status_code == 404
            assert 'Token not found' in str(rv.data)

            rv = c.post('/api/channels',
                        data=dict(token='invalid'),
                        follow_redirects=True)
            assert rv.status_code == 403
            assert 'The token is either invalid or expired' in str(rv.data)

            rv = c.post('/api/channels',
                        data=dict(token=token),
                        follow_redirects=True)
            assert rv.status_code == 200
            json_res = json.loads(rv.data.decode('utf8'))
            channel_res = json_res[0]
            assert channel_res['name'] == 'channel'
            assert len(channel_res['allowed_users']) == 1
            assert len(channel_res['messages']) == 1

            message = channel_res['messages'][0]
            assert message['author']['username'] == 'testUsername'
            assert message['content'] == 'hello world'
コード例 #9
0
    def test_settings(self) -> None:
        db.session.add(
            User(username='******',
                 password=hash_password('testPassword'),
                 email='*****@*****.**'))
        with app.test_client() as c:
            rv = c.get('/api/settings', follow_redirects=True)
            assert 'Please log in to access this page' in str(rv.data)

            rv = login(c, '*****@*****.**', 'testPassword')
            assert 'Log out' in str(rv.data)

            rv = c.get('/api/settings', follow_redirects=True)
            assert 'Your API token is:' in str(rv.data)
コード例 #10
0
    def test_index(self) -> None:
        db.session.add(
            User(username='******',
                 password=hash_password('testPassword'),
                 email='*****@*****.**'))
        with app.test_client() as c:
            rv = c.get('/', follow_redirects=True)
            assert 'Log out' not in str(rv.data)
            assert 'Log In' in str(rv.data)

            rv = login(c, '*****@*****.**', 'incorrectPassword')
            assert 'Login Unsuccessful. Incorrect email or password' in str(
                rv.data)
            assert 'Log out' not in str(rv.data)

            rv = login(c, '*****@*****.**', 'testPassword')
            assert 'Login Unsuccessful. Incorrect email or password' not in str(
                rv.data)
            assert 'Log out' in str(rv.data)

            rv = c.get('/', follow_redirects=True)
            assert 'Log out' in str(rv.data)
コード例 #11
0
 def user_2(self) -> User:
     """Another sample user for testing."""
     return User(username='******',
                 password=hash_password('testPassword2'),
                 email='*****@*****.**')
コード例 #12
0
 def user_1(self) -> User:
     """Sample user for testing."""
     return User(username='******',
                 password=hash_password('testPassword'),
                 email='*****@*****.**')
コード例 #13
0
    def test_settings(self) -> None:
        db.session.add(
            User(username='******',
                 password=hash_password('testPassword'),
                 email='*****@*****.**'))

        with app.test_client() as c:
            rv = login(c, '*****@*****.**', 'testPassword')
            assert 'Log out' in str(rv.data)
            rv = c.get('/settings', follow_redirects=True)
            assert '*****@*****.**' in find_substr_between(
                str(rv.data), 'Email address:', '</span>')
            assert 'default.png' in find_substr_between(
                str(rv.data), '<img src="', '"')
            assert '0' in find_substr_between(str(rv.data), 'All channels:',
                                              '</span>')
            assert '0' in find_substr_between(str(rv.data), 'All messages:',
                                              '</span>')

            db.session.add(Channel(name='channel', password='******'))
            db.session.add(ChannelAllowList(user_id=1, channel_id=1))
            rv = c.get('/settings', follow_redirects=True)
            assert '1' in find_substr_between(str(rv.data), 'All channels:',
                                              '</span>')
            assert '0' in find_substr_between(str(rv.data), 'All messages:',
                                              '</span>')

            for _ in range(13):
                db.session.add(
                    Message(content='_',
                            time=datetime.utcnow(),
                            target_channel=1,
                            author_id=1))

            rv = c.get('/settings', follow_redirects=True)
            assert '1' in find_substr_between(str(rv.data), 'All channels:',
                                              '</span>')
            assert '13' in find_substr_between(str(rv.data), 'All messages:',
                                               '</span>')

            rv = c.post('/settings',
                        data=dict(username='******',
                                  email='*****@*****.**'),
                        follow_redirects=True)
            assert 'Your profile has been successfully updated' in str(rv.data)
            assert '*****@*****.**' in find_substr_between(
                str(rv.data), 'Email address:', '</span>')

            with open('tests/assets/test.jpg', 'rb') as fp:
                file = FileStorage(fp)
                rv = c.post('/settings',
                            follow_redirects=True,
                            data=dict(username='******',
                                      email='*****@*****.**',
                                      profile_picture=file))

                assert 'Your profile has been successfully updated' in str(
                    rv.data)
                assert 'default.png' not in find_substr_between(
                    str(rv.data), '<img src="', '"')

                directory = os.path.dirname(
                    u.get_profile_picture_full_path('default.png'))
                profile_pictures = os.listdir(directory)
                assert len(profile_pictures) == 2

                for profile_picture in profile_pictures:
                    if profile_picture != 'default.png':
                        os.remove(
                            u.get_profile_picture_full_path(profile_picture))
コード例 #14
0
ファイル: test_main.py プロジェクト: dzionek/channels
    def test_setup_app(self) -> None:
        app.config['TESTING'] = True
        with app.app_context():
            db.drop_all()
            db.create_all()
            db.session.add(
                Channel(name='testJoin',
                        password=hash_password('passwordJoin')))
            db.session.commit()
            assert not User.query.first()

            driver = get_driver()
            time.sleep(5)
            # Registration
            driver.get('http://*****:*****@email.com')
            driver.find_element_by_name('password').send_keys('testPassword')
            confirm_password = driver.find_element_by_name('confirm_password')
            confirm_password.send_keys('testPassword')
            confirm_password.send_keys(Keys.ENTER)
            assert 'An account was successfully created for testUsername!' in driver.page_source

            # Log in
            driver.find_element_by_name('email').send_keys('*****@*****.**')
            password_input = driver.find_element_by_name('password')
            password_input.send_keys('testPassword')
            password_input.send_keys(Keys.ENTER)
            assert 'Log out' in driver.page_source
            assert 'No channels so far' in driver.page_source

            # Add channel
            #   - passwords don't match
            time.sleep(1)
            WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.ID, 'add-channel-button')))
            driver.find_element_by_id('add-channel-button').click()
            WebDriverWait(driver, 10).until(
                lambda x: x.find_element_by_name('add-name').is_displayed())
            driver.find_element_by_name('add-name').send_keys('testChannel')
            driver.find_element_by_name('add-password').send_keys(
                'testPassword')
            add_channel_conf_password = driver.find_element_by_name(
                'add-confirm_password')
            add_channel_conf_password.send_keys('testPassword2')
            add_channel_conf_password.send_keys(Keys.ENTER)
            assert 'Passwords must match' in driver.page_source
            assert len(Channel.query.all()) == 1

            #   - passwords match
            WebDriverWait(driver, 10).until(
                lambda x: x.find_element_by_name('add-name').is_displayed())
            driver.find_element_by_name('add-password').send_keys(
                'testPassword')
            add_channel_conf_password = driver.find_element_by_name(
                'add-confirm_password')
            add_channel_conf_password.send_keys('testPassword')
            add_channel_conf_password.send_keys(Keys.ENTER)
            assert 'You have successfully added the channel "testChannel"' in driver.page_source
            assert len(Channel.query.all()) == 2

            # Join channel
            #   - invalid password
            join_test_channel(driver, 'passwordJoin2')
            assert 'Joining unsuccessful' in driver.page_source
            assert len(ChannelAllowList.query.all()) == 1

            #   - valid password
            join_test_channel(driver, 'passwordJoin')
            assert 'Joining unsuccessful' not in driver.page_source
            assert 'You have successfully joined the channel "testJoin"' in driver.page_source
            assert len(ChannelAllowList.query.all()) == 2

            #   - trying to re-join the channel
            join_test_channel(driver, 'passwordJoin')
            assert 'Joining unsuccessful' not in driver.page_source
            assert 'You have successfully joined the channel "testJoin"' not in driver.page_source
            assert 'You are already member of this channel' in driver.page_source
            assert len(ChannelAllowList.query.all()) == 2

            driver.close()
            time.sleep(5)
            driver.quit()
            assert User.query.first()
コード例 #15
0
ファイル: test_main.py プロジェクト: dzionek/channels
    def test_get_messages_ajax(self) -> None:
        db.session.add(
            User(username='******',
                 password=hash_password('testPassword'),
                 email='*****@*****.**'))
        db.session.add(Channel(name='channel', password='******'))

        with app.test_client() as c:
            rv = c.post('/get-messages',
                        data={'channelName': 'channel'},
                        follow_redirects=True)
            assert 'messages' not in str(rv.data)

            rv = login(c, '*****@*****.**', 'testPassword')
            assert 'Log out' in str(rv.data)

            rv = c.post('/get-messages',
                        data={
                            'channelName': 'channel',
                            'counter': '1'
                        },
                        follow_redirects=True)
            assert 'Fatal error' in str(rv.data)

            rv = c.post('/get-messages',
                        data={
                            'channelName': 'channel',
                            'counter': 'NotANumber'
                        },
                        follow_redirects=True)
            assert 'Fatal error' in str(rv.data)

            rv = c.post('/get-messages',
                        data={
                            'channelName': 'channel',
                            'counter': '0'
                        },
                        follow_redirects=True)
            assert 'Fatal error' not in str(rv.data)
            json = eval(rv.data.decode('utf8'))
            assert json['messages'] == []

            for _ in range(5):
                db.session.add(
                    Message(content='_',
                            target_channel=1,
                            author_id=1,
                            time=datetime.utcnow()))

            rv = c.post('/get-messages',
                        data={
                            'channelName': 'channel',
                            'counter': '3'
                        },
                        follow_redirects=True)
            assert 'messages' in str(rv.data)
            json = eval(rv.data.decode('utf8'))
            assert len(json['messages']) == 3
            for content, user in [[message['content'], message['userName']]
                                  for message in json['messages']]:
                assert content == '_'
                assert user == 'testUsername'

            for _ in range(20):
                db.session.add(
                    Message(content='&',
                            target_channel=1,
                            author_id=1,
                            time=datetime.utcnow()))

            rv = c.post('/get-messages',
                        data={
                            'channelName': 'channel',
                            'counter': '25'
                        },
                        follow_redirects=True)
            json = eval(rv.data.decode('utf8'))

            assert len([message['content']
                        for message in json['messages']]) == 20

            assert set([message['content']
                        for message in json['messages']]) == set('&')