mercredi 22 juin 2016

How to patch an import in an imported module?

I'm trying to create unit tests for a module that is eases loading things to S3. The specific functionality in question takes an infile, fully-qualified or no, splits out the basename of the infile, and then does a Unix style join (has to always be Unix-style due to S3's folder structure) to the s3_destination, which would be an arbitrary folder structure, i.e. jira/some_folder/.

My difficulty comes from the fact that I develop (and test) on a Mac, and deploy on Windows. I would like to patch the os.path module in my module I'm importing so that it behaves as it would on Windows in my unit tests.

Here is a snippet of the code from the module class (S3Loader) being imported, aws_utils:

from os import path
import posixpath as u_path

self.s3_destination = u_path.join(
    self._s3_filepath,
    os.path.basename(self._infile)
)

So I'm using the posixpath module to assure that the join for the destination on S3 is always Unix-style, but the problem lies in how to unit-test the os.path.basename portion. I'd like to be able to patch it in the unit test to set aws_utils import of os.path to ntpath.

Here is the unit test:

def test_setting_infile_correctly_sets_s3_destination_on_windows(self):
    unloader = aws_utils.S3Loader(
        infile=r'C:\filepath\folder\testfile.txt',
        s3_filepath='testfolder/test1/')
    self.assertEqual(
        unloader.s3_destination,
        'testfolder/test1/testfile.txt')
    self.assertEqual(
        unloader.get_full_destination(),
        r'http://s3***/testfolder/test1/testfile.txt')

Aucun commentaire:

Enregistrer un commentaire