pytest:session_transaction未进入条件

pytest: session_transaction did not enter the condition

提问人:Kanyanat 提问时间:11/15/2023 更新时间:11/15/2023 访问量:21

问:

我尝试编写单元测试,然后我发现了这个问题,因为我想检查是否有.session

def get_session():
    if "test" in session:
        return 1
    else:
        return 2

这是我的方法,这是我test_login.py

def test_get_session(client):
    with client.session_transaction() as session:
        session["test"] = "testttt"
    result = get_session()
    assert "test" in session
    assert result == 1

我认为结果应该是 1,但是当我运行 pietist 时

________________________________ test_get_session _________________________________

client = <FlaskClient <Flask 'app'>>

    def test_get_session(client):
        with client.session_transaction() as session:
            session["test"] = "testttt"
        result = get_session()
        assert "test" in session
>       assert result == 1
E       assert 2 == 1

test_login.py:54: AssertionError

我想知道为什么通过但它进入了. 我想测试功能。 或者您有没有其他方法可以为我推荐测试会话?assert "test" in sessionelseif

Python 单元测试 Flask 会话

评论


答:

0赞 user22919420 11/15/2023 #1
def test_get_session(client):
    with client.session_transaction() as session:
        session["test"] = "testttt"
    result = get_session()
    assert "test" in session  # This assertion is correct; it checks if "test" is in the session
    assert result == 1  # This assertion fails, indicating that result is 2, not 1

第二个断言失败,因为当会话中出现“test”时,get_session 方法返回 2 而不是预期的 1。若要更正此问题,请编辑测试用例,使其适当地断言 get_session 函数的预期行为:

def test_get_session(client):
    with client.session_transaction() as session:
        session["test"] = "testttt"
    result = get_session()
    assert result == 1  # Check if the function returns 1 when "test" is in the session
    assert "test" in session  # Check if "test" is in the session