Skip to content

Commit

Permalink
Merge pull request #874 from rgreinho/ISSUE-873/variable-precedence
Browse files Browse the repository at this point in the history
Fix variable precedence
  • Loading branch information
zacbir authored May 14, 2018
2 parents df1a8f5 + 535559a commit 9c456ec
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 2 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ dist
build
docs/_build
click.egg-info
venv/
.tox
.cache
.ropeproject
Expand Down
5 changes: 3 additions & 2 deletions click/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1328,12 +1328,13 @@ def get_default(self, ctx):
def add_to_parser(self, parser, ctx):
pass


def consume_value(self, ctx, opts):
value = opts.get(self.name)
if value is None:
value = ctx.lookup_default(self.name)
if value is None:
value = self.value_from_envvar(ctx)
if value is None:
value = ctx.lookup_default(self.name)
return value

def type_cast_value(self, ctx, value):
Expand Down
48 changes: 48 additions & 0 deletions tests/test_commands.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# -*- coding: utf-8 -*-
import re

import click
import pytest


def test_other_command_invoke(runner):
Expand Down Expand Up @@ -267,3 +269,49 @@ def foo_bar():
result = runner.invoke(cli, ['foo-bar'])
assert not result.exception
assert result.output.splitlines() == ['foo-bar']


def test_environment_variables(runner):
@click.group()
def cli():
pass

@cli.command()
@click.option('--name', envvar='CLICK_NAME')
def foo(name):
click.echo(name)

result = runner.invoke(cli, ['foo'], env={'CLICK_NAME': 'environment'})

assert not result.exception
assert result.output == 'environment\n'


# Ensures the variables are read in the following order:
# 1. CLI
# 2. Environment
# 3. Defaults
variable_precedence_testdata = [
(['foo', '--name=cli'], {'CLICK_NAME': 'environment'}, 'cli\n'),
(['foo'], {'CLICK_NAME': 'environment'}, 'environment\n'),
(['foo'], None, 'defaults\n'),
]


@pytest.mark.parametrize("command,environment,expected",
variable_precedence_testdata)
def test_variable_precendence_00(runner, command, environment, expected):
@click.group()
def cli():
pass

@cli.command()
@click.option('--name', envvar='CLICK_NAME')
def foo(name):
click.echo(name)

defaults = {'foo': {'name': 'defaults'}}
result = runner.invoke(cli, command, default_map=defaults, env=environment)

assert not result.exception
assert result.output == expected
1 change: 1 addition & 0 deletions tox.ini
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
[tox]
envlist = py27,py34,py35,py36,pypy
skip_missing_interpreters = true

[testenv]
passenv = LANG
Expand Down

0 comments on commit 9c456ec

Please sign in to comment.