Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

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!

question from:https://stackoverflow.com/questions/8047736/how-to-load-data-from-a-file-for-a-unit-test-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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):
       ....

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...