unit testing - Mocking zipfile in python -


i'm trying use python mock library mock few methods zipfile module.

example source want test:

def zipstuff(listofpathtofiles):     zipfile(fname, 'w') archive:         each in listofpathtofiles:              archive.write(each, strippedfname)     return archive 

the "archive" above ignored normal execution, list of files during tests.

example unittest code:

emptylist=[]  def mockwrite(fname):     emptylist.append(fname)     return  mockzip.__enter__ = mock(return_value=emptylist) mockzip.__exit__ = mock(return_value=true) 

now, want mock archive.write instead of actual write call, replaced mockwrite function can list of files supposed zipped.

i've tried:

mockzip.write = mock(side_effect=mockwrite) 

but wasn't being called. debugging shows function calling mockzip.enter().write. if try:

mockzip.__enter__().write = mock(side_effect=mockwrite) 

python issues error 'list' has no attribute write (which correct). i'm new mock , python , appreciate pointers. suggestions?

instead of having mockzip.__enter__ return empty list, have return object following:

class mockzipfile:     def __init__(self):         self.files = []     def __iter__(self):         return iter(self.files)     def write(self, fname):         self.files.append(fname) 

you can add methods , implementations needed suit mocking needs.


Comments

Popular posts from this blog

Android : Making Listview full screen -

javascript - Parse JSON from the body of the POST -

javascript - Chrome Extension: Interacting with iframe embedded within popup -