1# Licensed under the Apache License, Version 2.0 (the "License"); 2# you may not use this file except in compliance with the License. 3# You may obtain a copy of the License at 4# 5# http://www.apache.org/licenses/LICENSE-2.0 6# 7# Unless required by applicable law or agreed to in writing, software 8# distributed under the License is distributed on an "AS IS" BASIS, 9# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10# See the License for the specific language governing permissions and 11# limitations under the License. 12 13""" 14Provides patches for some commonly used modules that enable them to work 15with pyfakefs. 16""" 17 18import os 19import sys 20import unittest 21 22from pyfakefs import fake_filesystem_unittest 23from pyfakefs.helpers import IS_PYPY 24 25try: 26 import pandas as pd 27except ImportError: 28 pd = None 29 30try: 31 import xlrd 32except ImportError: 33 xlrd = None 34 35try: 36 import openpyxl 37except ImportError: 38 openpyxl = None 39 40 41@unittest.skipIf( 42 IS_PYPY and sys.version_info < (3, 8), "Has a problem with older PyPy versions" 43) 44class TestPatchedPackages(fake_filesystem_unittest.TestCase): 45 def setUp(self): 46 self.setUpPyfakefs() 47 48 if pd is not None: 49 50 def test_read_csv(self): 51 path = "/foo/bar.csv" 52 self.fs.create_file(path, contents="1,2,3,4") 53 df = pd.read_csv(path) 54 assert (df.columns == ["1", "2", "3", "4"]).all() 55 56 def test_read_table(self): 57 path = "/foo/bar.csv" 58 self.fs.create_file(path, contents="1|2|3|4") 59 df = pd.read_table(path, delimiter="|") 60 assert (df.columns == ["1", "2", "3", "4"]).all() 61 62 if pd is not None and xlrd is not None: 63 64 def test_read_excel(self): 65 path = "/foo/bar.xlsx" 66 src_path = os.path.dirname(os.path.abspath(__file__)) 67 src_path = os.path.join(src_path, "fixtures", "excel_test.xlsx") 68 # map the file into another location to be sure that 69 # the real fs is not used 70 self.fs.add_real_file(src_path, target_path=path) 71 df = pd.read_excel(path) 72 assert (df.columns == [1, 2, 3, 4]).all() 73 74 if pd is not None and openpyxl is not None: 75 76 def test_write_excel(self): 77 self.fs.create_dir("/foo") 78 path = "/foo/bar.xlsx" 79 df = pd.DataFrame([[0, 1, 2, 3]]) 80 with pd.ExcelWriter(path) as writer: 81 df.to_excel(writer) 82 df = pd.read_excel(path) 83 assert (df.columns == ["Unnamed: 0", 0, 1, 2, 3]).all() 84