Chel MS
Chel MS

Reputation: 466

Pytest for my function that validates json file contents

I have a Python function that creates & appends content to a json file on the disk. Wanted to develop test cases using pytest.

Json snippet:

{
    "pictures": [
        "/home/mywork/pictures/pictures.zip",
        "/home/mywork/pictures/record.json"
    ],
    "lab_results": [
        "/home/mywork/lab_results/lab_results.zip",
        "/home/mywork/lab_results/private/results.json"
    ]
    ....
  }

How should I assert availability of files on the disk? I mean, json values are the physical files on the disk & would like to throw an error if the file is missing or of different pattern/format.

Is there a recommended way of doing that or any pre available module from pytest?

Upvotes: 0

Views: 727

Answers (1)

sphennings
sphennings

Reputation: 1083

Best practice would be to mock the filesystem calls and run your tests without touching the filesystem.

If you absolutely need to run tests against the filesystem pytest provides the tmp_path fixture to provide a unique temporary directory for you to use during testing.

You would then follow basic test practices of setting up your test environment, (in this case adding the relevant files to the directory), triggering a behavior (reading from or writing to files in the directory), then asserting that things happened as expected.

Upvotes: 1

Related Questions