最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - I can't make a mock on my environment variables - Stack Overflow

programmeradmin3浏览0评论

I have problems when testing the way in which I choose the db to connect to in a condition of my scope where I will perform the deplyoment:

from app.resources import secrets
from app.resources.scope import get_scope 
try:
    scope = get_scope()
    if "test" in scope or not scope:
        db_db = 'test_db'
    else:
        db_db = 'prod_db'
except EnvVarNotDefined:
    db_db = 'test_db'

the get_scope() package, configure it as follows in two files:

from app.resources.env import get_env

SCOPE = get_env("SCOPE", "")

def get_scope() -> str:
    return SCOPE

and get_env():

import os

def get_env(key: str, default: str = None) -> str:
    return os.getenv(key, default)

The test I defined is as follows

@patch("app.database.service.Database_Service.__new__")
class DatabaseServiceTest(TestCase):
    def setUp(self):
        self.app = app.create_app().test_client()
        self.app.testing = True
        self.db = Database_Service()

    @patch("app.resources.scope.get_scope")
    @patch("app.database.service.secrets.get_secret")
    def test_init_prod_scope(self, mock_get_secret, mock_get_scope, mock_auth):
        mock_get_scope.return_value = "prod"
        _ = Database_Service()
        mock_get_secret.assert_not_called()

Although I define mock_get_scope.return_value = “prod”, in the debugging I get an empty return of the scope mock: “”.

I tried to use mock.patch.dict(os.environ, clear=True) in my conftest.py file, but it didn't work and I saw it in this article:How can I mock my environment variables for my pytest?

I did the tests in this post, I couldn't get it to work either: Python mock Patch os.environ and return value

Finally, to the test I added the method mock_get_scope.assert_called_once() and the error obtained is: AssertionError: Expected 'get_scope' to have been called once. Called 0 times. Indeed, the error seems to be because I have not been able to mock the value of the scope method.

发布评论

评论列表(0)

  1. 暂无评论