diff --git a/CHANGELOG b/CHANGELOG
index 6da74217..eeb48cff 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -7,6 +7,8 @@ Not released yet
 - #517: Forward NUMBER_OF_PROCESSORS by default on Windows to fix
         `multiprocessor.cpu_count()`.
 - #518: Forward `USERPROFILE` by default on Windows.
+- #515: Don't require environment variables in test environments
+	where they are not used.
 
 2.7.0
 -----
diff --git a/tox/config.py b/tox/config.py
index d797951c..e5e616b3 100755
--- a/tox/config.py
+++ b/tox/config.py
@@ -792,7 +792,8 @@ class parseini:
             factors = set(name.split('-'))
             if section in self._cfg or factors <= known_factors:
                 config.envconfigs[name] = \
-                    self.make_envconfig(name, section, reader._subs, config)
+                    self.make_envconfig(name, section, reader._subs, config,
+                                        replace=name in config.envlist)
 
         all_develop = all(name in config.envconfigs
                           and config.envconfigs[name].usedevelop
@@ -808,7 +809,7 @@ class parseini:
                 factors.update(*mapcat(_split_factor_expr, exprs))
         return factors
 
-    def make_envconfig(self, name, section, subs, config):
+    def make_envconfig(self, name, section, subs, config, replace=True):
         factors = set(name.split('-'))
         reader = SectionReader(section, self._cfg, fallbacksections=["testenv"],
                                factors=factors)
@@ -823,7 +824,7 @@ class parseini:
             atype = env_attr.type
             if atype in ("bool", "path", "string", "dict", "dict_setenv", "argv", "argvlist"):
                 meth = getattr(reader, "get" + atype)
-                res = meth(env_attr.name, env_attr.default)
+                res = meth(env_attr.name, env_attr.default, replace=replace)
             elif atype == "space-separated-list":
                 res = reader.getlist(env_attr.name, sep=" ")
             elif atype == "line-list":
@@ -942,9 +943,9 @@ class SectionReader:
         if _posargs:
             self.posargs = _posargs
 
-    def getpath(self, name, defaultpath):
+    def getpath(self, name, defaultpath, replace=True):
         toxinidir = self._subs['toxinidir']
-        path = self.getstring(name, defaultpath)
+        path = self.getstring(name, defaultpath, replace=replace)
         if path is not None:
             return toxinidir.join(path, abs=True)
 
@@ -954,12 +955,12 @@ class SectionReader:
             return []
         return [x.strip() for x in s.split(sep) if x.strip()]
 
-    def getdict(self, name, default=None, sep="\n"):
+    def getdict(self, name, default=None, sep="\n", replace=True):
         value = self.getstring(name, None)
         return self._getdict(value, default=default, sep=sep)
 
-    def getdict_setenv(self, name, default=None, sep="\n"):
-        value = self.getstring(name, None, replace=True, crossonly=True)
+    def getdict_setenv(self, name, default=None, sep="\n", replace=True):
+        value = self.getstring(name, None, replace=replace, crossonly=True)
         definitions = self._getdict(value, default=default, sep=sep)
         self._setenv = SetenvDict(definitions, reader=self)
         return self._setenv
@@ -976,8 +977,8 @@ class SectionReader:
 
         return d
 
-    def getbool(self, name, default=None):
-        s = self.getstring(name, default)
+    def getbool(self, name, default=None, replace=True):
+        s = self.getstring(name, default, replace=replace)
         if not s:
             s = default
         if s is None:
@@ -994,12 +995,12 @@ class SectionReader:
                     "boolean value %r needs to be 'True' or 'False'")
         return s
 
-    def getargvlist(self, name, default=""):
+    def getargvlist(self, name, default="", replace=True):
         s = self.getstring(name, default, replace=False)
-        return _ArgvlistReader.getargvlist(self, s)
+        return _ArgvlistReader.getargvlist(self, s, replace=replace)
 
-    def getargv(self, name, default=""):
-        return self.getargvlist(name, default)[0]
+    def getargv(self, name, default="", replace=True):
+        return self.getargvlist(name, default, replace=replace)[0]
 
     def getstring(self, name, default=None, replace=True, crossonly=False):
         x = None
@@ -1153,7 +1154,7 @@ class Replacer:
 
 class _ArgvlistReader:
     @classmethod
-    def getargvlist(cls, reader, value):
+    def getargvlist(cls, reader, value, replace=True):
         """Parse ``commands`` argvlist multiline string.
 
         :param str name: Key name in a section.
@@ -1178,7 +1179,7 @@ class _ArgvlistReader:
                 replaced = reader._replace(current_command, crossonly=True)
                 commands.extend(cls.getargvlist(reader, replaced))
             else:
-                commands.append(cls.processcommand(reader, current_command))
+                commands.append(cls.processcommand(reader, current_command, replace))
             current_command = ""
         else:
             if current_command:
@@ -1188,7 +1189,7 @@ class _ArgvlistReader:
         return commands
 
     @classmethod
-    def processcommand(cls, reader, command):
+    def processcommand(cls, reader, command, replace=True):
         posargs = getattr(reader, "posargs", "")
         posargs_string = list2cmdline([x for x in posargs if x])
 
@@ -1196,23 +1197,26 @@ class _ArgvlistReader:
         # appropriate to construct the new command string. This
         # string is then broken up into exec argv components using
         # shlex.
-        newcommand = ""
-        for word in CommandParser(command).words():
-            if word == "{posargs}" or word == "[]":
-                newcommand += posargs_string
-                continue
-            elif word.startswith("{posargs:") and word.endswith("}"):
-                if posargs:
+        if replace:
+            newcommand = ""
+            for word in CommandParser(command).words():
+                if word == "{posargs}" or word == "[]":
                     newcommand += posargs_string
                     continue
-                else:
-                    word = word[9:-1]
-            new_arg = ""
-            new_word = reader._replace(word)
-            new_word = reader._replace(new_word)
-            new_word = new_word.replace('\\{', '{').replace('\\}', '}')
-            new_arg += new_word
-            newcommand += new_arg
+                elif word.startswith("{posargs:") and word.endswith("}"):
+                    if posargs:
+                        newcommand += posargs_string
+                        continue
+                    else:
+                        word = word[9:-1]
+                new_arg = ""
+                new_word = reader._replace(word)
+                new_word = reader._replace(new_word)
+                new_word = new_word.replace('\\{', '{').replace('\\}', '}')
+                new_arg += new_word
+                newcommand += new_arg
+        else:
+            newcommand = command
 
         # Construct shlex object that will not escape any values,
         # use all values as is in argv.

Environment variables required across unrelated environments
Hi there,

I have an issue where if one environment uses an `{env:X}` subsitution (without default), then that environment variable is required in all environments regardless of whether they are necessary or not.

Given this example `tox.ini` file:

```ini
[tox]
skipsdist = true

[testenv:standard-greeting]
commands =
  python -c 'print("Hello, world!")'

[testenv:custom-greeting]
passenv =
  NAME
commands =
  python -c 'print("Hello, {env:NAME}!"'
```

Then `custom-greeting` environment cannot be used unless `NAME` is present in the calling environment, even if that environment doesn't use the `{env:NAME}`.

```shell
$ tox -e standard-greeting
tox.ConfigError: ConfigError: substitution env:'NAME': unknown environment variable 'NAME'  or recursive definition.
```

I got this with tox 2.7.0 with both Python 3.5 and 2.7 on Windows.
diff --git a/tests/test_config.py b/tests/test_config.py
index 9254e992..743b08ed 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -1088,6 +1088,27 @@ class TestConfigTestEnv:
         assert 'FOO' in env
         assert 'BAR' in env
 
+    def test_substitution_notfound_issue515(tmpdir, newconfig):
+        config = newconfig("""
+            [tox]
+            envlist = standard-greeting
+
+            [testenv:standard-greeting]
+            commands =
+                python -c 'print("Hello, world!")'
+
+            [testenv:custom-greeting]
+            passenv =
+                NAME
+            commands =
+                python -c 'print("Hello, {env:NAME}!")'
+        """)
+        conf = config.envconfigs['standard-greeting']
+        assert conf.commands == [
+            ['python', '-c', 'print("Hello, world!")'],
+        ]
+
+    @pytest.mark.xfail(raises=AssertionError, reason="issue #301")
     def test_substitution_nested_env_defaults_issue301(tmpdir, newconfig, monkeypatch):
         monkeypatch.setenv("IGNORE_STATIC_DEFAULT", "env")
         monkeypatch.setenv("IGNORE_DYNAMIC_DEFAULT", "env")

pip install -e .[dev]
parse_log_pytest
pytest
pytest>=2.3.5 pytest-timeout pytest
apt-get update apt-get install -y gcc
3.6
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
certifi==2021.5.30
distlib==0.3.9
filelock==3.4.1
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
platformdirs==2.4.0
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
pytest-timeout==2.1.0
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
-e git+https://github.com/tox-dev/tox.git@6889c81a4c31fedeb22af056e9f2b7e8f86f00cf#egg=tox
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
virtualenv==20.17.1
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work

name: tox
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - attrs=21.4.0=pyhd3eb1b0_0
  - ca-certificates=2025.2.25=h06a4308_0
  - certifi=2021.5.30=py36h06a4308_0
  - importlib_metadata=4.8.1=hd3eb1b0_0
  - iniconfig=1.1.1=pyhd3eb1b0_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - libffi=3.3=he6710b0_2
  - libgcc-ng=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libstdcxx-ng=11.2.0=h1234567_1
  - more-itertools=8.12.0=pyhd3eb1b0_0
  - ncurses=6.4=h6a678d5_0
  - openssl=1.1.1w=h7f8727e_0
  - packaging=21.3=pyhd3eb1b0_0
  - pip=21.2.2=py36h06a4308_0
  - pluggy=0.13.1=py36h06a4308_0
  - py=1.11.0=pyhd3eb1b0_0
  - pyparsing=3.0.4=pyhd3eb1b0_0
  - pytest=6.2.4=py36h06a4308_2
  - python=3.6.13=h12debd9_1
  - readline=8.2=h5eee18b_0
  - setuptools=58.0.4=py36h06a4308_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - toml=0.10.2=pyhd3eb1b0_0
  - typing_extensions=4.1.1=pyh06a4308_0
  - wheel=0.37.1=pyhd3eb1b0_0
  - xz=5.6.4=h5eee18b_1
  - zipp=3.6.0=pyhd3eb1b0_0
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - distlib==0.3.9
      - filelock==3.4.1
      - importlib-metadata==4.8.3
      - importlib-resources==5.4.0
      - platformdirs==2.4.0
      - pytest-timeout==2.1.0
      - virtualenv==20.17.1
prefix: /opt/conda/envs/tox

tests/test_config.py::TestConfigTestEnv::test_substitution_notfound_issue515
tests/test_config.py::TestVenvConfig::test_force_dep_with_url tests/test_config.py::TestIniParser::test_getbool
tests/test_config.py::TestVenvConfig::test_config_parsing_minimal tests/test_config.py::TestVenvConfig::test_config_parsing_multienv tests/test_config.py::TestVenvConfig::test_envdir_set_manually tests/test_config.py::TestVenvConfig::test_envdir_set_manually_with_substitutions tests/test_config.py::TestVenvConfig::test_force_dep_version tests/test_config.py::TestVenvConfig::test_is_same_dep tests/test_config.py::TestConfigPlatform::test_config_parse_platform tests/test_config.py::TestConfigPlatform::test_config_parse_platform_rex tests/test_config.py::TestConfigPlatform::test_config_parse_platform_with_factors[win] tests/test_config.py::TestConfigPlatform::test_config_parse_platform_with_factors[lin] tests/test_config.py::TestConfigPackage::test_defaults tests/test_config.py::TestConfigPackage::test_defaults_distshare tests/test_config.py::TestConfigPackage::test_defaults_changed_dir tests/test_config.py::TestConfigPackage::test_project_paths tests/test_config.py::TestParseconfig::test_search_parents tests/test_config.py::TestParseconfig::test_explicit_config_path tests/test_config.py::test_get_homedir tests/test_config.py::TestGetcontextname::test_blank tests/test_config.py::TestGetcontextname::test_jenkins tests/test_config.py::TestGetcontextname::test_hudson_legacy tests/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_from_other_section tests/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_from_other_section_multiline tests/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_from_other_section_posargs tests/test_config.py::TestIniParserAgainstCommandsKey::test_command_section_and_posargs_substitution tests/test_config.py::TestIniParserAgainstCommandsKey::test_command_env_substitution tests/test_config.py::TestIniParserAgainstCommandsKey::test_command_env_substitution_global tests/test_config.py::TestIniParser::test_getstring_single tests/test_config.py::TestIniParser::test_missing_substitution tests/test_config.py::TestIniParser::test_getstring_fallback_sections tests/test_config.py::TestIniParser::test_getstring_substitution tests/test_config.py::TestIniParser::test_getlist tests/test_config.py::TestIniParser::test_getdict tests/test_config.py::TestIniParser::test_getstring_environment_substitution tests/test_config.py::TestIniParser::test_getstring_environment_substitution_with_default tests/test_config.py::TestIniParser::test_value_matches_section_substituion tests/test_config.py::TestIniParser::test_value_doesn_match_section_substitution tests/test_config.py::TestIniParser::test_getstring_other_section_substitution tests/test_config.py::TestIniParser::test_argvlist tests/test_config.py::TestIniParser::test_argvlist_windows_escaping tests/test_config.py::TestIniParser::test_argvlist_multiline tests/test_config.py::TestIniParser::test_argvlist_quoting_in_command tests/test_config.py::TestIniParser::test_argvlist_comment_after_command tests/test_config.py::TestIniParser::test_argvlist_command_contains_hash tests/test_config.py::TestIniParser::test_argvlist_positional_substitution tests/test_config.py::TestIniParser::test_argvlist_quoted_posargs tests/test_config.py::TestIniParser::test_argvlist_posargs_with_quotes tests/test_config.py::TestIniParser::test_positional_arguments_are_only_replaced_when_standing_alone tests/test_config.py::TestIniParser::test_posargs_are_added_escaped_issue310 tests/test_config.py::TestIniParser::test_substitution_with_multiple_words tests/test_config.py::TestIniParser::test_getargv tests/test_config.py::TestIniParser::test_getpath tests/test_config.py::TestIniParserPrefix::test_basic_section_access tests/test_config.py::TestIniParserPrefix::test_fallback_sections tests/test_config.py::TestIniParserPrefix::test_value_matches_prefixed_section_substituion tests/test_config.py::TestIniParserPrefix::test_value_doesn_match_prefixed_section_substitution tests/test_config.py::TestIniParserPrefix::test_other_section_substitution tests/test_config.py::TestConfigTestEnv::test_commentchars_issue33 tests/test_config.py::TestConfigTestEnv::test_defaults tests/test_config.py::TestConfigTestEnv::test_sitepackages_switch tests/test_config.py::TestConfigTestEnv::test_installpkg_tops_develop tests/test_config.py::TestConfigTestEnv::test_specific_command_overrides tests/test_config.py::TestConfigTestEnv::test_whitelist_externals tests/test_config.py::TestConfigTestEnv::test_changedir tests/test_config.py::TestConfigTestEnv::test_ignore_errors tests/test_config.py::TestConfigTestEnv::test_envbindir tests/test_config.py::TestConfigTestEnv::test_envbindir_jython[jython] tests/test_config.py::TestConfigTestEnv::test_envbindir_jython[pypy] tests/test_config.py::TestConfigTestEnv::test_envbindir_jython[pypy3] tests/test_config.py::TestConfigTestEnv::test_passenv_as_multiline_list[win32] tests/test_config.py::TestConfigTestEnv::test_passenv_as_multiline_list[linux2] tests/test_config.py::TestConfigTestEnv::test_passenv_as_space_separated_list[win32] tests/test_config.py::TestConfigTestEnv::test_passenv_as_space_separated_list[linux2] tests/test_config.py::TestConfigTestEnv::test_passenv_with_factor tests/test_config.py::TestConfigTestEnv::test_passenv_from_global_env tests/test_config.py::TestConfigTestEnv::test_passenv_glob_from_global_env tests/test_config.py::TestConfigTestEnv::test_changedir_override tests/test_config.py::TestConfigTestEnv::test_install_command_setting tests/test_config.py::TestConfigTestEnv::test_install_command_must_contain_packages tests/test_config.py::TestConfigTestEnv::test_install_command_substitutions tests/test_config.py::TestConfigTestEnv::test_pip_pre tests/test_config.py::TestConfigTestEnv::test_pip_pre_cmdline_override tests/test_config.py::TestConfigTestEnv::test_simple tests/test_config.py::TestConfigTestEnv::test_substitution_error tests/test_config.py::TestConfigTestEnv::test_substitution_defaults tests/test_config.py::TestConfigTestEnv::test_substitution_notfound_issue246 tests/test_config.py::TestConfigTestEnv::test_substitution_positional tests/test_config.py::TestConfigTestEnv::test_substitution_noargs_issue240 tests/test_config.py::TestConfigTestEnv::test_substitution_double tests/test_config.py::TestConfigTestEnv::test_posargs_backslashed_or_quoted tests/test_config.py::TestConfigTestEnv::test_rewrite_posargs tests/test_config.py::TestConfigTestEnv::test_rewrite_simple_posargs tests/test_config.py::TestConfigTestEnv::test_take_dependencies_from_other_testenv[envlist0-deps0] tests/test_config.py::TestConfigTestEnv::test_take_dependencies_from_other_testenv[envlist1-deps1] tests/test_config.py::TestConfigTestEnv::test_take_dependencies_from_other_section tests/test_config.py::TestConfigTestEnv::test_multilevel_substitution tests/test_config.py::TestConfigTestEnv::test_recursive_substitution_cycle_fails tests/test_config.py::TestConfigTestEnv::test_single_value_from_other_secton tests/test_config.py::TestConfigTestEnv::test_factors tests/test_config.py::TestConfigTestEnv::test_factor_ops tests/test_config.py::TestConfigTestEnv::test_default_factors tests/test_config.py::TestConfigTestEnv::test_factors_in_boolean tests/test_config.py::TestConfigTestEnv::test_factors_in_setenv tests/test_config.py::TestConfigTestEnv::test_factor_use_not_checked tests/test_config.py::TestConfigTestEnv::test_factors_groups_touch tests/test_config.py::TestConfigTestEnv::test_period_in_factor tests/test_config.py::TestConfigTestEnv::test_ignore_outcome tests/test_config.py::TestGlobalOptions::test_notest tests/test_config.py::TestGlobalOptions::test_verbosity tests/test_config.py::TestGlobalOptions::test_substitution_jenkins_default tests/test_config.py::TestGlobalOptions::test_substitution_jenkins_context tests/test_config.py::TestGlobalOptions::test_sdist_specification tests/test_config.py::TestGlobalOptions::test_env_selection tests/test_config.py::TestGlobalOptions::test_py_venv tests/test_config.py::TestGlobalOptions::test_default_environments tests/test_config.py::TestGlobalOptions::test_envlist_expansion tests/test_config.py::TestGlobalOptions::test_envlist_cross_product tests/test_config.py::TestGlobalOptions::test_envlist_multiline tests/test_config.py::TestGlobalOptions::test_minversion tests/test_config.py::TestGlobalOptions::test_skip_missing_interpreters_true tests/test_config.py::TestGlobalOptions::test_skip_missing_interpreters_false tests/test_config.py::TestGlobalOptions::test_defaultenv_commandline tests/test_config.py::TestGlobalOptions::test_defaultenv_partial_override tests/test_config.py::TestHashseedOption::test_default tests/test_config.py::TestHashseedOption::test_passing_integer tests/test_config.py::TestHashseedOption::test_passing_string tests/test_config.py::TestHashseedOption::test_passing_empty_string tests/test_config.py::TestHashseedOption::test_setenv tests/test_config.py::TestHashseedOption::test_noset tests/test_config.py::TestHashseedOption::test_noset_with_setenv tests/test_config.py::TestHashseedOption::test_one_random_hashseed tests/test_config.py::TestHashseedOption::test_setenv_in_one_testenv tests/test_config.py::TestSetenv::test_getdict_lazy tests/test_config.py::TestSetenv::test_getdict_lazy_update tests/test_config.py::TestSetenv::test_setenv_uses_os_environ tests/test_config.py::TestSetenv::test_setenv_default_os_environ tests/test_config.py::TestSetenv::test_setenv_uses_other_setenv tests/test_config.py::TestSetenv::test_setenv_recursive_direct tests/test_config.py::TestSetenv::test_setenv_overrides tests/test_config.py::TestSetenv::test_setenv_with_envdir_and_basepython tests/test_config.py::TestSetenv::test_setenv_ordering_1 tests/test_config.py::TestSetenv::test_setenv_cross_section_subst_issue294 tests/test_config.py::TestSetenv::test_setenv_cross_section_subst_twice tests/test_config.py::TestSetenv::test_setenv_cross_section_mixed tests/test_config.py::TestIndexServer::test_indexserver tests/test_config.py::TestIndexServer::test_parse_indexserver tests/test_config.py::TestIndexServer::test_multiple_homedir_relative_local_indexservers tests/test_config.py::TestConfigConstSubstitutions::test_replace_pathsep_unix[:] tests/test_config.py::TestConfigConstSubstitutions::test_replace_pathsep_unix[;] tests/test_config.py::TestConfigConstSubstitutions::test_pathsep_regex tests/test_config.py::TestParseEnv::test_parse_recreate tests/test_config.py::TestCmdInvocation::test_help tests/test_config.py::TestCmdInvocation::test_version tests/test_config.py::TestCmdInvocation::test_listenvs tests/test_config.py::TestCmdInvocation::test_listenvs_verbose_description tests/test_config.py::TestCmdInvocation::test_listenvs_all tests/test_config.py::TestCmdInvocation::test_listenvs_all_verbose_description tests/test_config.py::TestCmdInvocation::test_listenvs_all_verbose_description_no_additional_environments tests/test_config.py::TestCmdInvocation::test_config_specific_ini tests/test_config.py::TestCmdInvocation::test_no_tox_ini tests/test_config.py::TestCmdInvocation::test_override_workdir tests/test_config.py::TestCmdInvocation::test_showconfig_with_force_dep_version tests/test_config.py::test_env_spec[-e tests/test_config.py::TestCommandParser::test_command_parser_for_word tests/test_config.py::TestCommandParser::test_command_parser_for_posargs tests/test_config.py::TestCommandParser::test_command_parser_for_multiple_words tests/test_config.py::TestCommandParser::test_command_parser_for_substitution_with_spaces tests/test_config.py::TestCommandParser::test_command_parser_with_complex_word_set tests/test_config.py::TestCommandParser::test_command_with_runs_of_whitespace tests/test_config.py::TestCommandParser::test_command_with_split_line_in_subst_arguments tests/test_config.py::TestCommandParser::test_command_parsing_for_issue_10
tox/config.py CHANGELOG
tox/config.py CHANGELOG