Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Converting to pure unit tests #16499

Merged
merged 13 commits into from
Feb 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 0 additions & 12 deletions sdk/tables/azure-data-tables/tests/_shared/asynctestcase.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@

from .testcase import TableTestCase

LOGGING_FORMAT = '%(asctime)s %(name)-20s %(levelname)-5s %(message)s'

class AsyncFakeTokenCredential(object):
"""Protocol for classes able to provide OAuth tokens.
:param str scopes: Lets you specify the type of access needed.
Expand All @@ -23,16 +21,6 @@ async def get_token(self, *args):


class AsyncTableTestCase(TableTestCase):
@staticmethod
def generate_oauth_token(self):
if self.is_live:
from azure.identity.aio import ClientSecretCredential
return ClientSecretCredential(
self.get_settings_value("TENANT_ID"),
self.get_settings_value("CLIENT_ID"),
self.get_settings_value("CLIENT_SECRET"),
)
return self.generate_fake_token()

def generate_fake_token(self):
return AsyncFakeTokenCredential()
134 changes: 5 additions & 129 deletions sdk/tables/azure-data-tables/tests/_shared/testcase.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,33 +7,21 @@
from __future__ import division
from contextlib import contextmanager
import os
import time
from datetime import datetime, timedelta

import zlib
import sys
import string
import random
import re
import logging
from devtools_testutils import AzureTestCase
from azure_devtools.scenario_tests import RecordingProcessor, AzureTestError
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO

from azure.core.credentials import AccessToken

from azure.data.tables import generate_account_sas, AccountSasPermissions, ResourceTypes

import pytest

from devtools_testutils import AzureTestCase
from azure.core.credentials import AccessToken
from azure.data.tables import generate_account_sas, AccountSasPermissions, ResourceTypes

LOGGING_FORMAT = '%(asctime)s %(name)-20s %(levelname)-5s %(message)s'

SLEEP_DELAY = 30


class FakeTokenCredential(object):
"""Protocol for classes able to provide OAuth tokens.
:param str scopes: Lets you specify the type of access needed.
Expand All @@ -45,28 +33,7 @@ def get_token(self, *args):
return self.token


class XMSRequestIDBody(RecordingProcessor):
"""This process is used for Storage batch call only, to avoid the echo policy.
"""
def process_response(self, response):
content_type = None
for key, value in response.get('headers', {}).items():
if key.lower() == 'content-type':
content_type = (value[0] if isinstance(value, list) else value).lower()
break

if content_type and 'multipart/mixed' in content_type:
response['body']['string'] = re.sub(b"x-ms-client-request-id: [a-f0-9-]+\r\n", b"", response['body']['string'])

return response


class TableTestCase(AzureTestCase):

def __init__(self, *args, **kwargs):
super(TableTestCase, self).__init__(*args, **kwargs)
self.replay_processors.append(XMSRequestIDBody())
self._RESOURCE_GROUP = None,
class TableTestCase(object):

def connection_string(self, account, key):
return "DefaultEndpointsProtocol=https;AccountName=" + account + ";AccountKey=" + str(key) + ";EndpointSuffix=core.windows.net"
Expand All @@ -90,97 +57,6 @@ def account_url(self, account, endpoint_type):
if endpoint_type == "cosmos":
return "https://{}.table.cosmos.azure.com".format(account)


def configure_logging(self):
try:
enable_logging = self.get_settings_value("ENABLE_LOGGING")
except AzureTestError:
enable_logging = True # That's the default value in fake settings

self.enable_logging() if enable_logging else self.disable_logging()

def enable_logging(self):
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(LOGGING_FORMAT))
self.logger.handlers = [handler]
self.logger.setLevel(logging.INFO)
self.logger.propagate = True
self.logger.disabled = False

def disable_logging(self):
self.logger.propagate = False
self.logger.disabled = True
self.logger.handlers = []

def sleep(self, seconds):
if self.is_live:
time.sleep(seconds)

def get_random_bytes(self, size):
# recordings don't like random stuff. making this more
# deterministic.
return b'a'*size

def get_random_text_data(self, size):
'''Returns random unicode text data exceeding the size threshold for
chunking blob upload.'''
checksum = zlib.adler32(self.qualified_test_name.encode()) & 0xffffffff
rand = random.Random(checksum)
text = u''
words = [u'hello', u'world', u'python', u'啊齄丂狛狜']
while (len(text) < size):
index = int(rand.random()*(len(words) - 1))
text = text + u' ' + words[index]

return text

@staticmethod
def _set_test_proxy(service, settings):
if settings.USE_PROXY:
service.set_proxy(
settings.PROXY_HOST,
settings.PROXY_PORT,
settings.PROXY_USER,
settings.PROXY_PASSWORD,
)

def assertNamedItemInContainer(self, container, item_name, msg=None):
def _is_string(obj):
if sys.version_info >= (3,):
return isinstance(obj, str)
else:
return isinstance(obj, basestring)
for item in container:
if _is_string(item):
if item == item_name:
return
elif item.name == item_name:
return
elif hasattr(item, 'snapshot') and item.snapshot == item_name:
return


standardMsg = '{0} not found in {1}'.format(
repr(item_name), [str(c) for c in container])
self.fail(self._formatMessage(msg, standardMsg))

def assertNamedItemNotInContainer(self, container, item_name, msg=None):
for item in container:
if item.name == item_name:
standardMsg = '{0} unexpectedly found in {1}'.format(
repr(item_name), repr(container))
self.fail(self._formatMessage(msg, standardMsg))

def generate_oauth_token(self):
if self.is_live:
from azure.identity import ClientSecretCredential
return ClientSecretCredential(
self.get_settings_value("TENANT_ID"),
self.get_settings_value("CLIENT_ID"),
self.get_settings_value("CLIENT_SECRET"),
)
return self.generate_fake_token()

def generate_sas_token(self):
fake_key = 'a'*30 + 'b'*30

Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,25 @@ interactions:
DataServiceVersion:
- '3.0'
Date:
- Fri, 18 Dec 2020 17:08:50 GMT
- Wed, 03 Feb 2021 20:56:20 GMT
User-Agent:
- TestApp/v1.0 azsdk-python-data-tables/12.0.0b4 Python/3.9.0rc1 (Windows-10-10.0.19041-SP0)
- TestApp/v1.0 azsdk-python-data-tables/12.0.0b5 Python/3.9.0rc1 (Windows-10-10.0.19041-SP0)
x-ms-date:
- Fri, 18 Dec 2020 17:08:50 GMT
- Wed, 03 Feb 2021 20:56:20 GMT
x-ms-version:
- '2019-02-02'
method: GET
uri: https://fake_table_account.table.core.windows.net/Tables
response:
body:
string: '{"odata.metadata":"https://fake_table_account.table.core.windows.net/$metadata#Tables","value":[{"TableName":"listtable0cac14c3"},{"TableName":"listtable1cac14c3"},{"TableName":"listtable2cac14c3"},{"TableName":"listtable3cac14c3"}]}'
string: '{"odata.metadata":"https://fake_table_account.table.core.windows.net/$metadata#Tables","value":[]}'
headers:
cache-control:
- no-cache
content-type:
- application/json;odata=minimalmetadata;streaming=true;charset=utf-8
date:
- Fri, 18 Dec 2020 17:08:50 GMT
- Wed, 03 Feb 2021 20:56:20 GMT
server:
- Windows-Azure-Table/1.0 Microsoft-HTTPAPI/2.0
transfer-encoding:
Expand All @@ -53,26 +53,26 @@ interactions:
DataServiceVersion:
- '3.0'
Date:
- Fri, 18 Dec 2020 17:08:51 GMT
- Wed, 03 Feb 2021 20:56:21 GMT
User-Agent:
- TestApp/v2.0 TestApp/v1.0 azsdk-python-data-tables/12.0.0b4 Python/3.9.0rc1
- TestApp/v2.0 TestApp/v1.0 azsdk-python-data-tables/12.0.0b5 Python/3.9.0rc1
(Windows-10-10.0.19041-SP0)
x-ms-date:
- Fri, 18 Dec 2020 17:08:51 GMT
- Wed, 03 Feb 2021 20:56:21 GMT
x-ms-version:
- '2019-02-02'
method: GET
uri: https://fake_table_account.table.core.windows.net/Tables
response:
body:
string: '{"odata.metadata":"https://fake_table_account.table.core.windows.net/$metadata#Tables","value":[{"TableName":"listtable0cac14c3"},{"TableName":"listtable1cac14c3"},{"TableName":"listtable2cac14c3"},{"TableName":"listtable3cac14c3"}]}'
string: '{"odata.metadata":"https://fake_table_account.table.core.windows.net/$metadata#Tables","value":[]}'
headers:
cache-control:
- no-cache
content-type:
- application/json;odata=minimalmetadata;streaming=true;charset=utf-8
date:
- Fri, 18 Dec 2020 17:08:51 GMT
- Wed, 03 Feb 2021 20:56:20 GMT
server:
- Windows-Azure-Table/1.0 Microsoft-HTTPAPI/2.0
transfer-encoding:
Expand Down
Loading