Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 970481
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T02:48:42+00:00 2026-05-16T02:48:42+00:00

For testing things that query the environment (e.g., os.getenv , sys.version , etc.), it’s

  • 0

For testing things that query the environment (e.g., os.getenv, sys.version, etc.), it’s often more convenient to make the queries lie than to actually fake up the environment. Here’s a context manager that does this for one os.getenv call at a time:

from __future__ import with_statement
from contextlib import contextmanager
import os

@contextmanager
def fake_env(**fakes):
    '''fakes is a dict mapping variables to their values. In the
    fake_env context, os.getenv calls try to return out of the fakes
    dict whenever possible before querying the actual environment.
    '''

    global os
    original = os.getenv

    def dummy(var):
        try: return fakes[var]
        except KeyError: return original(var)

    os.getenv = dummy
    yield
    os.getenv = original

if __name__ == '__main__':

    print os.getenv('HOME') 
    with fake_env(HOME='here'):
        print os.getenv('HOME') 
    print os.getenv('HOME') 

But this only works for os.getenv and the syntax gets a bit clunky if I allow for functions with multiple arguments. I guess between ast and code/exec/eval I could extend it to take the function to override as a parameter, but not cleanly. Also, I would then be on my way to Greenspun’s Tenth. Is there a better way?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T02:48:43+00:00Added an answer on May 16, 2026 at 2:48 am

    You could easily just pass os.getenv itself as the first argument, then analyze it in the context manager much more simply than ast, code, etc etc:

    >>> os.getenv.__name__
    'getenv'
    >>> os.getenv.__module__
    'os'
    

    After that, for reasonably general purpose use, you could have the result object to be returned, or a mapping from arguments (probably tuples thereof) to results. The faker context manager could also optionally accept a callable to be used for faking.

    For example, with maximum simplicity:

    import sys
    
    def faker(original, fakefun):
    
        original = os.getenv
        themod = sys.modules[original.__module__]
        thename = original.__name__
    
        def dummy(*a, **k):
            try: return fakefun(*a, **k)
            except BaseException: return original(*a, **k)
    
        setattr(themod, thename, dummy)
        yield
        setattr(themod, thename, original)
    

    Your specific example could become:

    with faker(os.getenv, dict(HOME='here').__getitem__):
       ...
    

    Of course, a little more complexity may be warranted if e.g. you want to propagate certain exceptions rather than punting to the original function, or shortcut some common cases where providing a fakefun callable is clunky, and so on. But there’s no reason such a general faker need be much more complex than your specific one.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 506k
  • Answers 506k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Start with the generic example and then i will mock… May 16, 2026 at 3:49 pm
  • Editorial Team
    Editorial Team added an answer You need to specify the UNICODE flag, otherwise \w is… May 16, 2026 at 3:49 pm
  • Editorial Team
    Editorial Team added an answer You'll just have to add a new notify script entry… May 16, 2026 at 3:48 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

I have a query that pulls up questions from one table and answers from
I have a big query and I am tring to improve it part by
Our application exposes queries by way of web services, and what we've found is
I've built a script in PHP for a small shop that does a few
I'm new to Unit Testing, and I'm only getting into the routine of building
I am new to unit testing. Suppose I am building a web application. How
I have two problems with the below code that I need help fixing: 1)
I have an existing application that has some parts of formatted text-blocks (standard formats
Not sure where to start on this one -- not sure if the problem
Our (asp.net) system is part of a larger system. It is launched via this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.