Debian Codegraph @

test/unit/conftest.py

raw
1 ######################################################################
2 #
3 # File: test/unit/conftest.py
4 #
5 # Copyright 2023 Backblaze Inc. All Rights Reserved.
6 #
7 # License https://www.backblaze.com/using_b2_code.html
8 #
9 ######################################################################
10 import importlib
11 import os
12 from unittest import mock
13
14 import pytest
15 from b2sdk.v2 import REALM_URLS
16
17 from b2._internal.console_tool import _TqdmCloser
18 from b2._internal.version_listing import CLI_VERSIONS, UNSTABLE_CLI_VERSION, get_int_version
19
20 from ..helpers import b2_uri_args_v3, b2_uri_args_v4
21 from .helpers import RunOrDieExecutor
22 from .test_console_tool import BaseConsoleToolTest
23
24
25 @pytest.hookimpl
26 def pytest_addoption(parser):
27 parser.addoption(
28 '--cli',
29 default=UNSTABLE_CLI_VERSION,
30 choices=CLI_VERSIONS,
31 help='version of the CLI',
32 )
33
34
35 @pytest.hookimpl
36 def pytest_report_header(config):
37 int_version = get_int_version(config.getoption('--cli'))
38 return f"b2 apiver: {int_version}"
39
40
41 @pytest.fixture(scope='session')
42 def cli_version(request) -> str:
43 return request.config.getoption('--cli')
44
45
46 @pytest.fixture
47 def homedir(tmp_path_factory):
48 yield tmp_path_factory.mktemp("test_homedir")
49
50
51 @pytest.fixture
52 def env(homedir, monkeypatch):
53 """Get ENV for running b2 command from shell level."""
54 monkeypatch.setenv("HOME", str(homedir))
55 monkeypatch.delenv("XDG_CONFIG_HOME", raising=False)
56 monkeypatch.setenv("SHELL", "/bin/bash") # fix for running under github actions
57 if "TERM" not in os.environ:
58 monkeypatch.setenv("TERM", "xterm")
59 yield os.environ
60
61
62 @pytest.fixture(scope='session')
63 def console_tool_class(cli_version):
64 # Ensures import of the correct library to handle all the tests.
65 module = importlib.import_module(f'b2._internal.{cli_version}.registry')
66 return module.ConsoleTool
67
68
69 @pytest.fixture(scope='class')
70 def unit_test_console_tool_class(request, console_tool_class):
71 # Ensures that the unittest class uses the correct console tool version.
72 request.cls.console_tool_class = console_tool_class
73
74
75 @pytest.fixture(autouse=True, scope='session')
76 def mock_realm_urls():
77 with mock.patch.dict(REALM_URLS, {'production': 'http://production.example.com'}):
78 yield
79
80
81 @pytest.fixture
82 def bg_executor():
83 """Executor for running background tasks in tests"""
84 with RunOrDieExecutor() as executor:
85 yield executor
86
87
88 @pytest.fixture(autouse=True)
89 def disable_tqdm_closer_cleanup():
90 with mock.patch.object(_TqdmCloser, '__exit__'):
91 yield
92
93
94 class ConsoleToolTester(BaseConsoleToolTest):
95 def authorize(self):
96 self._authorize_account()
97
98 def run(self, *args, **kwargs):
99 return self._run_command(*args, **kwargs)
100
101
102 @pytest.fixture(scope="session", autouse=True)
103 def mock_signal():
104 with mock.patch('signal.signal'):
105 yield
106
107
108 @pytest.fixture
109 def b2_cli(console_tool_class):
110 cli_tester = ConsoleToolTester()
111 # Because of the magic the pytest does on importing and collecting fixtures,
112 # ConsoleToolTester is not injected with the `unit_test_console_tool_class`
113 # despite having it as a parent.
114 # Thus, we inject it manually here.
115 cli_tester.console_tool_class = console_tool_class
116 cli_tester.setUp()
117 yield cli_tester
118 cli_tester.tearDown()
119
120
121 @pytest.fixture
122 def authorized_b2_cli(b2_cli):
123 b2_cli.authorize()
124 yield b2_cli
125
126
127 @pytest.fixture
128 def bucket_info(b2_cli, authorized_b2_cli):
129 bucket_name = "my-bucket"
130 bucket_id = "bucket_0"
131 b2_cli.run(['create-bucket', bucket_name, 'allPublic'], expected_stdout=f'{bucket_id}\n')
132 return {
133 'bucketName': bucket_name,
134 'bucketId': bucket_id,
135 }
136
137
138 @pytest.fixture
139 def bucket(bucket_info):
140 return bucket_info['bucketName']
141
142
143 @pytest.fixture
144 def local_file(tmp_path):
145 """Set up a test file and return its path."""
146 filename = 'file1.txt'
147 content = 'hello world'
148 local_file = tmp_path / filename
149 local_file.write_text(content)
150
151 mod_time = 1500111222
152 os.utime(local_file, (mod_time, mod_time))
153
154 return local_file
155
156
157 @pytest.fixture
158 def uploaded_file_with_control_chars(b2_cli, bucket_info, local_file):
159 filename = '\u009bC\u009bC\u009bIfile.txt'
160 b2_cli.run(['upload-file', bucket_info["bucketName"], str(local_file), filename])
161 return {
162 'bucket': bucket_info["bucketName"],
163 'bucketId': bucket_info["bucketId"],
164 'fileName': filename,
165 'escapedFileName': '\\\\x9bC\\\\x9bC\\\\x9bIfile.txt',
166 'fileId': '1111',
167 'content': local_file.read_text(),
168 }
169
170
171 @pytest.fixture
172 def uploaded_file(b2_cli, bucket_info, local_file):
173 filename = 'file1.txt'
174 b2_cli.run(['upload-file', '--quiet', bucket_info["bucketName"], str(local_file), filename])
175 return {
176 'bucket': bucket_info["bucketName"],
177 'bucketId': bucket_info["bucketId"],
178 'fileName': filename,
179 'fileId': '9999',
180 'content': local_file.read_text(),
181 }
182
183
184 @pytest.fixture(scope='class')
185 def b2_uri_args(apiver_int, request):
186 if apiver_int >= 4:
187 fn = b2_uri_args_v4
188 else:
189 fn = b2_uri_args_v3
190
191 request.cls.b2_uri_args = staticmethod(fn)