1

I want to dynamically change token in my bashrc to assert an expected outcome.

For example: in my ~/.bashrc i have my token set

export GITHUB_ACCESS_TOKEN=ghp_NNNNNNNNNNNN

During the test I want to set the token

export GITHUB_ACCESS_TOKEN=TEST

and then assert to check that I cant access my repos by running a click command:

result = runner.invoke(clicker_cli, ["git", "clone", "<url_here>"])

It is not working as intended. I can still access my repo with my original token.

Context: I am using https://click.palletsprojects.com/en/8.0.x/ https://docs.pytest.org/en/6.2.x/monkeypatch.html

Shod
  • 801
  • 3
  • 12
  • 33

1 Answers1

0

You can set an optional env dictionary (Mapping) that will be used at runtime. Check the invoke documentation for detail. So the following code will do the trick.

result = runner.invoke(
   clicker_cli, ["git", "clone", "<url_here>"], 
   env={"GITHUB_ACCESS_TOKEN": "TEST"}
)

Full example

Here is a full working example.

import click
import os
from click.testing import CliRunner


@click.command()
@click.argument("msg")
def echo_token(msg):
    click.echo(f"{msg} {os.environ.get('GITHUB_ACCESS_TOKEN')}")


def test_echo_token(token="MY_TOKEN"):
    runner = CliRunner()
    result = runner.invoke(echo_token, ["Token is"],
             env={"GITHUB_ACCESS_TOKEN": token})
    assert result.exit_code == 0
    assert token in result.output
    print(result.output)

We can see that the environment variable is correctly set by running it.

pytest -s click_test.py
# click_test.py Token is MY_TOKEN
Romain
  • 19,910
  • 6
  • 56
  • 65
  • It still uses my old token since it is in my bashrc. I was looking into this and I am trying to see if this works: https://stackoverflow.com/questions/27553576/load-environment-variables-of-bashrc-into-python – ChristheCow Dec 03 '21 at 20:30
  • Thank you for the clarification. I did try use that but it has my token "set" as my old token – ChristheCow Dec 03 '21 at 20:31
  • Reading the documentation you provided: Can you help me understand runner.isolation? I think this might help me – ChristheCow Dec 03 '21 at 20:36
  • @ChristheCow according to the documentation *This is automatically done in the `invoke()` method*. So it's not the solution you are looking for. IMO it depends on what you are doing in your method. If you invoke a shell from your Python code it might source the `.bashrc` and overwrite the variable. – Romain Dec 04 '21 at 09:49
  • 1
    I understand. I will have to dive deeper to see what it is actually doing. I will need to check if the invoke source the bashrc. You solution does work. Thank you. I am now just curious as to why it overwrites. – ChristheCow Dec 09 '21 at 18:31