[Python] How to mock settings in Django Unit testing

Discussão em 'Python' iniciado por Stack, Março 29, 2025.

  1. Stack

    Stack Membro Participativo

    I am new to Django Unit testing and am trying to write unit test for a simple function which is like below:

    utils.py
    #some import statements
    from django.conf import settings

    if platform.system() == 'Linux':
    cx_Oracle.init_oracle_client(lib_dir=settings.GAP_DB_LIB_DIR)
    else:
    cx_Oracle.init_oracle_client(lib_dir=settings.LOCAL_DB_LIB_DIR)
    db_password = settings.DB_PASS
    db_user = settings.DB_USER
    db_connection_dsn = settings.DB_CONNECTION_DSN

    def project(repo):
    pieces = parse.urlsplit(repo)
    return pieces.path.rstrip('/').split('/')[-1]


    I am writing unit tests in test.py fie as below

    from django.test import TestCase
    from common import utils
    from utils import project
    from django.test import override_settings

    # Create your tests here.
    class UtilsTest(TestCase):
    def setUp(self):
    self.repo = "http://test/testrepo"

    @override_settings(LOCAL_DB_LIB_DIR="c:/testdir")
    def test_project(self):
    response = utils.project(self.repo)
    self.assertEqual(response,"testrepo")


    When I run tests am getting below error: AttributeError: 'Settings' object has no attribute 'LOCAL_DB_LIB_DIR' Please help me where I am doing wrong and correct my coding. Thanks in advance.

    Continue reading...

Compartilhe esta Página