Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load data from a file, for a unit test, in python?

I've written a specialized HTML parser, that I want to unit test with a couple of sample webpages I've downloaded.

In Java, I've used class resources, to load data into unit tests, without having to rely on them being at a particular path on the file system. Is there a way to do this in Python?

I found the doctest.testfile() function, but that appears to be specific to doctests. I'd like to just get a file handle, to a particular HTML file, which is relative to the current module.

Thanks in advance for any suggestions!

like image 485
cberner Avatar asked Nov 08 '11 08:11

cberner


People also ask

How do I run a unit test file in Python?

The command to run the tests is python -m unittest filename.py . In our case, the command to run the tests is python -m unittest test_utils.py .

Where do I put unit test files in Python?

There are several commonly accepted places to put test_module.py : In the same directory as module.py . In ../tests/test_module.py (at the same level as the code directory). In tests/test_module.py (one level under the code directory).


2 Answers

To load data from a file in a unittest, if the testdata is on the same dir as unittests, one solution :

TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__), 'testdata.html')   class MyTest(unittest.TestCase)     def setUp(self):        self.testdata = open(TESTDATA_FILENAME).read()     def test_something(self):        .... 
like image 55
Ferran Avatar answered Sep 23 '22 03:09

Ferran


This is based on Ferran's answer, but it closes the file during MyTest.tearDown() to avoid 'ResourceWarning: unclosed file':

TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__), 'testdata.html')   class MyTest(unittest.TestCase)     def setUp(self):        self.testfile = open(TESTDATA_FILENAME)        self.testdata = self.testfile.read()     def tearDown(self):        self.testfile.close()     def test_something(self):        .... 
like image 30
Leila Hadj-Chikh Avatar answered Sep 25 '22 03:09

Leila Hadj-Chikh