pytest parse argument and compare output files

Viewed 368

I wrote a program which I run in terminal by the following command

python simulation.py -f data_file.dat

The simulate.py script requires a input to run, "-f" and then the filename. The script writes image files and a average.csv file during running.

I am writing test code for the first time and have implemented unit tests for most functions found into simulate.py.

Now I want to write testing code for some of the images and average.csv and then do a diff check on the actual == expected image and csv. But these files are generated with calculations which are additive, therefore the only way to check that they are working is by running through the calculations and choosing a specific iteration to check actual vs expected.

  1. How can I run the script simulate.py with the argument using pytest?

  2. What is the best practice to compare the new files with the expected? Should I read the newly generated data in the test code and compare to a predefined expected file?

I attempted to write a test_case.py using the following:

import argparse
import pytest   

ap = argparse.ArgumentParser()
ap.add_argument("-f", required =True, default = "map.dat")
args = vars(ap.parse_args())

And then running the command pytest which results in an error:

------------------------------ Captured stderr --------------------------------
usage: pytest [-h] -f F
pytest: error: the following arguments are required: -f
=========================== short test summary info ============================
ERROR test_case.py - SystemExit: 2
!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
1 Answers

In Simulation.py you could have:

if __name__ == "__main__":
    args = sys.argv[1:]
    main(args)

def main(args):
    #write to data_file.dat bla bla

Then in the test_case.py you could import the main() function and pass arguments directly.

from simulation import main

class TestFileWrite:
    def test_data_file_dat(self):
        main(["arg1", "arg2"])
        assert [row for row in open("data_file.dat")] == [row for row in open("data_file_ref.dat")]
  1. It depends on the length of the file. If it is short text, you could store it in string literal data_ref=""" """
Related