Debian Codegraph @

tests/testing.py

raw
1 # -*- coding: utf-8 -*-
2 # coding=utf-8
3 # --------------------------------------------------------------------------
4 # Copyright (c) Microsoft Corporation. All rights reserved.
5 # Licensed under the MIT License. See License.txt in the project root for
6 # license information.
7 # --------------------------------------------------------------------------
8
9 from contextlib import contextmanager
10 import copy
11 from hashlib import md5
12 import os
13 import shutil
14 import tempfile
15 import uuid
16
17 import pytest
18 import vcr
19
20 from azure.datalake.store.core import AzureDLPath
21 from tests import fake_settings, settings
22 from tests.settings import ROOT_DIR
23
24
25 def _build_func_path_generator(function):
26 import inspect
27 module = os.path.basename(inspect.getfile(function)).replace('.py', '')
28 return module + '/' + function.__name__
29
30
31 def _scrub(val):
32 val = val.replace(settings.STORE_NAME, fake_settings.STORE_NAME)
33 val = val.replace(settings.TENANT_ID, fake_settings.TENANT_ID)
34 val = val.replace(settings.SUBSCRIPTION_ID, fake_settings.SUBSCRIPTION_ID)
35 val = val.replace(settings.RESOURCE_GROUP_NAME, fake_settings.RESOURCE_GROUP_NAME)
36 return val
37
38
39 def _scrub_sensitive_request_info(request):
40 request.uri = _scrub(request.uri.replace('%5C', '/'))
41 return request
42
43
44 def _scrub_sensitive_response_info(response):
45 response = copy.deepcopy(response)
46
47 headers = response.get('headers')
48 if headers:
49 for name, val in headers.items():
50 for i, v in enumerate(val):
51 val[i] = _scrub(v)
52
53 return response
54
55
56 recording_path = os.path.join(os.path.dirname(__file__), 'recordings')
57
58 my_vcr = vcr.VCR(
59 cassette_library_dir=recording_path,
60 record_mode=settings.RECORD_MODE,
61 before_record=_scrub_sensitive_request_info,
62 before_record_response=_scrub_sensitive_response_info,
63 func_path_generator=_build_func_path_generator,
64 path_transformer=vcr.VCR.ensure_suffix('.yaml'),
65 filter_headers=['authorization'],
66 filter_query_parameters=['filesessionid', 'leaseid']
67 )
68
69
70 def working_dir():
71 if not hasattr(working_dir, "path"):
72 unique_dir = ROOT_DIR
73 working_dir.path = AzureDLPath(unique_dir)
74 return working_dir.path
75
76
77 @pytest.fixture()
78 def azure():
79 from azure.datalake.store import AzureDLFileSystem
80 fs = AzureDLFileSystem(token_credential=settings.TOKEN_CREDEDENTIAL, store_name=settings.STORE_NAME)
81 # Clear filesystem cache to ensure we capture all requests from a test
82 fs.invalidate_cache()
83
84 yield fs
85
86 @pytest.fixture()
87 def second_azure():
88 from azure.datalake.store import AzureDLFileSystem
89 fs = AzureDLFileSystem(token_credential=settings.TOKEN_CREDEDENTIAL, store_name=settings.STORE_NAME)
90
91 # Clear filesystem cache to ensure we capture all requests from a test
92 fs.invalidate_cache()
93 yield fs
94
95
96 @contextmanager
97 def create_files(azure, number_of_files, root_path = working_dir(), prefix=''):
98 import itertools
99 from string import ascii_lowercase
100
101 def generate_paths():
102 def iter_all_strings():
103 for size in itertools.count(1):
104 for s in itertools.product(ascii_lowercase, repeat=size):
105 yield "".join(s)
106
107 for s in itertools.islice(iter_all_strings(), number_of_files):
108 s = AzureDLPath(prefix + s + ".txt")
109 yield root_path / s
110 for f in generate_paths():
111 azure.touch(f)
112
113
114 @contextmanager
115 def azure_teardown(fs):
116 try:
117 fs.mkdir(working_dir())
118 yield
119 finally:
120 # this is a best effort. If there is an error attempting to delete during cleanup,
121 # print it, but it should not cause the test to fail.
122 try:
123 fs.rm(working_dir(), recursive=True)
124 for path in fs.ls(working_dir(), invalidate_cache=False):
125 if fs.exists(path, invalidate_cache=False):
126 fs.rm(path, recursive=True)
127 except Exception as e:
128 print('warning: cleanup failed with exception:')
129 print(e)
130
131 @contextmanager
132 def ignoring(*exceptions):
133 try:
134 yield
135 except exceptions:
136 pass
137
138
139 @contextmanager
140 def tmpfile(extension='', dir=None):
141 extension = '.' + extension.lstrip('.')
142 handle, filename = tempfile.mkstemp(extension, dir=dir)
143 os.close(handle)
144 os.remove(filename)
145
146 try:
147 yield filename
148 finally:
149 if os.path.exists(filename):
150 if os.path.isdir(filename):
151 shutil.rmtree(filename)
152 else:
153 with ignoring(OSError):
154 os.remove(filename)
155
156
157 def md5sum(fname, chunksize=4096):
158 hashobj = md5()
159 with open(fname, 'rb') as f:
160 for chunk in iter(lambda: f.read(chunksize), b''):
161 hashobj.update(chunk)
162 return hashobj.hexdigest()
163
164
165 def posix(*args):
166 return AzureDLPath(*args).as_posix()