microversion-parse 1.0.1__py3-none-any.whl → 2.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,7 +12,11 @@
12
12
  # limitations under the License.
13
13
 
14
14
  import collections
15
+ from collections.abc import Iterable, MutableMapping, Sequence
16
+ from typing import Any, TYPE_CHECKING
15
17
 
18
+ if TYPE_CHECKING:
19
+ from typing_extensions import Self
16
20
 
17
21
  ENVIRON_HTTP_HEADER_FMT = 'http_{}'
18
22
  STANDARD_HEADER = 'openstack-api-version'
@@ -24,19 +28,25 @@ class Version(collections.namedtuple('Version', 'major minor')):
24
28
  Since it is a tuple, it is automatically comparable.
25
29
  """
26
30
 
27
- def __new__(cls, major, minor):
31
+ max_version: tuple[int, int]
32
+ min_version: tuple[int, int]
33
+
34
+ def __new__(cls, major: int, minor: int) -> 'Self':
28
35
  """Add min and max version attributes to the tuple."""
29
- self = super(Version, cls).__new__(cls, major, minor)
36
+ self = super().__new__(cls, major, minor)
30
37
  self.max_version = (-1, 0)
31
38
  self.min_version = (-1, 0)
32
39
  return self
33
40
 
34
- def __str__(self):
35
- return '%s.%s' % (self.major, self.minor)
41
+ def __str__(self) -> str:
42
+ return f'{self.major}.{self.minor}'
36
43
 
37
- def matches(self, min_version=None, max_version=None):
38
- """Is this version within min_version and max_version.
39
- """
44
+ def matches(
45
+ self,
46
+ min_version: tuple[int, int] | None = None,
47
+ max_version: tuple[int, int] | None = None,
48
+ ) -> bool:
49
+ """Is this version within min_version and max_version."""
40
50
  # NOTE(cdent): min_version and max_version are expected
41
51
  # to be set by the code that is creating the Version, if
42
52
  # they are known.
@@ -47,31 +57,34 @@ class Version(collections.namedtuple('Version', 'major minor')):
47
57
  return min_version <= self <= max_version
48
58
 
49
59
 
50
- def get_version(headers, service_type, legacy_headers=None):
60
+ def get_version(
61
+ headers: Iterable[tuple[str, str]] | MutableMapping[str, str],
62
+ service_type: str,
63
+ legacy_headers: Iterable[str] | None = None,
64
+ ) -> str | None:
51
65
  """Parse a microversion out of headers
52
66
 
53
- :param headers: The headers of a request, dict or list
54
- :param service_type: The service type being looked for in the headers
55
- :param legacy_headers: Other headers to look at for a version
56
- :returns: a version string or "latest"
57
- :raises: ValueError
58
-
59
- If headers is not a dict we assume is an iterator of
60
- tuple-like headers, which we will fold into a dict.
67
+ If headers is not a dict we assume is an iterator of tuple-like headers,
68
+ which we will fold into a dict.
61
69
 
62
- The flow is that we first look for the new standard singular
63
- header:
70
+ The flow is that we first look for the new standard singular header:
64
71
 
65
- * openstack-api-version: <service> <version>
72
+ * ``openstack-api-version: <service> <version>``
66
73
 
67
74
  If that's not present we fall back to the headers listed in
68
- legacy_headers. These often look like this:
75
+ ``legacy_headers``. These often look like this:
76
+
77
+ * ``openstack-<service>-api-version: <version>``
78
+ * ``openstack-<legacy>-api-version: <version>``
79
+ * ``x-openstack-<legacy>-api-version: <version>``
69
80
 
70
- * openstack-<service>-api-version: <version>
71
- * openstack-<legacy>-api-version: <version>
72
- * x-openstack-<legacy>-api-version: <version>
81
+ Folded headers are joined by ``,``.
73
82
 
74
- Folded headers are joined by ','.
83
+ :param headers: The headers of a request, dict or list
84
+ :param service_type: The service type being looked for in the headers
85
+ :param legacy_headers: Other headers to look at for a version
86
+ :returns: a version string or "latest"
87
+ :raises: ValueError
75
88
  """
76
89
 
77
90
  folded_headers = fold_headers(headers)
@@ -87,7 +100,9 @@ def get_version(headers, service_type, legacy_headers=None):
87
100
  return None
88
101
 
89
102
 
90
- def check_legacy_headers(headers, legacy_headers):
103
+ def check_legacy_headers(
104
+ headers: MutableMapping[str, str], legacy_headers: Iterable[str]
105
+ ) -> str | None:
91
106
  """Gather values from old headers."""
92
107
  for legacy_header in legacy_headers:
93
108
  try:
@@ -98,7 +113,9 @@ def check_legacy_headers(headers, legacy_headers):
98
113
  return None
99
114
 
100
115
 
101
- def check_standard_header(headers, service_type):
116
+ def check_standard_header(
117
+ headers: MutableMapping[str, str], service_type: str
118
+ ) -> str | None:
102
119
  """Parse the standard header to get value for service."""
103
120
  try:
104
121
  header = _extract_header_value(headers, STANDARD_HEADER)
@@ -112,8 +129,12 @@ def check_standard_header(headers, service_type):
112
129
  except (KeyError, ValueError):
113
130
  return None
114
131
 
132
+ return None
133
+
115
134
 
116
- def fold_headers(headers):
135
+ # we accept Any even though we know this will be a list of 2-item tuples or a
136
+ # dict, in order to avoid reworking logic
137
+ def fold_headers(headers: Any) -> MutableMapping[str, str]:
117
138
  """Turn a list of headers into a folded dict."""
118
139
  # If it behaves like a dict, return it. Webob uses objects which
119
140
  # are not dicts, but behave like them.
@@ -121,6 +142,7 @@ def fold_headers(headers):
121
142
  return dict((k.lower(), v) for k, v in headers.items())
122
143
  except AttributeError:
123
144
  pass
145
+
124
146
  header_dict = collections.defaultdict(list)
125
147
  for header, value in headers:
126
148
  header_dict[header.lower()].append(value.strip())
@@ -132,35 +154,40 @@ def fold_headers(headers):
132
154
  return folded_headers
133
155
 
134
156
 
135
- def headers_from_wsgi_environ(environ):
157
+ def headers_from_wsgi_environ(
158
+ environ: MutableMapping[str, str],
159
+ ) -> dict[str, str]:
136
160
  """Extract all the HTTP_ keys and values from environ to a new dict.
137
161
 
138
- Note that this does not change the keys in any way in the returned
139
- dict. Nor is the incoming environ modified.
162
+ Note that this does not change the keys in any way in the returned dict.
163
+ Nor is the incoming environ modified.
140
164
 
141
165
  :param environ: A PEP 3333 compliant WSGI environ dict.
142
166
  """
143
167
  return {key: environ[key] for key in environ if key.startswith('HTTP_')}
144
168
 
145
169
 
146
- def _extract_header_value(headers, header_name):
170
+ def _extract_header_value(
171
+ headers: MutableMapping[str, str], header_name: str
172
+ ) -> str:
147
173
  """Get the value of a header.
148
174
 
149
- The provided headers is a dict. If a key doesn't exist for
150
- header_name, try using the WSGI environ form of the name.
175
+ The provided headers is a dict. If a key doesn't exist for ``header_name``,
176
+ try using the WSGI environ form of the name.
151
177
 
152
- Raises KeyError if neither key is found.
178
+ :raises: KeyError if neither key is found.
153
179
  """
154
180
  try:
155
181
  value = headers[header_name]
156
182
  except KeyError:
157
183
  wsgi_header_name = ENVIRON_HTTP_HEADER_FMT.format(
158
- header_name.replace('-', '_'))
184
+ header_name.replace('-', '_')
185
+ )
159
186
  value = headers[wsgi_header_name]
160
187
  return value
161
188
 
162
189
 
163
- def parse_version_string(version_string):
190
+ def parse_version_string(version_string: str) -> Version:
164
191
  """Turn a version string into a Version
165
192
 
166
193
  :param version_string: A string of two numerals, X.Y.
@@ -173,28 +200,29 @@ def parse_version_string(version_string):
173
200
  # ValueError, TypeError or AttributeError when the incoming
174
201
  # data is poorly formed but will, however, naturally adapt to
175
202
  # extraneous whitespace.
176
- return Version(*(int(value) for value
177
- in version_string.split('.', 1)))
203
+ return Version(*(int(value) for value in version_string.split('.', 1)))
178
204
  except (ValueError, TypeError, AttributeError) as exc:
179
- raise TypeError('invalid version string: %s; %s' % (
180
- version_string, exc))
205
+ raise TypeError(f'invalid version string: {version_string}; {exc}')
181
206
 
182
207
 
183
- def extract_version(headers, service_type, versions_list):
208
+ def extract_version(
209
+ headers: Iterable[tuple[str, str]] | MutableMapping[str, str],
210
+ service_type: str,
211
+ versions_list: Sequence[str],
212
+ ) -> Version:
184
213
  """Extract the microversion from the headers.
185
214
 
186
- There may be multiple headers and some which don't match our
187
- service.
215
+ There may be multiple headers and some which don't match our service.
188
216
 
189
- If no version is found then the extracted version is the minimum
190
- available version.
217
+ If no version is found then the extracted version is the minimum available
218
+ version.
191
219
 
192
220
  :param headers: Request headers as dict list or WSGI environ
193
- :param service_type: The service_type as a string
221
+ :param service_type: The service type as a string
194
222
  :param versions_list: List of all possible microversions as strings,
195
- sorted from earliest to latest version.
196
- :returns: a Version with the optional min_version and max_version
197
- attributes set.
223
+ sorted from earliest to latest version.
224
+ :returns: a :class:`~Version` with the optional ``min_version`` and
225
+ ``max_version`` attributes set.
198
226
  :raises: ValueError
199
227
  """
200
228
  found_version = get_version(headers, service_type=service_type)
@@ -213,4 +241,4 @@ def extract_version(headers, service_type, versions_list):
213
241
  # to administratively disable a version if we really need to.
214
242
  if str(request_version) in versions_list:
215
243
  return request_version
216
- raise ValueError('Unacceptable version header: %s' % version_string)
244
+ raise ValueError(f'Unacceptable version header: {version_string}')
@@ -10,15 +10,29 @@
10
10
  # implied.
11
11
  # See the License for the specific language governing permissions and
12
12
  # limitations under the License.
13
+
13
14
  """WSGI middleware for getting microversion info."""
14
15
 
16
+ from collections.abc import Sequence
17
+ from typing import Any, Protocol, TYPE_CHECKING
18
+
15
19
  import webob
16
20
  import webob.dec
21
+ import webob.exc
17
22
 
18
23
  import microversion_parse
19
24
 
25
+ if TYPE_CHECKING:
26
+ from _typeshed.wsgi import WSGIApplication
27
+
28
+
29
+ class _JSONFormatter(Protocol):
30
+ def __call__(
31
+ self, *, body: str, status: str, title: str, environ: dict[str, Any]
32
+ ) -> Any: ...
33
+
20
34
 
21
- class MicroversionMiddleware(object):
35
+ class MicroversionMiddleware:
22
36
  """WSGI middleware for getting microversion info.
23
37
 
24
38
  The application will get a WSGI environ with a
@@ -37,8 +51,13 @@ class MicroversionMiddleware(object):
37
51
  Otherwise the application is called.
38
52
  """
39
53
 
40
- def __init__(self, application, service_type, versions,
41
- json_error_formatter=None):
54
+ def __init__(
55
+ self,
56
+ application: 'WSGIApplication | None',
57
+ service_type: str,
58
+ versions: Sequence[str],
59
+ json_error_formatter: _JSONFormatter | None = None,
60
+ ) -> None:
42
61
  """Create the WSGI middleware.
43
62
 
44
63
  :param application: The application hosting the service.
@@ -51,29 +70,35 @@ class MicroversionMiddleware(object):
51
70
  """
52
71
  self.application = application
53
72
  self.service_type = service_type
54
- self.microversion_environ = '%s.microversion' % service_type
73
+ self.microversion_environ = f'{service_type}.microversion'
55
74
  self.versions = versions
56
75
  self.json_error_formatter = json_error_formatter
57
76
 
58
77
  @webob.dec.wsgify
59
- def __call__(self, req):
78
+ def __call__(
79
+ self,
80
+ req: webob.request.Request,
81
+ ) -> webob.response.Response | None:
60
82
  try:
61
83
  microversion = microversion_parse.extract_version(
62
- req.headers, self.service_type, self.versions)
84
+ req.headers, self.service_type, self.versions
85
+ )
63
86
  # TODO(cdent): These error response are not formatted according to
64
87
  # api-sig guidelines, unless a json_error_formatter is provided
65
88
  # that can do it. For an example, see the placement service.
66
89
  except ValueError as exc:
67
90
  raise webob.exc.HTTPNotAcceptable(
68
- ('Invalid microversion: %(error)s') % {'error': exc},
69
- json_formatter=self.json_error_formatter)
91
+ (f'Invalid microversion: {exc}'),
92
+ json_formatter=self.json_error_formatter,
93
+ )
70
94
  except TypeError as exc:
71
95
  raise webob.exc.HTTPBadRequest(
72
- ('Invalid microversion: %(error)s') % {'error': exc},
73
- json_formatter=self.json_error_formatter)
96
+ (f'Invalid microversion: {exc}'),
97
+ json_formatter=self.json_error_formatter,
98
+ )
74
99
 
75
100
  req.environ[self.microversion_environ] = microversion
76
- microversion_header = '%s %s' % (self.service_type, microversion)
101
+ microversion_header = f'{self.service_type} {microversion}'
77
102
  standard_header = microversion_parse.STANDARD_HEADER
78
103
 
79
104
  try:
File without changes
@@ -18,9 +18,8 @@ import microversion_parse
18
18
 
19
19
 
20
20
  class TestVersion(testtools.TestCase):
21
-
22
21
  def setUp(self):
23
- super(TestVersion, self).setUp()
22
+ super().setUp()
24
23
  self.version = microversion_parse.Version(1, 5)
25
24
 
26
25
  def test_version_is_tuple(self):
@@ -69,7 +68,6 @@ class TestVersion(testtools.TestCase):
69
68
 
70
69
 
71
70
  class TestParseVersionString(testtools.TestCase):
72
-
73
71
  def test_good_version(self):
74
72
  version = microversion_parse.parse_version_string('1.1')
75
73
  self.assertEqual((1, 1), version)
@@ -81,57 +79,68 @@ class TestParseVersionString(testtools.TestCase):
81
79
  self.assertEqual(microversion_parse.Version(1, 1), version)
82
80
 
83
81
  def test_non_numeric(self):
84
- self.assertRaises(TypeError,
85
- microversion_parse.parse_version_string,
86
- 'hello')
82
+ self.assertRaises(
83
+ TypeError, microversion_parse.parse_version_string, 'hello'
84
+ )
87
85
 
88
86
  def test_mixed_alphanumeric(self):
89
- self.assertRaises(TypeError,
90
- microversion_parse.parse_version_string,
91
- '1.a')
87
+ self.assertRaises(
88
+ TypeError, microversion_parse.parse_version_string, '1.a'
89
+ )
92
90
 
93
91
  def test_too_many_numeric(self):
94
- self.assertRaises(TypeError,
95
- microversion_parse.parse_version_string,
96
- '1.1.1')
92
+ self.assertRaises(
93
+ TypeError, microversion_parse.parse_version_string, '1.1.1'
94
+ )
97
95
 
98
96
  def test_not_string(self):
99
- self.assertRaises(TypeError,
100
- microversion_parse.parse_version_string,
101
- 1.1)
97
+ self.assertRaises(
98
+ TypeError, microversion_parse.parse_version_string, 1.1
99
+ )
102
100
 
103
101
 
104
102
  class TestExtractVersion(testtools.TestCase):
105
-
106
103
  def setUp(self):
107
- super(TestExtractVersion, self).setUp()
104
+ super().setUp()
108
105
  self.headers = [
109
106
  ('OpenStack-API-Version', 'service1 1.2'),
110
107
  ('OpenStack-API-Version', 'service2 1.5'),
111
108
  ('OpenStack-API-Version', 'service3 latest'),
112
109
  ('OpenStack-API-Version', 'service4 2.5'),
113
110
  ]
114
- self.version_list = ['1.1', '1.2', '1.3', '1.4',
115
- '2.1', '2.2', '2.3', '2.4']
111
+ self.version_list = [
112
+ '1.1',
113
+ '1.2',
114
+ '1.3',
115
+ '1.4',
116
+ '2.1',
117
+ '2.2',
118
+ '2.3',
119
+ '2.4',
120
+ ]
116
121
 
117
122
  def test_simple_extract(self):
118
123
  version = microversion_parse.extract_version(
119
- self.headers, 'service1', self.version_list)
124
+ self.headers, 'service1', self.version_list
125
+ )
120
126
  self.assertEqual((1, 2), version)
121
127
 
122
128
  def test_default_min(self):
123
129
  version = microversion_parse.extract_version(
124
- self.headers, 'notlisted', self.version_list)
130
+ self.headers, 'notlisted', self.version_list
131
+ )
125
132
  self.assertEqual((1, 1), version)
126
133
 
127
134
  def test_latest(self):
128
135
  version = microversion_parse.extract_version(
129
- self.headers, 'service3', self.version_list)
136
+ self.headers, 'service3', self.version_list
137
+ )
130
138
  self.assertEqual((2, 4), version)
131
139
 
132
140
  def test_min_max_extract(self):
133
141
  version = microversion_parse.extract_version(
134
- self.headers, 'service1', self.version_list)
142
+ self.headers, 'service1', self.version_list
143
+ )
135
144
 
136
145
  # below min
137
146
  self.assertFalse(version.matches((1, 3)))
@@ -144,13 +153,24 @@ class TestExtractVersion(testtools.TestCase):
144
153
  # explicit min
145
154
  self.assertFalse(version.matches(min_version=(2, 3)))
146
155
  # explicit both
147
- self.assertTrue(version.matches(min_version=(0, 3),
148
- max_version=(1, 5)))
156
+ self.assertTrue(
157
+ version.matches(min_version=(0, 3), max_version=(1, 5))
158
+ )
149
159
 
150
160
  def test_version_disabled(self):
151
- self.assertRaises(ValueError, microversion_parse.extract_version,
152
- self.headers, 'service2', self.version_list)
161
+ self.assertRaises(
162
+ ValueError,
163
+ microversion_parse.extract_version,
164
+ self.headers,
165
+ 'service2',
166
+ self.version_list,
167
+ )
153
168
 
154
169
  def test_version_out_of_range(self):
155
- self.assertRaises(ValueError, microversion_parse.extract_version,
156
- self.headers, 'service4', self.version_list)
170
+ self.assertRaises(
171
+ ValueError,
172
+ microversion_parse.extract_version,
173
+ self.headers,
174
+ 'service4',
175
+ self.version_list,
176
+ )
@@ -17,7 +17,6 @@ import microversion_parse
17
17
 
18
18
 
19
19
  class TestFoldHeaders(testtools.TestCase):
20
-
21
20
  def test_dict_headers(self):
22
21
  headers = {
23
22
  'header-one': 'alpha',
@@ -39,20 +38,19 @@ class TestFoldHeaders(testtools.TestCase):
39
38
 
40
39
  folded_headers = microversion_parse.fold_headers(headers)
41
40
  self.assertEqual(2, len(folded_headers))
42
- self.assertEqual(set(['header-one', 'header-two']),
43
- set(folded_headers.keys()))
41
+ self.assertEqual(
42
+ set(['header-one', 'header-two']), set(folded_headers.keys())
43
+ )
44
44
  self.assertEqual('alpha,gamma', folded_headers['header-one'])
45
45
 
46
46
  def test_bad_headers(self):
47
47
  headers = 'wow this is not a headers'
48
- self.assertRaises(ValueError, microversion_parse.fold_headers,
49
- headers)
48
+ self.assertRaises(ValueError, microversion_parse.fold_headers, headers)
50
49
 
51
50
  # TODO(cdent): Test with request objects from frameworks.
52
51
 
53
52
 
54
53
  class TestStandardHeader(testtools.TestCase):
55
-
56
54
  def test_simple_match(self):
57
55
  headers = {
58
56
  'header-one': 'alpha',
@@ -88,8 +86,7 @@ class TestStandardHeader(testtools.TestCase):
88
86
  'openstack-api-version': 'network 5.9 ',
89
87
  'header-two': 'beta',
90
88
  }
91
- version = microversion_parse.check_standard_header(
92
- headers, 'compute')
89
+ version = microversion_parse.check_standard_header(headers, 'compute')
93
90
  self.assertEqual(None, version)
94
91
 
95
92
  def test_match_multiple_services(self):
@@ -98,11 +95,11 @@ class TestStandardHeader(testtools.TestCase):
98
95
  'openstack-api-version': 'network 5.9 ,compute 2.1,telemetry 7.8',
99
96
  'header-two': 'beta',
100
97
  }
101
- version = microversion_parse.check_standard_header(
102
- headers, 'compute')
98
+ version = microversion_parse.check_standard_header(headers, 'compute')
103
99
  self.assertEqual('2.1', version)
104
100
  version = microversion_parse.check_standard_header(
105
- headers, 'telemetry')
101
+ headers, 'telemetry'
102
+ )
106
103
  self.assertEqual('7.8', version)
107
104
 
108
105
  def test_match_multiple_same_service(self):
@@ -111,13 +108,11 @@ class TestStandardHeader(testtools.TestCase):
111
108
  'openstack-api-version': 'compute 5.9 ,compute 2.1,compute 7.8',
112
109
  'header-two': 'beta',
113
110
  }
114
- version = microversion_parse.check_standard_header(
115
- headers, 'compute')
111
+ version = microversion_parse.check_standard_header(headers, 'compute')
116
112
  self.assertEqual('7.8', version)
117
113
 
118
114
 
119
115
  class TestLegacyHeaders(testtools.TestCase):
120
-
121
116
  def test_legacy_headers_straight(self):
122
117
  headers = {
123
118
  'header-one': 'alpha',
@@ -125,8 +120,10 @@ class TestLegacyHeaders(testtools.TestCase):
125
120
  'header-two': 'beta',
126
121
  }
127
122
  version = microversion_parse.get_version(
128
- headers, service_type='compute',
129
- legacy_headers=['openstack-CoMpUte-api-version'])
123
+ headers,
124
+ service_type='compute',
125
+ legacy_headers=['openstack-CoMpUte-api-version'],
126
+ )
130
127
  self.assertEqual('2.1', version)
131
128
 
132
129
  def test_legacy_headers_folded(self):
@@ -136,8 +133,10 @@ class TestLegacyHeaders(testtools.TestCase):
136
133
  'header-two': 'beta',
137
134
  }
138
135
  version = microversion_parse.get_version(
139
- headers, service_type='compute',
140
- legacy_headers=['openstack-compute-api-version'])
136
+ headers,
137
+ service_type='compute',
138
+ legacy_headers=['openstack-compute-api-version'],
139
+ )
141
140
  self.assertEqual('9.2', version)
142
141
 
143
142
  def test_older_legacy_headers(self):
@@ -147,9 +146,13 @@ class TestLegacyHeaders(testtools.TestCase):
147
146
  'header-two': 'beta',
148
147
  }
149
148
  version = microversion_parse.get_version(
150
- headers, service_type='compute',
151
- legacy_headers=['openstack-nova-api-version',
152
- 'x-openstack-nova-api-version'])
149
+ headers,
150
+ service_type='compute',
151
+ legacy_headers=[
152
+ 'openstack-nova-api-version',
153
+ 'x-openstack-nova-api-version',
154
+ ],
155
+ )
153
156
  # We don't do x- for service types.
154
157
  self.assertEqual('9.2', version)
155
158
 
@@ -161,19 +164,26 @@ class TestLegacyHeaders(testtools.TestCase):
161
164
  'header-two': 'beta',
162
165
  }
163
166
  version = microversion_parse.get_version(
164
- headers, service_type='compute',
165
- legacy_headers=['openstack-compute-api-version',
166
- 'x-openstack-nova-api-version'])
167
+ headers,
168
+ service_type='compute',
169
+ legacy_headers=[
170
+ 'openstack-compute-api-version',
171
+ 'x-openstack-nova-api-version',
172
+ ],
173
+ )
167
174
  self.assertEqual('3.7', version)
168
175
  version = microversion_parse.get_version(
169
- headers, service_type='compute',
170
- legacy_headers=['x-openstack-nova-api-version',
171
- 'openstack-compute-api-version'])
176
+ headers,
177
+ service_type='compute',
178
+ legacy_headers=[
179
+ 'x-openstack-nova-api-version',
180
+ 'openstack-compute-api-version',
181
+ ],
182
+ )
172
183
  self.assertEqual('9.2', version)
173
184
 
174
185
 
175
186
  class TestGetHeaders(testtools.TestCase):
176
-
177
187
  def test_preference(self):
178
188
  headers = {
179
189
  'header-one': 'alpha',
@@ -183,15 +193,17 @@ class TestGetHeaders(testtools.TestCase):
183
193
  'header-two': 'beta',
184
194
  }
185
195
  version = microversion_parse.get_version(
186
- headers, service_type='compute',
187
- legacy_headers=['openstack-compute-api-version',
188
- 'x-openstack-nova-api-version'])
196
+ headers,
197
+ service_type='compute',
198
+ legacy_headers=[
199
+ 'openstack-compute-api-version',
200
+ 'x-openstack-nova-api-version',
201
+ ],
202
+ )
189
203
  self.assertEqual('11.12', version)
190
204
 
191
205
  def test_no_headers(self):
192
- headers = {}
193
- version = microversion_parse.get_version(
194
- headers, service_type='compute')
206
+ version = microversion_parse.get_version({}, service_type='compute')
195
207
  self.assertEqual(None, version)
196
208
 
197
209
  def test_unfolded_service(self):
@@ -202,7 +214,8 @@ class TestGetHeaders(testtools.TestCase):
202
214
  ('openstack-api-version', '3.0'),
203
215
  ]
204
216
  version = microversion_parse.get_version(
205
- headers, service_type='compute')
217
+ headers, service_type='compute'
218
+ )
206
219
  self.assertEqual('2.0', version)
207
220
 
208
221
  def test_unfolded_in_name(self):
@@ -213,15 +226,17 @@ class TestGetHeaders(testtools.TestCase):
213
226
  ('openstack-telemetry-api-version', '3.0'),
214
227
  ]
215
228
  version = microversion_parse.get_version(
216
- headers, service_type='compute',
217
- legacy_headers=['x-openstack-nova-api-version'])
229
+ headers,
230
+ service_type='compute',
231
+ legacy_headers=['x-openstack-nova-api-version'],
232
+ )
218
233
  self.assertEqual('2.0', version)
219
234
 
220
235
  def test_capitalized_headers(self):
221
- headers = {
222
- 'X-Openstack-Ironic-Api-Version': '123.456'
223
- }
236
+ headers = {'X-Openstack-Ironic-Api-Version': '123.456'}
224
237
  version = microversion_parse.get_version(
225
- headers, service_type='ironic',
226
- legacy_headers=['X-Openstack-Ironic-Api-Version'])
238
+ headers,
239
+ service_type='ironic',
240
+ legacy_headers=['X-Openstack-Ironic-Api-Version'],
241
+ )
227
242
  self.assertEqual('123.456', version)
@@ -17,45 +17,50 @@ import microversion_parse
17
17
 
18
18
 
19
19
  class TestHeadersFromWSGIEnviron(testtools.TestCase):
20
-
21
20
  def test_empty_environ(self):
22
- environ = {}
23
- expected = {}
24
- self.assertEqual(
25
- expected,
26
- microversion_parse.headers_from_wsgi_environ(environ))
21
+ self.assertEqual({}, microversion_parse.headers_from_wsgi_environ({}))
27
22
 
28
23
  def test_non_empty_no_headers(self):
29
24
  environ = {'PATH_INFO': '/foo/bar'}
30
- expected = {}
31
- found_headers = microversion_parse.headers_from_wsgi_environ(environ)
32
- self.assertEqual(expected, found_headers)
25
+ self.assertEqual(
26
+ {}, microversion_parse.headers_from_wsgi_environ(environ)
27
+ )
33
28
 
34
29
  def test_headers(self):
35
- environ = {'PATH_INFO': '/foo/bar',
36
- 'HTTP_OPENSTACK_API_VERSION': 'placement 2.1',
37
- 'HTTP_CONTENT_TYPE': 'application/json'}
38
- expected = {'HTTP_OPENSTACK_API_VERSION': 'placement 2.1',
39
- 'HTTP_CONTENT_TYPE': 'application/json'}
30
+ environ = {
31
+ 'PATH_INFO': '/foo/bar',
32
+ 'HTTP_OPENSTACK_API_VERSION': 'placement 2.1',
33
+ 'HTTP_CONTENT_TYPE': 'application/json',
34
+ }
35
+ expected = {
36
+ 'HTTP_OPENSTACK_API_VERSION': 'placement 2.1',
37
+ 'HTTP_CONTENT_TYPE': 'application/json',
38
+ }
40
39
  found_headers = microversion_parse.headers_from_wsgi_environ(environ)
41
40
  self.assertEqual(expected, found_headers)
42
41
 
43
42
  def test_get_version_from_environ(self):
44
- environ = {'PATH_INFO': '/foo/bar',
45
- 'HTTP_OPENSTACK_API_VERSION': 'placement 2.1',
46
- 'HTTP_CONTENT_TYPE': 'application/json'}
43
+ environ = {
44
+ 'PATH_INFO': '/foo/bar',
45
+ 'HTTP_OPENSTACK_API_VERSION': 'placement 2.1',
46
+ 'HTTP_CONTENT_TYPE': 'application/json',
47
+ }
47
48
  expected_version = '2.1'
48
49
  headers = microversion_parse.headers_from_wsgi_environ(environ)
49
50
  version = microversion_parse.get_version(headers, 'placement')
50
51
  self.assertEqual(expected_version, version)
51
52
 
52
53
  def test_get_version_from_environ_legacy(self):
53
- environ = {'PATH_INFO': '/foo/bar',
54
- 'HTTP_X_OPENSTACK_PLACEMENT_API_VERSION': '2.1',
55
- 'HTTP_CONTENT_TYPE': 'application/json'}
54
+ environ = {
55
+ 'PATH_INFO': '/foo/bar',
56
+ 'HTTP_X_OPENSTACK_PLACEMENT_API_VERSION': '2.1',
57
+ 'HTTP_CONTENT_TYPE': 'application/json',
58
+ }
56
59
  expected_version = '2.1'
57
60
  headers = microversion_parse.headers_from_wsgi_environ(environ)
58
61
  version = microversion_parse.get_version(
59
- headers, 'placement',
60
- legacy_headers=['x-openstack-placement-api-version'])
62
+ headers,
63
+ 'placement',
64
+ legacy_headers=['x-openstack-placement-api-version'],
65
+ )
61
66
  self.assertEqual(expected_version, version)
@@ -32,7 +32,7 @@ VERSIONS = [
32
32
  ]
33
33
 
34
34
 
35
- class SimpleWSGI(object):
35
+ class SimpleWSGI:
36
36
  """A WSGI application that can be contiained within a middlware."""
37
37
 
38
38
  def __call__(self, environ, start_response):
@@ -41,12 +41,13 @@ class SimpleWSGI(object):
41
41
  start_response('200 OK', [('content-type', 'text/plain')])
42
42
  return [b'good']
43
43
 
44
- raise webob.exc.HTTPNotFound('%s not found' % path_info)
44
+ raise webob.exc.HTTPNotFound(f'{path_info} not found')
45
45
 
46
46
 
47
47
  def app():
48
48
  app = middleware.MicroversionMiddleware(
49
- SimpleWSGI(), SERVICE_TYPE, VERSIONS)
49
+ SimpleWSGI(), SERVICE_TYPE, VERSIONS
50
+ )
50
51
  return app
51
52
 
52
53
 
@@ -54,4 +55,5 @@ def load_tests(loader, tests, pattern):
54
55
  """Provide a TestSuite to the discovery process."""
55
56
  test_dir = os.path.join(os.path.dirname(__file__), TESTS_DIR)
56
57
  return driver.build_tests(
57
- test_dir, loader, test_loader_name=__name__, intercept=app)
58
+ test_dir, loader, test_loader_name=__name__, intercept=app
59
+ )
@@ -22,59 +22,74 @@ class TestWebobHeaders(testtools.TestCase):
22
22
  """Webob uses a dict-like header which is not actually a dict."""
23
23
 
24
24
  def test_simple_headers(self):
25
- headers = wb_headers.EnvironHeaders({
26
- 'HTTP_HEADER_ONE': 'alpha',
27
- 'HTTP_HEADER_TWO': 'beta',
28
- 'HTTP_HEADER_THREE': 'gamma',
29
- })
25
+ headers = wb_headers.EnvironHeaders(
26
+ {
27
+ 'HTTP_HEADER_ONE': 'alpha',
28
+ 'HTTP_HEADER_TWO': 'beta',
29
+ 'HTTP_HEADER_THREE': 'gamma',
30
+ }
31
+ )
30
32
 
31
33
  folded_headers = microversion_parse.fold_headers(headers)
32
34
  self.assertEqual(3, len(folded_headers))
33
- self.assertEqual(set(['header-one', 'header-three', 'header-two']),
34
- set(folded_headers.keys()))
35
+ self.assertEqual(
36
+ set(['header-one', 'header-three', 'header-two']),
37
+ set(folded_headers.keys()),
38
+ )
35
39
  self.assertEqual('gamma', folded_headers['header-three'])
36
40
 
37
41
  def test_simple_match(self):
38
- headers = wb_headers.EnvironHeaders({
39
- 'HTTP_HEADER_ONE': 'alpha',
40
- 'HTTP_OPENSTACK_API_VERSION': 'compute 2.1',
41
- 'HTTP_HEADER_TWO': 'beta',
42
- })
42
+ headers = wb_headers.EnvironHeaders(
43
+ {
44
+ 'HTTP_HEADER_ONE': 'alpha',
45
+ 'HTTP_OPENSTACK_API_VERSION': 'compute 2.1',
46
+ 'HTTP_HEADER_TWO': 'beta',
47
+ }
48
+ )
43
49
  version = microversion_parse.check_standard_header(headers, 'compute')
44
50
  self.assertEqual('2.1', version)
45
51
 
46
52
  def test_match_multiple_services(self):
47
- headers = wb_headers.EnvironHeaders({
48
- 'HTTP_HEADER_ONE': 'alpha',
49
- 'HTTP_OPENSTACK_API_VERSION':
50
- 'network 5.9 ,compute 2.1,telemetry 7.8',
51
- 'HTTP_HEADER_TWO': 'beta',
52
- })
53
- version = microversion_parse.check_standard_header(
54
- headers, 'compute')
53
+ headers = wb_headers.EnvironHeaders(
54
+ {
55
+ 'HTTP_HEADER_ONE': 'alpha',
56
+ 'HTTP_OPENSTACK_API_VERSION': 'network 5.9 ,compute 2.1,telemetry 7.8', # noqa: E501
57
+ 'HTTP_HEADER_TWO': 'beta',
58
+ }
59
+ )
60
+ version = microversion_parse.check_standard_header(headers, 'compute')
55
61
  self.assertEqual('2.1', version)
56
62
  version = microversion_parse.check_standard_header(
57
- headers, 'telemetry')
63
+ headers, 'telemetry'
64
+ )
58
65
  self.assertEqual('7.8', version)
59
66
 
60
67
  def test_legacy_headers_straight(self):
61
- headers = wb_headers.EnvironHeaders({
62
- 'HTTP_HEADER_ONE': 'alpha',
63
- 'HTTP_X_OPENSTACK_NOVA_API_VERSION': ' 2.1 ',
64
- 'HTTP_HEADER_TWO': 'beta',
65
- })
68
+ headers = wb_headers.EnvironHeaders(
69
+ {
70
+ 'HTTP_HEADER_ONE': 'alpha',
71
+ 'HTTP_X_OPENSTACK_NOVA_API_VERSION': ' 2.1 ',
72
+ 'HTTP_HEADER_TWO': 'beta',
73
+ }
74
+ )
66
75
  version = microversion_parse.get_version(
67
- headers, service_type='compute',
68
- legacy_headers=['x-openstack-nova-api-version'])
76
+ headers,
77
+ service_type='compute',
78
+ legacy_headers=['x-openstack-nova-api-version'],
79
+ )
69
80
  self.assertEqual('2.1', version)
70
81
 
71
82
  def test_legacy_headers_folded(self):
72
- headers = wb_headers.EnvironHeaders({
73
- 'HTTP_HEADER_ONE': 'alpha',
74
- 'HTTP_X_OPENSTACK_NOVA_API_VERSION': ' 2.1, 9.2 ',
75
- 'HTTP_HEADER_TWO': 'beta',
76
- })
83
+ headers = wb_headers.EnvironHeaders(
84
+ {
85
+ 'HTTP_HEADER_ONE': 'alpha',
86
+ 'HTTP_X_OPENSTACK_NOVA_API_VERSION': ' 2.1, 9.2 ',
87
+ 'HTTP_HEADER_TWO': 'beta',
88
+ }
89
+ )
77
90
  version = microversion_parse.get_version(
78
- headers, service_type='compute',
79
- legacy_headers=['x-openstack-nova-api-version'])
91
+ headers,
92
+ service_type='compute',
93
+ legacy_headers=['x-openstack-nova-api-version'],
94
+ )
80
95
  self.assertEqual('9.2', version)
@@ -1,9 +1,16 @@
1
1
  Andreas Jaeger <aj@suse.com>
2
2
  Chris Dent <cdent@anticdent.org>
3
3
  Chris Dent <chris.dent@gmail.com>
4
+ Daniel Bengtsson <dbengt@redhat.com>
5
+ Ghanshyam <gmann@ghanshyammann.com>
4
6
  Hervé Beraud <hberaud@redhat.com>
5
7
  Louis Taylor <louis@kragniz.eu>
6
8
  Moisés Guimarães de Medeiros <moguimar@redhat.com>
7
9
  PollyZ <Polly.Zhou@rackspace.com>
10
+ Stephen Finucane <stephenfin@redhat.com>
11
+ Takashi Kajinami <kajinamit@oss.nttdata.com>
12
+ Takashi Kajinami <tkajinam@redhat.com>
8
13
  Vieri <15050873171@163.com>
9
14
  huang.zhiping <huang.zhiping@99cloud.net>
15
+ niuke <niuke19970315@163.com>
16
+ niuke <niuke@inspur.com>
@@ -1,24 +1,26 @@
1
1
  Metadata-Version: 2.1
2
- Name: microversion-parse
3
- Version: 1.0.1
2
+ Name: microversion_parse
3
+ Version: 2.1.0
4
4
  Summary: OpenStack microversion header parser
5
- Home-page: http://www.openstack.org/
6
- Author: OpenStack
7
- Author-email: openstack-discuss@lists.openstack.org
8
- License: UNKNOWN
9
- Platform: UNKNOWN
5
+ Author-email: OpenStack <openstack-discuss@lists.openstack.org>
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://opendev.org/openstack/microversion-parse
10
8
  Classifier: Environment :: OpenStack
11
9
  Classifier: Intended Audience :: Information Technology
10
+ Classifier: Intended Audience :: System Administrators
12
11
  Classifier: License :: OSI Approved :: Apache Software License
13
12
  Classifier: Operating System :: POSIX :: Linux
14
13
  Classifier: Programming Language :: Python
15
14
  Classifier: Programming Language :: Python :: 3
16
- Classifier: Programming Language :: Python :: 3.6
17
- Classifier: Programming Language :: Python :: 3.7
18
- Classifier: Programming Language :: Python :: 3 :: Only
19
- Classifier: Programming Language :: Python :: Implementation :: CPython
20
- Requires-Python: >=3.6
21
- Requires-Dist: WebOb (>=1.2.3)
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/x-rst
21
+ License-File: LICENSE
22
+ License-File: AUTHORS
23
+ Requires-Dist: WebOb >=1.2.3
22
24
 
23
25
  microversion_parse
24
26
  ==================
@@ -141,6 +143,3 @@ For example::
141
143
 
142
144
 
143
145
  .. _microversion: http://specs.openstack.org/openstack/api-wg/guidelines/microversion_specification.html
144
-
145
-
146
-
@@ -0,0 +1,18 @@
1
+ microversion_parse/__init__.py,sha256=Z6nytE7QxZ0_4itRx1okXixFEjTy__wVwBjkVymM0oQ,8420
2
+ microversion_parse/middleware.py,sha256=Yexfs92qU6h65J8VltzW4R7XWOljvJ5o4_s9ZSlHsVA,4186
3
+ microversion_parse/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ microversion_parse/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ microversion_parse/tests/test_extract_version.py,sha256=Iq4Qt6nRNBtVpvUagNztBsyuCPhne0MrBjyfQ5p5x3E,5646
6
+ microversion_parse/tests/test_get_version.py,sha256=Y2kXLpC9__YKKf99P2kr0Kf46EmUkCk3HcA-8g6FziQ,8294
7
+ microversion_parse/tests/test_headers_from_wsgi_environ.py,sha256=3MWht2zsjsVNEGO_v8OHJrs269DL0VvDoyOHTziSVCA,2446
8
+ microversion_parse/tests/test_middleware.py,sha256=td-uKPzMUsdFB5UKlKmlGwHF9YSmT1CZ2Pu2th-BRHU,1753
9
+ microversion_parse/tests/test_webob.py,sha256=Z1lmgxWIV_MQf22zbAoT8BCW959ig0fkj_pCOD0PMzo,3281
10
+ microversion_parse/tests/gabbits/middleware.yaml,sha256=6o107QtCqV6znRRxikL4v2szYkGcrUSJw6fuFZJnY6g,1766
11
+ microversion_parse/tests/gabbits/simple.yaml,sha256=oc08Zvm7yHZUYEpF765j3GXxyySbOWfXdIyZCGT66Rg,210
12
+ microversion_parse-2.1.0.dist-info/AUTHORS,sha256=W9ay9PlIfZxhS9VD3C5NcVfca4_2Cws7HqI9Ah-N7pw,573
13
+ microversion_parse-2.1.0.dist-info/LICENSE,sha256=tAkwu8-AdEyGxGoSvJ2gVmQdcicWw3j1ZZueVV74M-E,11357
14
+ microversion_parse-2.1.0.dist-info/METADATA,sha256=juo4E-zy_I7wmnlAqNpG4w8A_kDwaWsuUvnMbOt7Lv8,5084
15
+ microversion_parse-2.1.0.dist-info/WHEEL,sha256=iAkIy5fosb7FzIOwONchHf19Qu7_1wCWyFNR5gu9nU0,91
16
+ microversion_parse-2.1.0.dist-info/pbr.json,sha256=K3JMRKpH9T5sIWs2SJ-gsxU-DylPK11Sie5J9_AB29o,46
17
+ microversion_parse-2.1.0.dist-info/top_level.txt,sha256=KS1nxGD4tgRyCDIAxcWf7h8y7vuwQpw59ys-8jChuQ4,19
18
+ microversion_parse-2.1.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: bdist_wheel (0.34.2)
2
+ Generator: setuptools (75.3.2)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -0,0 +1 @@
1
+ {"git_version": "77ea32a", "is_release": true}
@@ -1,17 +0,0 @@
1
- microversion_parse/__init__.py,sha256=vcAnFDgxrPqKFf70XVFuMdtAYI9ebUPVEyGm12qCvbc,7521
2
- microversion_parse/middleware.py,sha256=GqIcF8UjaMbiiqdO-bNDUUTk6UOKKfxyWUH42np0sJY,3695
3
- microversion_parse/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
- microversion_parse/tests/test_extract_version.py,sha256=Yo-9hqxu5_1bKWBd9Ia5I47y-5MpxsMuuGIcBQld_lI,5624
5
- microversion_parse/tests/test_get_version.py,sha256=8FjjeNQC59lMhKzebvXAiFSAgoxHzgvGVg5ENBbthLQ,8157
6
- microversion_parse/tests/test_headers_from_wsgi_environ.py,sha256=cpgxG_iF8NeqtwuN8yunEcuah3dnvv-b2QpFw6Pdlx4,2506
7
- microversion_parse/tests/test_middleware.py,sha256=yeIGPYfkRsXcWToadiAM3SRyDJOpU6aynnhljRjpkRU,1757
8
- microversion_parse/tests/test_webob.py,sha256=Jvep4qBXKRNS27akLjqbt1Y2ATJ9tQud137mx1MQKSs,3039
9
- microversion_parse/tests/gabbits/middleware.yaml,sha256=6o107QtCqV6znRRxikL4v2szYkGcrUSJw6fuFZJnY6g,1766
10
- microversion_parse/tests/gabbits/simple.yaml,sha256=oc08Zvm7yHZUYEpF765j3GXxyySbOWfXdIyZCGT66Rg,210
11
- microversion_parse-1.0.1.dist-info/AUTHORS,sha256=-USkF6ouCBkNC6yroRNO5oqA-UuMhE9h-PxCSsMIT5U,320
12
- microversion_parse-1.0.1.dist-info/LICENSE,sha256=tAkwu8-AdEyGxGoSvJ2gVmQdcicWw3j1ZZueVV74M-E,11357
13
- microversion_parse-1.0.1.dist-info/METADATA,sha256=M5bceRT69vOb88YfCN4WKp8cDEBCn8ABY3q3Qrk3S-Q,4960
14
- microversion_parse-1.0.1.dist-info/WHEEL,sha256=g4nMs7d-Xl9-xC9XovUrsDHGXt-FT0E17Yqo92DEfvY,92
15
- microversion_parse-1.0.1.dist-info/pbr.json,sha256=Fm7TAYCXbgb81DZkVcVpO2Hc5VqbtfFmXfQAu7d3jJQ,46
16
- microversion_parse-1.0.1.dist-info/top_level.txt,sha256=KS1nxGD4tgRyCDIAxcWf7h8y7vuwQpw59ys-8jChuQ4,19
17
- microversion_parse-1.0.1.dist-info/RECORD,,
@@ -1 +0,0 @@
1
- {"git_version": "2c36df6", "is_release": true}