forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_open.py
78 lines (61 loc) · 2.56 KB
/
test_open.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import io
import os.path
import pathlib
import sys
import unittest
import importlib_resources as resources
from importlib_resources.tests import data
class CommonTests(unittest.TestCase):
def test_package_name(self):
# Passing in the package name should succeed.
with resources.open(data.__name__, 'utf-8.file') as file:
pass # No error.
def test_package_object(self):
# Passing in the package itself should succeed.
with resources.open(data, 'utf-8.file') as file:
pass # No error.
def test_string_path(self):
path = 'utf-8.file'
# Passing in a string for the path should succeed.
with resources.open(data, path) as file:
pass # No error.
@unittest.skipIf(sys.version_info < (3, 6), 'requires os.PathLike support')
def test_pathlib_path(self):
# Passing in a pathlib.PurePath object for the path should succeed.
path = pathlib.PurePath('utf-8.file')
with resources.open(data, path) as file:
pass # No error.
def test_absolute_path(self):
# An absolute path is a ValueError.
path = pathlib.Path(__file__)
full_path = path.parent/'utf-8.file'
with self.assertRaises(ValueError):
with resources.open(data, str(full_path)) as file:
pass
def test_relative_path(self):
# A reative path is a ValueError.
with self.assertRaises(ValueError):
with resources.open(data, '../data/utf-8.file') as file:
pass
def test_importing_module_as_side_effect(self):
# The anchor package can already be imported.
del sys.modules[data.__name__]
with resources.open(data.__name__, 'utf-8.file') as file:
pass # No Errors.
def test_non_package(self):
# The anchor package cannot be a module.
with self.assertRaises(TypeError):
with resources.open(__spec__.name, 'utf-8.file') as file:
pass
class OpenTests(unittest.TestCase):
def test_opened_for_reading(self):
# The file-like object is ready for reading.
with resources.open(data, 'utf-8.file') as file:
self.assertEqual(b"Hello, UTF-8 world!\n", file.read())
def test_wrap_for_text(self):
# The file-like object can be wrapped for text reading.
with resources.open(data, 'utf-8.file') as file:
text_file = io.TextIOWrapper(file, encoding='utf-8')
self.assertEqual('Hello, UTF-8 world!\n', text_file.read())
if __name__ == '__main__':
unittest.main()