I am writing some unit tests (using the unittest module) for my application and want to write something that can verify that the method I call returns a file object. Since this is not an easy call, I wonder what is the best practice for defining this?
So in the diagram:
possible_file = self.dao.get_file("anotherfile.pdf") self.assertTrue(possible_file is file-like)
Perhaps I need to consider which specific interface this file object implements or what methods make it file-based, how do I want to support it?
Thank,
R
" " , " ", , , read write ... , fileno, " ", StringIO cStringIO . " ", - !
read
write
fileno
StringIO
cStringIO
, , . , FileLikeEnoughForMe abstractmethod isinstance , Python 2.6 : , hasattr, ( , .. -).
FileLikeEnoughForMe
abstractmethod
isinstance
hasattr
Python , , . , , , write ing.
IO > isinstance. , , , .
(unittesting) , , :
thingy = ... try: thingy.write( ... ) thingy.writeline( ... ) ... thingy.read( ) except AttributeError: ...
Check if the returned object provides the interface you are looking for. For example, for example:
self.assert_(hasattr(possible_file, 'write')) self.assert_(hasattr(possible_file, 'read'))