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!
要从单元测试中的文件加载数据,如果测试数据与单元测试位于相同的目录中,则需要一个解决方案:
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.
您还可以使用StringIO或cStringIO来模拟包含文件内容的字符串作为文件。
链接地址: http://www.djcxy.com/p/54712.html