Question:
Create a test case for add user functionality in a movie app - Python

Problem:

I'm trying to write a test case for the movie site that I'm creating. I want to test the add_user method. Each time I call add_user() from my test method, it is created a user in my SQLite db and then returns as a fail that the user already exists.


def add_user(self, name):

    param = {'name': name}

    query = text('Insert into users (name) values (:name)')

    check_usr_query = text('Select name from users '

                           'Where name = :name')


    check_usr = self._execute_query(check_usr_query, param).fetchone()


    if check_usr is not None:

       return 'User Already Exists in Database'

    else:

        with self.engine.connect() as conn:

            conn.execute(query, param)

            conn.commit()

        return 'Successfully added user'


import pytest

from DataManager.sql_data_manager import SQLiteDataManager


dataManager = SQLiteDataManager('DataManager/movie.db')


def test_add_user():

    name = 'Esth'

    test_data = dataManager.add_user(name)

    check_usr = dataManager.get_user_by_name(name)

    if test_data == 'Successfully added user':

        assert test_data == 'Successfully added user'

        print(name + ' added to db')

    elif test_data == 'User Already Exists in Database':

        assert check_usr is not None

        print(name + ' Already exists in the db')


Solution:

You have several options here:

  1. Use >pytest teardown fixture to cleanup user on test complete

  2. Remove user Esth on test launch if it exists

  3. Create user with the >random name

  4. Create new database on every test run


Suggested blogs:

>How to load static files using Nginx, Docker, and Django?

>How to tell Django "if anything in urlpatterns does not match the GET string?

>How can I browser to render links in streamed content in Django?

>Access the "model" attribute for a ListView in Django for template

>How to use a function to print S3 data to HTML using Django?


Ritu Singh

Ritu Singh

Submit
0 Answers