test_utils.py 2.59 KB
Newer Older
# coding=utf-8
from unittest import TestCase
import mock

from earthdiagnostics.utils import TempFile, Utils


class TestTempFile(TestCase):
    def setUp(self):
        TempFile.scratch_folder = '/tmp'
        TempFile.prefix = 'prefix'

    def test_get(self):
        self.assertEqual(TempFile.get('tempfile', clean=False), '/tmp/tempfile')
        self.assertEqual(TempFile.get('tempfile2', clean=True), '/tmp/tempfile2')
        self.assertNotIn('/tmp/tempfile', TempFile.files)
        self.assertIn('/tmp/tempfile2', TempFile.files)

        TempFile.autoclean = True
        self.assertEqual(TempFile.get('tempfile3'), '/tmp/tempfile3')
        self.assertIn('/tmp/tempfile3', TempFile.files)

        TempFile.autoclean = False
        self.assertEqual(TempFile.get('tempfile4'), '/tmp/tempfile4')
        self.assertNotIn('/tmp/tempfile4', TempFile.files)

        with mock.patch('tempfile.mkstemp') as mkstemp_mock:
            with mock.patch('os.close') as close_mock:
                mkstemp_mock.return_value = (34, 'path_to_tempfile')
                TempFile.get()
                TempFile.get(suffix='suffix')

                mkstemp_mock.assert_has_calls((mock.call(dir='/tmp', prefix='prefix', suffix='.nc'),
                                               mock.call(dir='/tmp', prefix='prefix', suffix='suffix')))
                close_mock.assert_has_calls((mock.call(34), mock.call(34)))

    def test_clean(self):
        with mock.patch('os.path.exists') as exists_mock:
            with mock.patch('tempfile.mkstemp'):
                with mock.patch('os.close'):
                    with mock.patch('os.remove'):
                        TempFile.clean()
                        TempFile.clean()
                        exists_mock.side_effect = [True, False]
                        TempFile.autoclean = True
                        TempFile.get('tempfile')
                        TempFile.get('tempfile2')
                        TempFile.clean()
                        self.assertEqual(len(TempFile.files), 0)


class TestUtils(TestCase):

    def test_rename_variable(self):
        with mock.patch('earthdiagnostics.utils.Utils.rename_variables') as rename_mock:
            Utils.rename_variable('file', 'old', 'new')
Javier Vegas-Regidor's avatar
Javier Vegas-Regidor committed
            Utils.rename_variable('file', 'old', 'new', False)
Javier Vegas-Regidor's avatar
Javier Vegas-Regidor committed
            Utils.rename_variable('file', 'old', 'new', False, False)
            rename_mock.assert_has_calls((mock.call('file', {'old': 'new'}, True, True),
                                          mock.call('file', {'old': 'new'}, False, True),
                                          mock.call('file', {'old': 'new'}, False, False)))