1

I have a click command that does something with a file:

import click

@click.command()
@click.argument("file", type=click.File("r"))
def foo(file):
    print(file.read())

And I'd like to test it without creating temporary files, but I don't know which path to give the runner and can't find examples on the web. Something like this would be nice:

from click.testing import CliRunner

from magic_lib import magic_file

def test_foo():
    runner = CliRunner()
    fake_file = magic_file("Hello, world!")
    result = runner.invoke(foo, [fake_file.location])
    assert result.output == "Hello, world!\n"

Any way I can make click.File understand where I want it to look?

1 Answer 1

1

You can use pyfakefs. The usage depends on your testing framework; it's easiest to use with pytest because it automatically provides an fs fixture:

def test_foo(fs):
    fake_file = fs.create_file('/foo/bar', contents="Hello, world!")

    runner = CliRunner()
    result = runner.invoke(foo, [fake_file.path])
    assert result.output == "Hello, world!\n"

P.S.: Because the print in foo adds a newline, the file has to be created without \n at the end for the test to work.

Sign up to request clarification or add additional context in comments.

4 Comments

"pyfakefs automatically adds a newline to the file" I think that's from the click function, since it calls print.
Funny thing, I just found an example solution using click's own test object here, but yours is way leaner and allows me to re-use my invoke-fixture, so I won't bother writing an answer featuring that one.
@Arne I think you should reconsider it. IMO The optimal solution is to use isolated_filesystem
@FcknGioconda why do you think click's is better? As far as I can see, pyfakefs does the same thing, but once I learned it I can also use it in all my other projects that don't use click.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.