pythonpytestmonkeypatchingpython-click

Pytest: How do I change ~/.bashrc token durning runtime?


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


Solution

  • 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