Skip to content

Commit ea8750f

Browse files
authored
Merge pull request #5 from KieranBrantnerMagee/kibrantn/servicebus/track2-control-client-queue-create-tests
Initial commit of queue creation tests
2 parents 5674fa5 + 75d8d23 commit ea8750f

File tree

2 files changed

+138
-21
lines changed

2 files changed

+138
-21
lines changed

sdk/servicebus/azure-servicebus/azure/servicebus/management/_management_client.py

+26-21
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from azure.core.pipeline.transport import RequestsTransport
1515
from azure.servicebus import ServiceBusSharedKeyCredential
1616
from msrest.serialization import Model
17+
from msrest.exceptions import ValidationError
1718

1819
from .._common.constants import JWT_TOKEN_SCOPE
1920
from .._common.utils import parse_conn_str
@@ -44,13 +45,13 @@ def _handle_response_error():
4445
raise new_response_error
4546

4647

47-
def _convert_xml_to_object(queue_name, et, clazz):
48+
def _convert_xml_to_object(queue_name, et, class_):
4849
# type: (str, Union[Element, ElementTree], Type[Model]) -> Union[QueueDescription, QueueRuntimeInfo]
4950
content_ele = cast(ElementTree, et).find(constants.CONTENT_TAG)
5051
if not content_ele:
5152
raise ResourceNotFoundError("Queue '{}' does not exist".format(queue_name))
5253
qc_ele = content_ele.find(constants.QUEUE_DESCRIPTION_TAG)
53-
obj = clazz.deserialize(qc_ele)
54+
obj = class_.deserialize(qc_ele)
5455
obj.queue_name = queue_name
5556
return obj
5657

@@ -116,7 +117,7 @@ def from_connection_string(cls, connection_string, **kwargs):
116117
endpoint = endpoint[endpoint.index("//")+2:]
117118
return cls(endpoint, ServiceBusSharedKeyCredential(shared_access_key_name, shared_access_key))
118119

119-
def _get_queue_object(self, queue_name, clazz):
120+
def _get_queue_object(self, queue_name, class_):
120121
# type: (str, Type[Model]) -> Union[QueueDescription, QueueRuntimeInfo]
121122

122123
if not queue_name:
@@ -127,10 +128,10 @@ def _get_queue_object(self, queue_name, clazz):
127128
ElementTree,
128129
self._impl.queue.get(queue_name, enrich=False, api_version=constants.API_VERSION)
129130
)
130-
return _convert_xml_to_object(queue_name, et, clazz)
131+
return _convert_xml_to_object(queue_name, et, class_)
131132

132-
def _list_queues(self, skip, max_count, clazz):
133-
# type: (int, int, Type[Model]) -> Union[List[QueueDescription], List[QueueRuntimeInfo]]
133+
def _list_queues(self, skip, max_count, class_):
134+
# type: (int, int, Type[Model]) -> Union[List[QueueDescription], List[QueueRuntimeInfo])
134135
with _handle_response_error():
135136
et = cast(
136137
ElementTree,
@@ -145,7 +146,7 @@ def _list_queues(self, skip, max_count, clazz):
145146
queue_description = _convert_xml_to_object(
146147
entity_name, # type: ignore
147148
cast(Element, entry),
148-
clazz
149+
class_
149150
)
150151
queues.append(queue_description)
151152
return queues
@@ -169,36 +170,40 @@ def get_queue_runtime_info(self, queue_name):
169170
def create_queue(self, queue):
170171
# type: (Union[str, QueueDescription]) -> QueueDescription
171172
"""Create a queue
172-
173+
173174
:param queue: The queue name or a `QueueDescription` instance. When it's a str, it will be the name
174175
of the created queue. Other properties of the created queue will have default values decided by the
175176
ServiceBus. Use a `QueueDesceiption` if you want to set queue properties other than the queue name.
176177
:type queue: Union[str, QueueDescription].
177178
:returns: `QueueDescription` returned from ServiceBus.
178179
"""
179-
180-
try: # queue is a QueueDescription
181-
queue_name = queue.queue_name
180+
queue_name = None
181+
try:
182+
queue_name = queue.queue_name # type: ignore
182183
to_create = copy(queue)
183-
to_create.queue_name = None
184-
except AttributeError: # str expected. But if not str, it might work and might not work.
184+
to_create.queue_name = None
185+
except AttributeError:
185186
queue_name = queue
186-
to_create = QueueDescription()
187-
if queue_name is None:
188-
raise ValueError("queue should be a non-empty str or a QueueDescription with non-empty queue_name")
187+
to_create = QueueDescription() # Use an empty queue description.
189188

190189
create_entity_body = CreateQueueBody(
191190
content=CreateQueueBodyContent(
192191
queue_description=to_create,
193192
)
194193
)
195194
request_body = create_entity_body.serialize(is_xml=True)
195+
try:
196+
with _handle_response_error():
197+
et = cast(
198+
ElementTree,
199+
self._impl.queue.put(queue_name, request_body, api_version=constants.API_VERSION)
200+
)
201+
except ValidationError as e:
202+
# post-hoc try to give a somewhat-justifiable failure reason.
203+
if isinstance(queue, str) or (isinstance(queue, QueueDescription) and isinstance(queue.queue_name, str)):
204+
raise ValueError("queue must be a non-empty str or a QueueDescription with non-empty str queue_name", e)
205+
raise TypeError("queue must be a non-empty str or a QueueDescription with non-empty str queue_name", e)
196206

197-
with _handle_response_error():
198-
et = cast(
199-
ElementTree,
200-
self._impl.queue.put(queue_name, request_body, api_version=constants.API_VERSION)
201-
)
202207
return _convert_xml_to_object(queue_name, et, QueueDescription)
203208

204209
def update_queue(self, queue_description):
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
#-------------------------------------------------------------------------
2+
# Copyright (c) Microsoft Corporation. All rights reserved.
3+
# Licensed under the MIT License. See License.txt in the project root for
4+
# license information.
5+
#--------------------------------------------------------------------------
6+
7+
import logging
8+
import pytest
9+
import uuid
10+
import datetime
11+
12+
from azure.servicebus.management import ServiceBusManagementClient, QueueDescription
13+
from azure.servicebus._common.utils import utc_now
14+
from azure.core.exceptions import ResourceExistsError
15+
16+
from devtools_testutils import AzureMgmtTestCase, CachedResourceGroupPreparer
17+
from servicebus_preparer import CachedServiceBusNamespacePreparer, ServiceBusQueuePreparer, CachedServiceBusQueuePreparer
18+
from utilities import get_logger
19+
20+
_logger = get_logger(logging.DEBUG)
21+
22+
class ServiceBusMgmtQueueTests(AzureMgmtTestCase):
23+
24+
@pytest.mark.liveTest
25+
@CachedResourceGroupPreparer(name_prefix='servicebustest')
26+
@CachedServiceBusNamespacePreparer(name_prefix='servicebustest')
27+
def test_mgmt_queue_create_by_name(self, servicebus_namespace_connection_string, **kwargs):
28+
mgmt_service = ServiceBusManagementClient.from_connection_string(servicebus_namespace_connection_string)
29+
30+
queue_name = str(uuid.uuid4())
31+
created_at = utc_now()
32+
mgmt_service.create_queue(queue_name)
33+
34+
queue = mgmt_service.get_queue(queue_name)
35+
assert queue.queue_name == queue_name
36+
assert queue.entity_availability_status == 'Available'
37+
assert queue.status == 'Available'
38+
assert created_at < queue.created_at < utc_now() + datetime.timedelta(minutes=10) # TODO: Should be created_at_utc for consistency with dataplane.
39+
40+
@pytest.mark.liveTest
41+
@CachedResourceGroupPreparer(name_prefix='servicebustest')
42+
@CachedServiceBusNamespacePreparer(name_prefix='servicebustest')
43+
def test_mgmt_queue_create_with_invalid_name(self, servicebus_namespace_connection_string, **kwargs):
44+
mgmt_service = ServiceBusManagementClient.from_connection_string(servicebus_namespace_connection_string)
45+
46+
with pytest.raises(TypeError):
47+
mgmt_service.create_queue(Exception())
48+
49+
with pytest.raises(TypeError):
50+
mgmt_service.create_queue(QueueDescription(queue_name=Exception()))
51+
52+
with pytest.raises(ValueError):
53+
mgmt_service.create_queue('')
54+
55+
with pytest.raises(ValueError):
56+
mgmt_service.create_queue(QueueDescription(queue_name=''))
57+
58+
@pytest.mark.liveTest
59+
@CachedResourceGroupPreparer(name_prefix='servicebustest')
60+
@CachedServiceBusNamespacePreparer(name_prefix='servicebustest')
61+
def test_mgmt_queue_create_with_queue_description(self, servicebus_namespace_connection_string, **kwargs):
62+
mgmt_service = ServiceBusManagementClient.from_connection_string(servicebus_namespace_connection_string)
63+
64+
queue_name = str(uuid.uuid4())
65+
#TODO: Why don't we have an input model (queueOptions? as superclass of QueueDescription?) and output model to not show these params?
66+
#TODO: This fails with the following: E msrest.exceptions.DeserializationError: Find several XML 'prefix:DeadLetteringOnMessageExpiration' where it was not expected .tox\whl\lib\site-packages\msrest\serialization.py:1262: DeserializationError
67+
mgmt_service.create_queue(QueueDescription(queue_name=queue_name,
68+
auto_delete_on_idle=datetime.timedelta(minutes=10),
69+
dead_lettering_on_message_expiration=True,
70+
default_message_time_to_live=datetime.timedelta(minutes=11),
71+
duplicate_detection_history_time_window=datetime.timedelta(minutes=12),
72+
enable_batched_operations=True,
73+
enable_express=True,
74+
enable_partitioning=True,
75+
is_anonymous_accessible=True,
76+
lock_duration=datetime.timedelta(minutes=13),
77+
max_delivery_count=14,
78+
max_size_in_megabytes=15,
79+
requires_duplicate_detection=True,
80+
requires_session=True,
81+
support_ordering=True
82+
))
83+
84+
queue = mgmt_service.get_queue(queue_name)
85+
assert queue.queue_name == queue_name
86+
assert queue.auto_delete_on_idle == datetime.timedelta(minutes=10)
87+
assert queue.dead_lettering_on_message_expiration == True
88+
assert queue.default_message_time_to_live == datetime.timedelta(minutes=11)
89+
assert queue.duplicate_detection_history_time_window == datetime.timedelta(minutes=12)
90+
assert queue.enable_batched_operations == True
91+
assert queue.enable_express == True
92+
assert queue.enable_partitioning == True
93+
assert queue.is_anonymous_accessible == True
94+
assert queue.lock_duration == datetime.timedelta(minutes=13)
95+
assert queue.max_delivery_count == 14
96+
assert queue.max_size_in_megabytes == 15
97+
assert queue.requires_duplicate_detection == True
98+
assert queue.requires_session == True
99+
assert queue.support_ordering == True
100+
101+
@pytest.mark.liveTest
102+
@CachedResourceGroupPreparer(name_prefix='servicebustest')
103+
@CachedServiceBusNamespacePreparer(name_prefix='servicebustest')
104+
def test_mgmt_queue_create_duplicate(self, servicebus_namespace_connection_string, **kwargs):
105+
mgmt_service = ServiceBusManagementClient.from_connection_string(servicebus_namespace_connection_string)
106+
107+
queue_name = str(uuid.uuid4())
108+
created_at = utc_now()
109+
mgmt_service.create_queue(queue_name)
110+
with pytest.raises(ResourceExistsError):
111+
mgmt_service.create_queue(queue_name)
112+

0 commit comments

Comments
 (0)