[Python] Mocking a class in Python, works in namespace package, but doesn't for regular package

Discussão em 'Python' iniciado por Stack, Janeiro 15, 2025.

  1. Stack

    Stack Membro Participativo

    Context


    I'm writing unit tests for my application.

    I have a module in configuration/connections.py with configuration (usually defined by environment variables):

    from typing import Literal

    from pydantic_settings import BaseSettings

    class StorageConfig(BaseSettings):
    storage_name: Literal["file", "s3"]


    this config is called in the module connections/storage/main.py :

    import fsspec

    from configuration.connections import StorageConfig

    storage_config = StorageConfig()

    fs: fsspec.AbstractFileSystem = fsspec.filesystem(storage_config.storage_name)


    and because the environment config does not exist when I run my unit tests, I'm trying to mock the object StorageConfig:

    import pytest
    from pydantic import BaseModel

    @pytest.fixture(autouse=True)
    def local_config(mocker):
    class LocalStorageConfig(BaseModel):
    storage_name: str = "file"

    mocker.patch("configuration.connections.StorageConfig", new=LocalStorageConfig)

    Problem


    Depending on my folder architecture, the mock works and sometimes does not.


    1. If I have connections.storage as a namespace package, and my test is in connections/storage/tests/test_storage.py and that I patch directly configuration.connections.StorageConfig (as opposed to what the documentation would like me to do), it works fine.


    2. If connections.storage is a regular package, and all the other things as in 1., it does not work anymore


    3. If I move my test in tests/integration/test_storage.py and keep all the other things as in 2., it works.
    Question

    1. Why does regular package and namespace package have an impact on the mock?
    2. Why is the position of my test file impacting the mock?
    3. Why can't it work when I patch connections.storage.main.StorageConfig as the documentation suggest it would?

    Continue reading...

Compartilhe esta Página