0

所以我有网络应用程序,如果用户登录,他就无法注册。取而代之的是,他被重定向,并显示一条消息说他无法注册。

问题是由于某种原因我无法对其进行测试。

这是视图

@users_template.route('/signup', methods=['GET', 'POST'])
def signup():
    form = RegisterationForm()
    if current_user.is_authenticated and current_user.is_active:  # prevent the user from seeing the register page if he's already logged in
        flash('You cannot sign up while you\'re logged in')
        return redirect(url_for('main.home'))

    if request.method == 'POST' and form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        user = User(username=username, password=password)
        if db.session.query(User).filter(User.username == username).first() is None:
            current_app.logger.info('<{}> did not register before. Registering him/her now'.format(username))
            db.session.add(user)
            db.session.commit()
            flash('Thank you for registering. Please login now')
            return redirect(url_for('users.login'))
        else:  # the user name has been registered before
            flash('You already registered')
    return render_template('signup.html', form=form)

现在在我的测试模块中我有这个方法

def test_signup_page_requires_logout(self):
    data_to_signup = {'username': 'mustafa1', 'password': 'mustafa1',
            'confirm_password': 'mustafa1'}
    data_to_login = {'username': 'mustafa1', 'password': 'mustafa1'}
    # with statement preserves the request context for the current_user
    with self.client:
        self.client.post('/signup', data=data_to_signup)
        self.client.post('/login', data=data_to_login)
        response = self.client.get('/signup', follow_redirects=True)
        assert b'You cannot sign up while you\'re logged in' in response.data

更令人困惑的是,这种结构适用于其他方法

def test_headquarter_after_login(self):
    data_to_signup = {'username': 'mustafa1', 'password': 'mustafa1',
            'confirm_password': 'mustafa1'}
    data_to_login = {'username': 'mustafa1', 'password': 'mustafa1'}
    with self.client:
        self.client.post('/signup', data=data_to_signup)
        self.client.post('/login', data=data_to_login)
        response = self.client.get('/headquarter')
        assert b'Headquarter page' in response.data

编辑:这是登录视图

from .. import bcrypt
@users_template.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm(request.form)
    if form.validate_on_submit() and request.method == 'POST':
        username = form.username.data
        password = form.password.data

        user = User.query.filter(User.username == username).first()

        if user is not None and bcrypt.check_password_hash(user.password, password):  # authenticate
            login_user(user)  # then log the user in
            flash('You are logged in')
            return redirect(url_for('main.home'))

        else:
            flash('Incorrect username or password')  # if username is wrong, it will be caught by the error handling above
    return render_template('login.html', form=form)  # for a GET request

这是错误(我正在使用 py.test fyi)

            assert current_user.is_active() == True
            assert current_user.is_authenticated() == True
>           assert b'You cannot sign up while you\'re logged in' in response.data
E           AssertionError: assert b"You cannot sign up while you're logged in" in b'<!DOCTYPE html>\n<html lang="en">\n  <head>\n    <meta charset="utf-8">\n    <meta http-equiv="X-UA-Compatible" cont...jquery/1.12.4/jquery.min.js"></script>\n    <script src="/static/js/bootstrap.min.js"> </script>\n  </body>\n</html>\n'
E            +  where b'<!DOCTYPE html>\n<html lang="en">\n  <head>\n    <meta charset="utf-8">\n    <meta http-equiv="X-UA-Compatible" cont...jquery/1.12.4/jquery.min.js"></script>\n    <script src="/static/js/bootstrap.min.js"> </script>\n  </body>\n</html>\n' = <TestResponse 3874 bytes [200 OK]>.

这是为了在我的所有模板中显示闪现的消息(它在我继承的“base.html”中)

    {% if get_flashed_messages() %}
        {% for message in get_flashed_messages() %}
            <div class='container'>
                    <span class='alert alert-info'>
                        <small>{{ message }}</small>
                    </span>
            </div>
        {% endfor %}
    {% endif %}

我使用闪烁的消息进行了更多测试,并且效果很好。像这个用于测试用户注册

assert b'Thank you for registering. Please login now' in response.data
4

1 回答 1

1

建议编号:

  1. 因为这条线:

    if current_user.is_authenticated and current_user.is_active:
    

    current_user 将他的is_active标志设置为False. 如果我不对,请粘贴测试错误。

  2. 另一个线索可能是主页模板中缺少 Flash 消息。例如,将此代码放在下面flashMessages.html

    {% macro render_flashMessages() %}
        {% with messages = get_flashed_messages() %}
            {% if messages %}
            <ul class="list-unstyled">
                {% for message in messages %}
                <li><div class="alert alert-info">{{ message|safe }}</div></li>
                {% endfor %}
            </ul>
            {% endif %}
        {% endwith %}
    {% endmacro %}
    

    那么你可以以这种方式使用它home.html

    {% from "flashMessages.html" import render_flashMessages %}
    
    {{ render_flashMessages() }}
    
  3. 接下来要检查的是将 assert 与 response.data 以外的东西一起使用,如果您使用的是Flask-WebTest,您可以尝试:

    assert b'You cannot sign up while you\'re logged in' in response.flashes[0][1]
    

    在哪里flashes

    包含在请求期间闪烁的消息的元组(类别、消息)列表。

  4. 但是如果你没有使用 FlaskWebTest,你可以检查会话:

    from flask import session
    
    session['_flashes'][0][1]
    
于 2016-09-03T06:26:50.223 回答