File: test_useragent.py

package info (click to toggle)
python-botocore 1.37.9%2Brepack-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 121,768 kB
  • sloc: python: 73,696; xml: 14,880; javascript: 181; makefile: 155
file content (254 lines) | stat: -rw-r--r-- 8,265 bytes parent folder | download
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import logging
import platform

import pytest

import botocore.useragent
from botocore import __version__ as botocore_version
from botocore.config import Config
from botocore.context import get_context
from botocore.useragent import (
    UserAgentComponent,
    UserAgentComponentSizeConfig,
    UserAgentString,
    register_feature_id,
    sanitize_user_agent_string_component,
)
from tests import mock

from .. import requires_crt


# Returns a list of unmodified User-Agent components.
def unmodified_components(components):
    return components


@pytest.mark.parametrize(
    'raw_str, allow_hash, expected_str',
    [
        ('foo', False, 'foo'),
        ('foo', True, 'foo'),
        ('ExampleFramework (1.2.3)', False, 'ExampleFramework--1.2.3-'),
        ('foo#1.2.3', False, 'foo-1.2.3'),
        ('foo#1.2.3', True, 'foo#1.2.3'),
        ('', False, ''),
        ('', True, ''),
        ('', False, ''),
        ('#', False, '-'),
        ('#', True, '#'),
        (' ', False, '-'),
        ('  ', False, '--'),
        ('@=[]{ }/\\øß©', True, '------------'),
        (
            'Java_HotSpot_(TM)_64-Bit_Server_VM/25.151-b12',
            True,
            'Java_HotSpot_-TM-_64-Bit_Server_VM-25.151-b12',
        ),
    ],
)
def test_sanitize_ua_string_component(raw_str, allow_hash, expected_str):
    actual_str = sanitize_user_agent_string_component(raw_str, allow_hash)
    assert actual_str == expected_str


@mock.patch.object(
    botocore.useragent, 'modify_components', unmodified_components
)
def test_basic_user_agent_string():
    ua = UserAgentString(
        platform_name='linux',
        platform_version='1.2.3-foo',
        platform_machine='x86_64',
        python_version='3.8.20',
        python_implementation='Dpython',
        execution_env='AWS_Lambda_python3.8',
        crt_version='Unknown',
    ).with_client_config(
        Config(retries={'mode': 'legacy'}, user_agent_appid='fooapp')
    )

    actual = ua.to_string()
    expected = (
        f'Botocore/{botocore_version} '
        'md/awscrt#Unknown '
        'ua/2.1 '
        'os/linux#1.2.3-foo '
        'md/arch#x86_64 '
        'lang/python#3.8.20 '
        'md/pyimpl#Dpython '
        'exec-env/AWS_Lambda_python3.8 '
        'cfg/retry-mode#legacy '
        'app/fooapp'
    )
    assert actual == expected


def test_shared_test_case():
    # This test case is shared across AWS SDKs.

    uas = UserAgentString(
        platform_name="Linux",
        platform_version="5.4.228-131.415.AMZN2.X86_64",
        platform_machine="",
        python_version="4.3.2",
        python_implementation=None,
        execution_env='lambda',
    ).with_client_config(
        Config(user_agent_appid='123456', retries={'mode': 'standard'})
    )
    actual = uas.to_string().split(' ')
    expected_in_exact_order = [
        f"Botocore/{botocore_version}",
        "ua/2.1",
        "os/linux#5.4.228-131.415.AMZN2.X86_64",
        "lang/python#4.3.2",
        "exec-env/lambda",
    ]
    expected_in_any_order = [
        "cfg/retry-mode#standard",
        "app/123456",
    ]
    for el in [*expected_in_exact_order, *expected_in_any_order]:
        assert el in actual

    indices = [actual.index(el) for el in expected_in_exact_order]
    assert indices == list(sorted(indices)), 'Elements were found out of order'


@mock.patch.object(
    botocore.useragent, 'modify_components', unmodified_components
)
def test_user_agent_string_with_missing_information():
    # Even when collecting information from the environment fails completely,
    # some minimal string should be generated.
    uas = UserAgentString(
        platform_name=None,
        platform_version=None,
        platform_machine=None,
        python_version=None,
        python_implementation=None,
        execution_env=None,
        crt_version=None,
    ).with_client_config(Config())
    actual = uas.to_string()
    assert actual == f'Botocore/{botocore_version} ua/2.1 os/other lang/python'


def test_from_environment(monkeypatch):
    monkeypatch.setenv('AWS_EXECUTION_ENV', 'lambda')
    monkeypatch.setattr(platform, 'system', lambda: 'Linux')
    monkeypatch.setattr(
        platform, 'release', lambda: '5.4.228-131.415.AMZN2.X86_64'
    )
    monkeypatch.setattr(platform, 'python_version', lambda: '4.3.2')
    monkeypatch.setattr(platform, 'python_implementation', lambda: 'CPython')

    uas = UserAgentString.from_environment()

    assert uas._execution_env == 'lambda'
    assert uas._platform_name == 'Linux'
    assert uas._platform_version == '5.4.228-131.415.AMZN2.X86_64'
    assert uas._python_version == '4.3.2'
    assert uas._python_implementation == 'CPython'


@requires_crt()
def test_from_environment_can_read_crt_version(monkeypatch):
    import awscrt

    monkeypatch.setattr(awscrt, '__version__', 'a.b.c')
    uas = UserAgentString.from_environment()
    assert uas._crt_version == 'a.b.c'


def test_from_environment_with_most_values_not_available(monkeypatch):
    # Asserts that ``None`` values are properly passed through to the
    # UserAgentString class. There are separate tests to assert that
    # ``UserAgentString.to_string()`` can handle ``None`` values.
    monkeypatch.delenv('AWS_EXECUTION_ENV', raising=False)
    monkeypatch.setattr(platform, 'system', lambda: None)
    monkeypatch.setattr(platform, 'release', lambda: None)
    monkeypatch.setattr(platform, 'python_version', lambda: None)
    monkeypatch.setattr(platform, 'python_implementation', lambda: None)

    uas = UserAgentString.from_environment()

    assert uas._execution_env is None
    assert uas._platform_name is None
    assert uas._platform_version is None
    assert uas._python_version is None
    assert uas._python_implementation is None


def test_from_environment_unknown_platform(monkeypatch):
    monkeypatch.setattr(platform, 'system', lambda: 'FooOS')
    monkeypatch.setattr(platform, 'release', lambda: '0.0.1')
    uas = UserAgentString.from_environment()
    assert ' os/other md/FooOS#0.0.1 ' in uas.to_string()


def test_user_agent_string_with_registered_features(client_context):
    uas = UserAgentString.from_environment()
    uas.set_client_features({'A'})
    register_feature_id('WAITER')

    uafields = uas.to_string().split(' ')
    feature_field = [field for field in uafields if field.startswith('m/')][0]
    feature_list = feature_field[2:].split(',')
    assert sorted(feature_list) == ['A', 'B']


def test_register_feature_id(client_context):
    register_feature_id('WAITER')
    ctx = get_context()
    assert ctx.features == {'B'}


def test_register_unknown_feature_id_skips(client_context):
    register_feature_id('MY_FEATURE')
    ctx = get_context()
    assert ctx.features == set()


def test_user_agent_truncated_string():
    size_config = UserAgentComponentSizeConfig(4, ',')
    component = UserAgentComponent(
        'm',
        'A,BCD',
        size_config=size_config,
    )
    assert component.to_string() == 'm/A'


def test_user_agent_empty_truncated_string_logs(caplog):
    caplog.set_level(logging.DEBUG)
    size_config = UserAgentComponentSizeConfig(1, ',')
    component = UserAgentComponent(
        'm',
        'A,B,C',
        size_config=size_config,
    )
    assert component.to_string() == ''
    assert 'could not be truncated' in caplog.text


def test_non_positive_user_agent_component_size_config_raises():
    with pytest.raises(ValueError) as excinfo:
        UserAgentComponentSizeConfig(0, ',')
    assert 'Invalid `max_size_in_bytes`' in str(excinfo.value)
    with pytest.raises(ValueError) as excinfo:
        UserAgentComponentSizeConfig(-1, ',')
    assert 'Invalid `max_size_in_bytes`' in str(excinfo.value)