How to load data from a file, for a unit test, in python?
You can also use a StringIO or cStringIO to simulate a string containing your file's contents as a file.
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):
....
I guess your task boils down to what's given here to get the current file. Then extend that path by the path to you HTML file and open it.
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):
....