Search code examples
pythonflasksessionsession-variablesflask-session

Flask session-- Test case failure


Working on storing login objects in session. Solution working fine on local machine. however test cases failing on hacker rank environment. Steps followed :

  • login page created to accept username and password
  • routes created to save information from form as session object

user.html

<!DOCTYPE html>
<html lang="en">
<body>
{% block content %}
<!-- write a condition to check if the user in session or not with appropriate response and redirect routes-->
{% if login %}
    Logged in as {{ session['username'] }} 
    <a href="/logout">logout</a>
    {%else%}
    You are not logged in
    <a href="/login">login</a>.
    {%endif %}

{% endblock %}
</body>
</html>

test.py

 def test_login_and_user_page(self):
        soup1 = self.get_soup1()
        msg = soup1.find('p', {'id': 'a'})
        link = soup1.find('a')
        assert msg.text == 'Logged in as admin'
        assert link['href'] == '/logout'

        soup3 = self.get_soup3()
        assert soup3.text == "You've been logged out successfully!"

        soup4 = self.get_soup4()
        msg = soup4.find('p', {'id': 'a'})
        assert msg.text == 'Logged in as user'

    def test_user_page(self):
        soup2 = self.get_soup2()
        msg = soup2.find('p', {'id': 'b'})
        link = soup2.find('a')
        assert msg.text == 'You are not logged in'
        assert link['href'] == '/login'

Test failure:

============================================== FAILURES ==============================================
_______________________________ Test_Webpage.test_login_and_user_page ________________________________

self = <tests.Test_Webpage object at 0x7f8baae8c198>

    def test_login_and_user_page(self):
        soup1 = self.get_soup1()
        msg = soup1.find('p', {'id': 'a'})
        link = soup1.find('a')
>       assert msg.text == 'Logged in as admin'
E       AttributeError: 'NoneType' object has no attribute 'text'

Solution

  • As i wrote in my comment, the testcases try to filter for an <p> Tag to get the Output on the Webpage:

    msg = soup2.find('p', {'id': 'a'}) # first testcase
    msg = soup2.find('p', {'id': 'b'}) # second testcase
    

    But on your html Template you just wrote the text down:

    Logged in as {{ session['username'] }} 
    You are not logged in
    

    if you put these messages into the <p> tags and give them the correct id it should work.

    <p id="a">Logged in as {{ session['username'] }}</p>
    <p id="b">You are not logged in</p>