Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use test resources (like a fixed yaml file) with pytest?

I've looked around the docs on the pytest website, but haven't found a clear example of working with 'test resources', such as reading in fixed files during unit tests. Something similar to what http://jlorenzen.blogspot.com/2007/06/proper-way-to-access-file-resources-in.html describes for Java.

For example, if I have a yaml file checked in to source control, what is the right way to write a test which loads from that file? I think this boils down to understanding the right way to access a 'resource file' on the python equivalent of the classpath (PYTHONPATH?).

This seems like it should be simple. Is there an easy solution?

like image 888
Jacob Avatar asked Apr 11 '13 00:04

Jacob


People also ask

How do I run a specific file in pytest?

Running pytest We can run a specific test file by giving its name as an argument. A specific function can be run by providing its name after the :: characters. Markers can be used to group tests. A marked grouped of tests is then run with pytest -m .

Do pytest files need to start with test?

Pytest requires the test function names to start with test. Function names which are not of format test* are not considered as test functions by pytest. We cannot explicitly make pytest consider any function not starting with test as a test function.

How do I use pytest fixtures?

To access the fixture function, the tests have to mention the fixture name as input parameter. Pytest while the test is getting executed, will see the fixture name as input parameter. It then executes the fixture function and the returned value is stored to the input parameter, which can be used by the test.


1 Answers

Perhaps what you are looking for is pkg_resources or pkgutil. For example, if you have a module within your python source called "resources", you could read your "resourcefile" using:

with open(pkg_resources.resource_filename("resources", "resourcefile")) as infile:
    for line in infile:
        print(line)

or:

 with tempfile.TemporaryFile() as outfile:
        outfile.write(pkgutil.get_data("resources", "resourcefile"))

The latter even works when your "script" is an executable zip file. The former works without needing to unpack your resources from an egg.

Note that creating a subdirectory of your source does not make it a module. You need to add a file named __init__.py within the directory for it to be visible as a module for the purposes of pkg_resources and pkgutil. __init__.py can be empty.

like image 159
Dave Avatar answered Oct 13 '22 12:10

Dave