PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 5, 2022

[FIXED] Why use monkeypatch.setenv instead of os.putenv

 November 05, 2022     environment-variables, monkeypatching, pytest, python     No comments   

Issue

pytest's monkeypatch module provides a setenv function which will Set environment variable name to value. Why does monkeypatch provide this? It sounds the same as os.putenv? It provides prepend argument as a convenience, but that seems like a weak reason to have a new function for setting an environment variable.


Solution

This is about tearing down the changes that the test makes in the environment. If you only use os.putenv, or modify the os.environ directly, then your modifications will stay in place even after the end of the test. That means the next test that runs will have the change applied, too! Since the tests are not necessarily ordered, it means you no longer have a repeatable and reliable test execution.

It's undesirable for a individual tests to change some global mutable state, therefore either use a context manager or the fixture provided when you need to configure environment variables during tests.



Answered By - wim
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing