-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Documentation: add setenv/delenv examples to monkeypatch docs #5250
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
Expand docs on use of ``setenv`` and ``delenv`` with ``monkeypatch``. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -16,7 +16,7 @@ and a discussion of its motivation. | |
|
||
|
||
Simple example: monkeypatching functions | ||
--------------------------------------------------- | ||
---------------------------------------- | ||
|
||
If you want to pretend that ``os.expanduser`` returns a certain | ||
directory, you can use the :py:meth:`monkeypatch.setattr` method to | ||
|
@@ -38,8 +38,8 @@ Here our test function monkeypatches ``os.path.expanduser`` and | |
then calls into a function that calls it. After the test function | ||
finishes the ``os.path.expanduser`` modification will be undone. | ||
|
||
example: preventing "requests" from remote operations | ||
------------------------------------------------------ | ||
Global patch example: preventing "requests" from remote operations | ||
------------------------------------------------------------------ | ||
|
||
If you want to prevent the "requests" library from performing http | ||
requests in all your tests, you can do:: | ||
|
@@ -81,6 +81,80 @@ so that any attempts within tests to create http requests will fail. | |
See issue `#3290 <https://github.com/pytest-dev/pytest/issues/3290>`_ for details. | ||
|
||
|
||
Monkeypatching environment variables | ||
------------------------------------ | ||
|
||
If you are working with environment variables you often need to safely change the values | ||
or delete them from the system for testing purposes. ``Monkeypatch`` provides a mechanism | ||
to do this using the ``setenv`` and ``delenv`` method. Our example code to test: | ||
|
||
.. code-block:: python | ||
|
||
# contents of our original code file e.g. code.py | ||
import os | ||
|
||
|
||
def get_os_user_lower(): | ||
"""Simple retrieval function. | ||
Returns lowercase USER or raises EnvironmentError.""" | ||
username = os.getenv("USER") | ||
|
||
if username is None: | ||
raise EnvironmentError("USER environment is not set.") | ||
|
||
return username.lower() | ||
|
||
There are two potential paths. First, the ``USER`` environment variable is set to a | ||
value. Second, the ``USER`` environment variable does not exist. Using ``monkeypatch`` | ||
both paths can be safely tested without impacting the running environment: | ||
|
||
.. code-block:: python | ||
|
||
# contents of our test file e.g. test_code.py | ||
import pytest | ||
|
||
|
||
def test_upper_to_lower(monkeypatch): | ||
"""Set the USER env var to assert the behavior.""" | ||
monkeypatch.setenv("USER", "TestingUser") | ||
assert get_os_user_lower() == "testinguser" | ||
|
||
|
||
def test_raise_exception(monkeypatch): | ||
"""Remove the USER env var and assert EnvironmentError is raised.""" | ||
monkeypatch.delenv("USER", raising=False) | ||
|
||
with pytest.raises(EnvironmentError): | ||
_ = get_os_user_lower() | ||
|
||
This behavior can be be moved into ``fixture`` structures and shared across tests: | ||
|
||
.. code-block:: python | ||
|
||
import pytest | ||
|
||
|
||
@pytest.fixture | ||
def mock_env_user(monkeypatch): | ||
monkeypatch.setenv("USER", "TestingUser") | ||
|
||
|
||
@pytest.fixture | ||
def mock_env_missing(monkeypatch): | ||
monkeypatch.delenv("USER", raising=False) | ||
|
||
|
||
# Notice the tests reference the fixtures for mocks | ||
def test_upper_to_lower(mock_env_user): | ||
assert get_os_user_lower() == "testinguser" | ||
|
||
|
||
def test_raise_exception(mock_env_missing): | ||
with pytest.raises(EnvironmentError): | ||
_ = get_os_user_lower() | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Also here. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ditto |
||
|
||
|
||
|
||
.. currentmodule:: _pytest.monkeypatch | ||
|
||
API Reference | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.