|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +import io |
| 4 | +import os |
| 5 | +import sys |
| 6 | +import tempfile |
| 7 | + |
| 8 | +from fitparse.utils import fileish_open |
| 9 | + |
| 10 | +if sys.version_info >= (2, 7): |
| 11 | + import unittest |
| 12 | +else: |
| 13 | + import unittest2 as unittest |
| 14 | + |
| 15 | + |
| 16 | +def testfile(filename): |
| 17 | + return os.path.join(os.path.dirname(os.path.realpath(__file__)), 'files', filename) |
| 18 | + |
| 19 | + |
| 20 | +class UtilsTestCase(unittest.TestCase): |
| 21 | + |
| 22 | + def test_fileish_open_read(self): |
| 23 | + """Test the constructor does the right thing when given different types |
| 24 | + (specifically, test files with 8 characters, followed by an uppercase.FIT |
| 25 | + extension), which confused the fileish check on Python 2, see |
| 26 | + https://github.com/dtcooper/python-fitparse/issues/29#issuecomment-312436350 |
| 27 | + for details""" |
| 28 | + |
| 29 | + def test_fopen(fileish): |
| 30 | + with fileish_open(fileish, 'rb') as f: |
| 31 | + self.assertIsNotNone(f.read(1)) |
| 32 | + f.seek(0, os.SEEK_SET) |
| 33 | + |
| 34 | + test_fopen(testfile('nametest.FIT')) |
| 35 | + with open(testfile("nametest.FIT"), 'rb') as f: |
| 36 | + test_fopen(f) |
| 37 | + with open(testfile("nametest.FIT"), 'rb') as f: |
| 38 | + test_fopen(f.read()) |
| 39 | + with open(testfile("nametest.FIT"), 'rb') as f: |
| 40 | + test_fopen(io.BytesIO(f.read())) |
| 41 | + |
| 42 | + def test_fileish_open_write(self): |
| 43 | + |
| 44 | + def test_fopen(fileish): |
| 45 | + with fileish_open(fileish, 'wb') as f: |
| 46 | + f.write(b'\x12') |
| 47 | + f.seek(0, os.SEEK_SET) |
| 48 | + |
| 49 | + tmpfile = tempfile.NamedTemporaryFile(prefix='fitparse-test', suffix='.FIT', delete=False) |
| 50 | + filename = tmpfile.name |
| 51 | + tmpfile.close() |
| 52 | + try: |
| 53 | + test_fopen(filename) |
| 54 | + with open(filename, 'wb') as f: |
| 55 | + test_fopen(f) |
| 56 | + test_fopen(io.BytesIO()) |
| 57 | + finally: |
| 58 | + # remove silently |
| 59 | + try: |
| 60 | + os.remove(filename) |
| 61 | + except OSError: |
| 62 | + pass |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == '__main__': |
| 66 | + unittest.main() |
0 commit comments