prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>ammoToDmgPattern.py<|end_file_name|><|fim▁begin|># noinspection PyPackageRequirements
import wx
import gui.globalEvents as GE
import gui.mainFrame
from gui.contextMenu import ContextMenuSingle
from service.fit import Fit
class AmmoToDmgPattern(ContextMenuSingle):
visibilitySetting = 'ammoPattern'
def __init__(self):
self.mainFrame = gui.mainFrame.MainFrame.getInstance()
def display(self, callingWindow, srcContext, mainItem):
if srcContext not in ("marketItemGroup", "marketItemMisc") or self.mainFrame.getActiveFit() is None:
return False
if mainItem is None:
return False
for attr in ("emDamage", "thermalDamage", "explosiveDamage", "kineticDamage"):
if mainItem.getAttribute(attr) is not None:
return True
return False
def getText(self, callingWindow, itmContext, mainItem):
return "Set {} as Damage Pattern".format(itmContext if itmContext is not None else "Item")
def <|fim_middle|>(self, callingWindow, fullContext, mainItem, i):
fitID = self.mainFrame.getActiveFit()
Fit.getInstance().setAsPattern(fitID, mainItem)
wx.PostEvent(self.mainFrame, GE.FitChanged(fitIDs=(fitID,)))
def getBitmap(self, callingWindow, context, mainItem):
return None
AmmoToDmgPattern.register()
<|fim▁end|> | activate |
<|file_name|>ammoToDmgPattern.py<|end_file_name|><|fim▁begin|># noinspection PyPackageRequirements
import wx
import gui.globalEvents as GE
import gui.mainFrame
from gui.contextMenu import ContextMenuSingle
from service.fit import Fit
class AmmoToDmgPattern(ContextMenuSingle):
visibilitySetting = 'ammoPattern'
def __init__(self):
self.mainFrame = gui.mainFrame.MainFrame.getInstance()
def display(self, callingWindow, srcContext, mainItem):
if srcContext not in ("marketItemGroup", "marketItemMisc") or self.mainFrame.getActiveFit() is None:
return False
if mainItem is None:
return False
for attr in ("emDamage", "thermalDamage", "explosiveDamage", "kineticDamage"):
if mainItem.getAttribute(attr) is not None:
return True
return False
def getText(self, callingWindow, itmContext, mainItem):
return "Set {} as Damage Pattern".format(itmContext if itmContext is not None else "Item")
def activate(self, callingWindow, fullContext, mainItem, i):
fitID = self.mainFrame.getActiveFit()
Fit.getInstance().setAsPattern(fitID, mainItem)
wx.PostEvent(self.mainFrame, GE.FitChanged(fitIDs=(fitID,)))
def <|fim_middle|>(self, callingWindow, context, mainItem):
return None
AmmoToDmgPattern.register()
<|fim▁end|> | getBitmap |
<|file_name|>test_session.py<|end_file_name|><|fim▁begin|>"""
Tests for login and logout.
"""
import datetime
from unittest.mock import patch
import responses
import quilt3
from .utils import QuiltTestCase
class TestSession(QuiltTestCase):
@patch('quilt3.session.open_url')
@patch('quilt3.session.input', return_value='123456')
@patch('quilt3.session.login_with_token')
def test_login(self, mock_login_with_token, mock_input, mock_open_url):
quilt3.login()
url = quilt3.session.get_registry_url()
mock_open_url.assert_called_with(f'{url}/login')
mock_login_with_token.assert_called_with('123456')
@patch('quilt3.session._save_auth')
@patch('quilt3.session._save_credentials')
def test_login_with_token(self, mock_save_credentials, mock_save_auth):
url = quilt3.session.get_registry_url()
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789
)
self.requests_mock.add(
responses.POST,
f'{url}/api/token',
json=mock_auth,
status=200
)
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key',
SecretAccessKey='secret-key',
SessionToken='session-token',
Expiration="2019-05-28T23:58:07+00:00"
),
status=200
)
quilt3.session.login_with_token('123456')
mock_save_auth.assert_called_with({url: mock_auth})
mock_save_credentials.assert_called_with(dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time="2019-05-28T23:58:07+00:00"
))
@patch('quilt3.session._save_credentials')
@patch('quilt3.session._load_credentials')
def test_create_botocore_session(self, mock_load_credentials, mock_save_credentials):
def format_date(date):
return date.replace(tzinfo=datetime.timezone.utc, microsecond=0).isoformat()
# Test good credentials.
future_date = datetime.datetime.utcnow() + datetime.timedelta(hours=1)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(future_date)
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key'
assert credentials.secret_key == 'secret-key'
assert credentials.token == 'session-token'
mock_save_credentials.assert_not_called()
# Test expired credentials.
past_date = datetime.datetime.utcnow() - datetime.timedelta(minutes=5)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(past_date)
)
url = quilt3.session.get_registry_url()
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key2',
SecretAccessKey='secret-key2',
SessionToken='session-token2',
Expiration=format_date(future_date)
),
status=200
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
<|fim▁hole|>
mock_save_credentials.assert_called()
def test_logged_in(self):
registry_url = quilt3.session.get_registry_url()
other_registry_url = registry_url + 'other'
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789,
)
with patch('quilt3.session._load_auth', return_value={registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() == 'https://example.com'
mocked_load_auth.assert_called_once()
with patch('quilt3.session._load_auth', return_value={other_registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() is None
mocked_load_auth.assert_called_once()<|fim▁end|> | assert credentials.access_key == 'access-key2'
assert credentials.secret_key == 'secret-key2'
assert credentials.token == 'session-token2' |
<|file_name|>test_session.py<|end_file_name|><|fim▁begin|>"""
Tests for login and logout.
"""
import datetime
from unittest.mock import patch
import responses
import quilt3
from .utils import QuiltTestCase
class TestSession(QuiltTestCase):
<|fim_middle|>
<|fim▁end|> | @patch('quilt3.session.open_url')
@patch('quilt3.session.input', return_value='123456')
@patch('quilt3.session.login_with_token')
def test_login(self, mock_login_with_token, mock_input, mock_open_url):
quilt3.login()
url = quilt3.session.get_registry_url()
mock_open_url.assert_called_with(f'{url}/login')
mock_login_with_token.assert_called_with('123456')
@patch('quilt3.session._save_auth')
@patch('quilt3.session._save_credentials')
def test_login_with_token(self, mock_save_credentials, mock_save_auth):
url = quilt3.session.get_registry_url()
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789
)
self.requests_mock.add(
responses.POST,
f'{url}/api/token',
json=mock_auth,
status=200
)
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key',
SecretAccessKey='secret-key',
SessionToken='session-token',
Expiration="2019-05-28T23:58:07+00:00"
),
status=200
)
quilt3.session.login_with_token('123456')
mock_save_auth.assert_called_with({url: mock_auth})
mock_save_credentials.assert_called_with(dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time="2019-05-28T23:58:07+00:00"
))
@patch('quilt3.session._save_credentials')
@patch('quilt3.session._load_credentials')
def test_create_botocore_session(self, mock_load_credentials, mock_save_credentials):
def format_date(date):
return date.replace(tzinfo=datetime.timezone.utc, microsecond=0).isoformat()
# Test good credentials.
future_date = datetime.datetime.utcnow() + datetime.timedelta(hours=1)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(future_date)
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key'
assert credentials.secret_key == 'secret-key'
assert credentials.token == 'session-token'
mock_save_credentials.assert_not_called()
# Test expired credentials.
past_date = datetime.datetime.utcnow() - datetime.timedelta(minutes=5)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(past_date)
)
url = quilt3.session.get_registry_url()
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key2',
SecretAccessKey='secret-key2',
SessionToken='session-token2',
Expiration=format_date(future_date)
),
status=200
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key2'
assert credentials.secret_key == 'secret-key2'
assert credentials.token == 'session-token2'
mock_save_credentials.assert_called()
def test_logged_in(self):
registry_url = quilt3.session.get_registry_url()
other_registry_url = registry_url + 'other'
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789,
)
with patch('quilt3.session._load_auth', return_value={registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() == 'https://example.com'
mocked_load_auth.assert_called_once()
with patch('quilt3.session._load_auth', return_value={other_registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() is None
mocked_load_auth.assert_called_once() |
<|file_name|>test_session.py<|end_file_name|><|fim▁begin|>"""
Tests for login and logout.
"""
import datetime
from unittest.mock import patch
import responses
import quilt3
from .utils import QuiltTestCase
class TestSession(QuiltTestCase):
@patch('quilt3.session.open_url')
@patch('quilt3.session.input', return_value='123456')
@patch('quilt3.session.login_with_token')
def test_login(self, mock_login_with_token, mock_input, mock_open_url):
<|fim_middle|>
@patch('quilt3.session._save_auth')
@patch('quilt3.session._save_credentials')
def test_login_with_token(self, mock_save_credentials, mock_save_auth):
url = quilt3.session.get_registry_url()
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789
)
self.requests_mock.add(
responses.POST,
f'{url}/api/token',
json=mock_auth,
status=200
)
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key',
SecretAccessKey='secret-key',
SessionToken='session-token',
Expiration="2019-05-28T23:58:07+00:00"
),
status=200
)
quilt3.session.login_with_token('123456')
mock_save_auth.assert_called_with({url: mock_auth})
mock_save_credentials.assert_called_with(dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time="2019-05-28T23:58:07+00:00"
))
@patch('quilt3.session._save_credentials')
@patch('quilt3.session._load_credentials')
def test_create_botocore_session(self, mock_load_credentials, mock_save_credentials):
def format_date(date):
return date.replace(tzinfo=datetime.timezone.utc, microsecond=0).isoformat()
# Test good credentials.
future_date = datetime.datetime.utcnow() + datetime.timedelta(hours=1)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(future_date)
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key'
assert credentials.secret_key == 'secret-key'
assert credentials.token == 'session-token'
mock_save_credentials.assert_not_called()
# Test expired credentials.
past_date = datetime.datetime.utcnow() - datetime.timedelta(minutes=5)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(past_date)
)
url = quilt3.session.get_registry_url()
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key2',
SecretAccessKey='secret-key2',
SessionToken='session-token2',
Expiration=format_date(future_date)
),
status=200
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key2'
assert credentials.secret_key == 'secret-key2'
assert credentials.token == 'session-token2'
mock_save_credentials.assert_called()
def test_logged_in(self):
registry_url = quilt3.session.get_registry_url()
other_registry_url = registry_url + 'other'
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789,
)
with patch('quilt3.session._load_auth', return_value={registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() == 'https://example.com'
mocked_load_auth.assert_called_once()
with patch('quilt3.session._load_auth', return_value={other_registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() is None
mocked_load_auth.assert_called_once()
<|fim▁end|> | quilt3.login()
url = quilt3.session.get_registry_url()
mock_open_url.assert_called_with(f'{url}/login')
mock_login_with_token.assert_called_with('123456') |
<|file_name|>test_session.py<|end_file_name|><|fim▁begin|>"""
Tests for login and logout.
"""
import datetime
from unittest.mock import patch
import responses
import quilt3
from .utils import QuiltTestCase
class TestSession(QuiltTestCase):
@patch('quilt3.session.open_url')
@patch('quilt3.session.input', return_value='123456')
@patch('quilt3.session.login_with_token')
def test_login(self, mock_login_with_token, mock_input, mock_open_url):
quilt3.login()
url = quilt3.session.get_registry_url()
mock_open_url.assert_called_with(f'{url}/login')
mock_login_with_token.assert_called_with('123456')
@patch('quilt3.session._save_auth')
@patch('quilt3.session._save_credentials')
def test_login_with_token(self, mock_save_credentials, mock_save_auth):
<|fim_middle|>
@patch('quilt3.session._save_credentials')
@patch('quilt3.session._load_credentials')
def test_create_botocore_session(self, mock_load_credentials, mock_save_credentials):
def format_date(date):
return date.replace(tzinfo=datetime.timezone.utc, microsecond=0).isoformat()
# Test good credentials.
future_date = datetime.datetime.utcnow() + datetime.timedelta(hours=1)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(future_date)
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key'
assert credentials.secret_key == 'secret-key'
assert credentials.token == 'session-token'
mock_save_credentials.assert_not_called()
# Test expired credentials.
past_date = datetime.datetime.utcnow() - datetime.timedelta(minutes=5)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(past_date)
)
url = quilt3.session.get_registry_url()
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key2',
SecretAccessKey='secret-key2',
SessionToken='session-token2',
Expiration=format_date(future_date)
),
status=200
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key2'
assert credentials.secret_key == 'secret-key2'
assert credentials.token == 'session-token2'
mock_save_credentials.assert_called()
def test_logged_in(self):
registry_url = quilt3.session.get_registry_url()
other_registry_url = registry_url + 'other'
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789,
)
with patch('quilt3.session._load_auth', return_value={registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() == 'https://example.com'
mocked_load_auth.assert_called_once()
with patch('quilt3.session._load_auth', return_value={other_registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() is None
mocked_load_auth.assert_called_once()
<|fim▁end|> | url = quilt3.session.get_registry_url()
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789
)
self.requests_mock.add(
responses.POST,
f'{url}/api/token',
json=mock_auth,
status=200
)
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key',
SecretAccessKey='secret-key',
SessionToken='session-token',
Expiration="2019-05-28T23:58:07+00:00"
),
status=200
)
quilt3.session.login_with_token('123456')
mock_save_auth.assert_called_with({url: mock_auth})
mock_save_credentials.assert_called_with(dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time="2019-05-28T23:58:07+00:00"
)) |
<|file_name|>test_session.py<|end_file_name|><|fim▁begin|>"""
Tests for login and logout.
"""
import datetime
from unittest.mock import patch
import responses
import quilt3
from .utils import QuiltTestCase
class TestSession(QuiltTestCase):
@patch('quilt3.session.open_url')
@patch('quilt3.session.input', return_value='123456')
@patch('quilt3.session.login_with_token')
def test_login(self, mock_login_with_token, mock_input, mock_open_url):
quilt3.login()
url = quilt3.session.get_registry_url()
mock_open_url.assert_called_with(f'{url}/login')
mock_login_with_token.assert_called_with('123456')
@patch('quilt3.session._save_auth')
@patch('quilt3.session._save_credentials')
def test_login_with_token(self, mock_save_credentials, mock_save_auth):
url = quilt3.session.get_registry_url()
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789
)
self.requests_mock.add(
responses.POST,
f'{url}/api/token',
json=mock_auth,
status=200
)
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key',
SecretAccessKey='secret-key',
SessionToken='session-token',
Expiration="2019-05-28T23:58:07+00:00"
),
status=200
)
quilt3.session.login_with_token('123456')
mock_save_auth.assert_called_with({url: mock_auth})
mock_save_credentials.assert_called_with(dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time="2019-05-28T23:58:07+00:00"
))
@patch('quilt3.session._save_credentials')
@patch('quilt3.session._load_credentials')
def test_create_botocore_session(self, mock_load_credentials, mock_save_credentials):
<|fim_middle|>
def test_logged_in(self):
registry_url = quilt3.session.get_registry_url()
other_registry_url = registry_url + 'other'
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789,
)
with patch('quilt3.session._load_auth', return_value={registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() == 'https://example.com'
mocked_load_auth.assert_called_once()
with patch('quilt3.session._load_auth', return_value={other_registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() is None
mocked_load_auth.assert_called_once()
<|fim▁end|> | def format_date(date):
return date.replace(tzinfo=datetime.timezone.utc, microsecond=0).isoformat()
# Test good credentials.
future_date = datetime.datetime.utcnow() + datetime.timedelta(hours=1)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(future_date)
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key'
assert credentials.secret_key == 'secret-key'
assert credentials.token == 'session-token'
mock_save_credentials.assert_not_called()
# Test expired credentials.
past_date = datetime.datetime.utcnow() - datetime.timedelta(minutes=5)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(past_date)
)
url = quilt3.session.get_registry_url()
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key2',
SecretAccessKey='secret-key2',
SessionToken='session-token2',
Expiration=format_date(future_date)
),
status=200
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key2'
assert credentials.secret_key == 'secret-key2'
assert credentials.token == 'session-token2'
mock_save_credentials.assert_called() |
<|file_name|>test_session.py<|end_file_name|><|fim▁begin|>"""
Tests for login and logout.
"""
import datetime
from unittest.mock import patch
import responses
import quilt3
from .utils import QuiltTestCase
class TestSession(QuiltTestCase):
@patch('quilt3.session.open_url')
@patch('quilt3.session.input', return_value='123456')
@patch('quilt3.session.login_with_token')
def test_login(self, mock_login_with_token, mock_input, mock_open_url):
quilt3.login()
url = quilt3.session.get_registry_url()
mock_open_url.assert_called_with(f'{url}/login')
mock_login_with_token.assert_called_with('123456')
@patch('quilt3.session._save_auth')
@patch('quilt3.session._save_credentials')
def test_login_with_token(self, mock_save_credentials, mock_save_auth):
url = quilt3.session.get_registry_url()
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789
)
self.requests_mock.add(
responses.POST,
f'{url}/api/token',
json=mock_auth,
status=200
)
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key',
SecretAccessKey='secret-key',
SessionToken='session-token',
Expiration="2019-05-28T23:58:07+00:00"
),
status=200
)
quilt3.session.login_with_token('123456')
mock_save_auth.assert_called_with({url: mock_auth})
mock_save_credentials.assert_called_with(dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time="2019-05-28T23:58:07+00:00"
))
@patch('quilt3.session._save_credentials')
@patch('quilt3.session._load_credentials')
def test_create_botocore_session(self, mock_load_credentials, mock_save_credentials):
def format_date(date):
<|fim_middle|>
# Test good credentials.
future_date = datetime.datetime.utcnow() + datetime.timedelta(hours=1)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(future_date)
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key'
assert credentials.secret_key == 'secret-key'
assert credentials.token == 'session-token'
mock_save_credentials.assert_not_called()
# Test expired credentials.
past_date = datetime.datetime.utcnow() - datetime.timedelta(minutes=5)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(past_date)
)
url = quilt3.session.get_registry_url()
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key2',
SecretAccessKey='secret-key2',
SessionToken='session-token2',
Expiration=format_date(future_date)
),
status=200
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key2'
assert credentials.secret_key == 'secret-key2'
assert credentials.token == 'session-token2'
mock_save_credentials.assert_called()
def test_logged_in(self):
registry_url = quilt3.session.get_registry_url()
other_registry_url = registry_url + 'other'
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789,
)
with patch('quilt3.session._load_auth', return_value={registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() == 'https://example.com'
mocked_load_auth.assert_called_once()
with patch('quilt3.session._load_auth', return_value={other_registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() is None
mocked_load_auth.assert_called_once()
<|fim▁end|> | return date.replace(tzinfo=datetime.timezone.utc, microsecond=0).isoformat() |
<|file_name|>test_session.py<|end_file_name|><|fim▁begin|>"""
Tests for login and logout.
"""
import datetime
from unittest.mock import patch
import responses
import quilt3
from .utils import QuiltTestCase
class TestSession(QuiltTestCase):
@patch('quilt3.session.open_url')
@patch('quilt3.session.input', return_value='123456')
@patch('quilt3.session.login_with_token')
def test_login(self, mock_login_with_token, mock_input, mock_open_url):
quilt3.login()
url = quilt3.session.get_registry_url()
mock_open_url.assert_called_with(f'{url}/login')
mock_login_with_token.assert_called_with('123456')
@patch('quilt3.session._save_auth')
@patch('quilt3.session._save_credentials')
def test_login_with_token(self, mock_save_credentials, mock_save_auth):
url = quilt3.session.get_registry_url()
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789
)
self.requests_mock.add(
responses.POST,
f'{url}/api/token',
json=mock_auth,
status=200
)
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key',
SecretAccessKey='secret-key',
SessionToken='session-token',
Expiration="2019-05-28T23:58:07+00:00"
),
status=200
)
quilt3.session.login_with_token('123456')
mock_save_auth.assert_called_with({url: mock_auth})
mock_save_credentials.assert_called_with(dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time="2019-05-28T23:58:07+00:00"
))
@patch('quilt3.session._save_credentials')
@patch('quilt3.session._load_credentials')
def test_create_botocore_session(self, mock_load_credentials, mock_save_credentials):
def format_date(date):
return date.replace(tzinfo=datetime.timezone.utc, microsecond=0).isoformat()
# Test good credentials.
future_date = datetime.datetime.utcnow() + datetime.timedelta(hours=1)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(future_date)
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key'
assert credentials.secret_key == 'secret-key'
assert credentials.token == 'session-token'
mock_save_credentials.assert_not_called()
# Test expired credentials.
past_date = datetime.datetime.utcnow() - datetime.timedelta(minutes=5)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(past_date)
)
url = quilt3.session.get_registry_url()
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key2',
SecretAccessKey='secret-key2',
SessionToken='session-token2',
Expiration=format_date(future_date)
),
status=200
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key2'
assert credentials.secret_key == 'secret-key2'
assert credentials.token == 'session-token2'
mock_save_credentials.assert_called()
def test_logged_in(self):
<|fim_middle|>
<|fim▁end|> | registry_url = quilt3.session.get_registry_url()
other_registry_url = registry_url + 'other'
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789,
)
with patch('quilt3.session._load_auth', return_value={registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() == 'https://example.com'
mocked_load_auth.assert_called_once()
with patch('quilt3.session._load_auth', return_value={other_registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() is None
mocked_load_auth.assert_called_once() |
<|file_name|>test_session.py<|end_file_name|><|fim▁begin|>"""
Tests for login and logout.
"""
import datetime
from unittest.mock import patch
import responses
import quilt3
from .utils import QuiltTestCase
class TestSession(QuiltTestCase):
@patch('quilt3.session.open_url')
@patch('quilt3.session.input', return_value='123456')
@patch('quilt3.session.login_with_token')
def <|fim_middle|>(self, mock_login_with_token, mock_input, mock_open_url):
quilt3.login()
url = quilt3.session.get_registry_url()
mock_open_url.assert_called_with(f'{url}/login')
mock_login_with_token.assert_called_with('123456')
@patch('quilt3.session._save_auth')
@patch('quilt3.session._save_credentials')
def test_login_with_token(self, mock_save_credentials, mock_save_auth):
url = quilt3.session.get_registry_url()
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789
)
self.requests_mock.add(
responses.POST,
f'{url}/api/token',
json=mock_auth,
status=200
)
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key',
SecretAccessKey='secret-key',
SessionToken='session-token',
Expiration="2019-05-28T23:58:07+00:00"
),
status=200
)
quilt3.session.login_with_token('123456')
mock_save_auth.assert_called_with({url: mock_auth})
mock_save_credentials.assert_called_with(dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time="2019-05-28T23:58:07+00:00"
))
@patch('quilt3.session._save_credentials')
@patch('quilt3.session._load_credentials')
def test_create_botocore_session(self, mock_load_credentials, mock_save_credentials):
def format_date(date):
return date.replace(tzinfo=datetime.timezone.utc, microsecond=0).isoformat()
# Test good credentials.
future_date = datetime.datetime.utcnow() + datetime.timedelta(hours=1)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(future_date)
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key'
assert credentials.secret_key == 'secret-key'
assert credentials.token == 'session-token'
mock_save_credentials.assert_not_called()
# Test expired credentials.
past_date = datetime.datetime.utcnow() - datetime.timedelta(minutes=5)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(past_date)
)
url = quilt3.session.get_registry_url()
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key2',
SecretAccessKey='secret-key2',
SessionToken='session-token2',
Expiration=format_date(future_date)
),
status=200
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key2'
assert credentials.secret_key == 'secret-key2'
assert credentials.token == 'session-token2'
mock_save_credentials.assert_called()
def test_logged_in(self):
registry_url = quilt3.session.get_registry_url()
other_registry_url = registry_url + 'other'
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789,
)
with patch('quilt3.session._load_auth', return_value={registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() == 'https://example.com'
mocked_load_auth.assert_called_once()
with patch('quilt3.session._load_auth', return_value={other_registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() is None
mocked_load_auth.assert_called_once()
<|fim▁end|> | test_login |
<|file_name|>test_session.py<|end_file_name|><|fim▁begin|>"""
Tests for login and logout.
"""
import datetime
from unittest.mock import patch
import responses
import quilt3
from .utils import QuiltTestCase
class TestSession(QuiltTestCase):
@patch('quilt3.session.open_url')
@patch('quilt3.session.input', return_value='123456')
@patch('quilt3.session.login_with_token')
def test_login(self, mock_login_with_token, mock_input, mock_open_url):
quilt3.login()
url = quilt3.session.get_registry_url()
mock_open_url.assert_called_with(f'{url}/login')
mock_login_with_token.assert_called_with('123456')
@patch('quilt3.session._save_auth')
@patch('quilt3.session._save_credentials')
def <|fim_middle|>(self, mock_save_credentials, mock_save_auth):
url = quilt3.session.get_registry_url()
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789
)
self.requests_mock.add(
responses.POST,
f'{url}/api/token',
json=mock_auth,
status=200
)
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key',
SecretAccessKey='secret-key',
SessionToken='session-token',
Expiration="2019-05-28T23:58:07+00:00"
),
status=200
)
quilt3.session.login_with_token('123456')
mock_save_auth.assert_called_with({url: mock_auth})
mock_save_credentials.assert_called_with(dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time="2019-05-28T23:58:07+00:00"
))
@patch('quilt3.session._save_credentials')
@patch('quilt3.session._load_credentials')
def test_create_botocore_session(self, mock_load_credentials, mock_save_credentials):
def format_date(date):
return date.replace(tzinfo=datetime.timezone.utc, microsecond=0).isoformat()
# Test good credentials.
future_date = datetime.datetime.utcnow() + datetime.timedelta(hours=1)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(future_date)
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key'
assert credentials.secret_key == 'secret-key'
assert credentials.token == 'session-token'
mock_save_credentials.assert_not_called()
# Test expired credentials.
past_date = datetime.datetime.utcnow() - datetime.timedelta(minutes=5)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(past_date)
)
url = quilt3.session.get_registry_url()
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key2',
SecretAccessKey='secret-key2',
SessionToken='session-token2',
Expiration=format_date(future_date)
),
status=200
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key2'
assert credentials.secret_key == 'secret-key2'
assert credentials.token == 'session-token2'
mock_save_credentials.assert_called()
def test_logged_in(self):
registry_url = quilt3.session.get_registry_url()
other_registry_url = registry_url + 'other'
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789,
)
with patch('quilt3.session._load_auth', return_value={registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() == 'https://example.com'
mocked_load_auth.assert_called_once()
with patch('quilt3.session._load_auth', return_value={other_registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() is None
mocked_load_auth.assert_called_once()
<|fim▁end|> | test_login_with_token |
<|file_name|>test_session.py<|end_file_name|><|fim▁begin|>"""
Tests for login and logout.
"""
import datetime
from unittest.mock import patch
import responses
import quilt3
from .utils import QuiltTestCase
class TestSession(QuiltTestCase):
@patch('quilt3.session.open_url')
@patch('quilt3.session.input', return_value='123456')
@patch('quilt3.session.login_with_token')
def test_login(self, mock_login_with_token, mock_input, mock_open_url):
quilt3.login()
url = quilt3.session.get_registry_url()
mock_open_url.assert_called_with(f'{url}/login')
mock_login_with_token.assert_called_with('123456')
@patch('quilt3.session._save_auth')
@patch('quilt3.session._save_credentials')
def test_login_with_token(self, mock_save_credentials, mock_save_auth):
url = quilt3.session.get_registry_url()
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789
)
self.requests_mock.add(
responses.POST,
f'{url}/api/token',
json=mock_auth,
status=200
)
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key',
SecretAccessKey='secret-key',
SessionToken='session-token',
Expiration="2019-05-28T23:58:07+00:00"
),
status=200
)
quilt3.session.login_with_token('123456')
mock_save_auth.assert_called_with({url: mock_auth})
mock_save_credentials.assert_called_with(dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time="2019-05-28T23:58:07+00:00"
))
@patch('quilt3.session._save_credentials')
@patch('quilt3.session._load_credentials')
def <|fim_middle|>(self, mock_load_credentials, mock_save_credentials):
def format_date(date):
return date.replace(tzinfo=datetime.timezone.utc, microsecond=0).isoformat()
# Test good credentials.
future_date = datetime.datetime.utcnow() + datetime.timedelta(hours=1)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(future_date)
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key'
assert credentials.secret_key == 'secret-key'
assert credentials.token == 'session-token'
mock_save_credentials.assert_not_called()
# Test expired credentials.
past_date = datetime.datetime.utcnow() - datetime.timedelta(minutes=5)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(past_date)
)
url = quilt3.session.get_registry_url()
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key2',
SecretAccessKey='secret-key2',
SessionToken='session-token2',
Expiration=format_date(future_date)
),
status=200
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key2'
assert credentials.secret_key == 'secret-key2'
assert credentials.token == 'session-token2'
mock_save_credentials.assert_called()
def test_logged_in(self):
registry_url = quilt3.session.get_registry_url()
other_registry_url = registry_url + 'other'
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789,
)
with patch('quilt3.session._load_auth', return_value={registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() == 'https://example.com'
mocked_load_auth.assert_called_once()
with patch('quilt3.session._load_auth', return_value={other_registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() is None
mocked_load_auth.assert_called_once()
<|fim▁end|> | test_create_botocore_session |
<|file_name|>test_session.py<|end_file_name|><|fim▁begin|>"""
Tests for login and logout.
"""
import datetime
from unittest.mock import patch
import responses
import quilt3
from .utils import QuiltTestCase
class TestSession(QuiltTestCase):
@patch('quilt3.session.open_url')
@patch('quilt3.session.input', return_value='123456')
@patch('quilt3.session.login_with_token')
def test_login(self, mock_login_with_token, mock_input, mock_open_url):
quilt3.login()
url = quilt3.session.get_registry_url()
mock_open_url.assert_called_with(f'{url}/login')
mock_login_with_token.assert_called_with('123456')
@patch('quilt3.session._save_auth')
@patch('quilt3.session._save_credentials')
def test_login_with_token(self, mock_save_credentials, mock_save_auth):
url = quilt3.session.get_registry_url()
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789
)
self.requests_mock.add(
responses.POST,
f'{url}/api/token',
json=mock_auth,
status=200
)
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key',
SecretAccessKey='secret-key',
SessionToken='session-token',
Expiration="2019-05-28T23:58:07+00:00"
),
status=200
)
quilt3.session.login_with_token('123456')
mock_save_auth.assert_called_with({url: mock_auth})
mock_save_credentials.assert_called_with(dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time="2019-05-28T23:58:07+00:00"
))
@patch('quilt3.session._save_credentials')
@patch('quilt3.session._load_credentials')
def test_create_botocore_session(self, mock_load_credentials, mock_save_credentials):
def <|fim_middle|>(date):
return date.replace(tzinfo=datetime.timezone.utc, microsecond=0).isoformat()
# Test good credentials.
future_date = datetime.datetime.utcnow() + datetime.timedelta(hours=1)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(future_date)
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key'
assert credentials.secret_key == 'secret-key'
assert credentials.token == 'session-token'
mock_save_credentials.assert_not_called()
# Test expired credentials.
past_date = datetime.datetime.utcnow() - datetime.timedelta(minutes=5)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(past_date)
)
url = quilt3.session.get_registry_url()
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key2',
SecretAccessKey='secret-key2',
SessionToken='session-token2',
Expiration=format_date(future_date)
),
status=200
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key2'
assert credentials.secret_key == 'secret-key2'
assert credentials.token == 'session-token2'
mock_save_credentials.assert_called()
def test_logged_in(self):
registry_url = quilt3.session.get_registry_url()
other_registry_url = registry_url + 'other'
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789,
)
with patch('quilt3.session._load_auth', return_value={registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() == 'https://example.com'
mocked_load_auth.assert_called_once()
with patch('quilt3.session._load_auth', return_value={other_registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() is None
mocked_load_auth.assert_called_once()
<|fim▁end|> | format_date |
<|file_name|>test_session.py<|end_file_name|><|fim▁begin|>"""
Tests for login and logout.
"""
import datetime
from unittest.mock import patch
import responses
import quilt3
from .utils import QuiltTestCase
class TestSession(QuiltTestCase):
@patch('quilt3.session.open_url')
@patch('quilt3.session.input', return_value='123456')
@patch('quilt3.session.login_with_token')
def test_login(self, mock_login_with_token, mock_input, mock_open_url):
quilt3.login()
url = quilt3.session.get_registry_url()
mock_open_url.assert_called_with(f'{url}/login')
mock_login_with_token.assert_called_with('123456')
@patch('quilt3.session._save_auth')
@patch('quilt3.session._save_credentials')
def test_login_with_token(self, mock_save_credentials, mock_save_auth):
url = quilt3.session.get_registry_url()
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789
)
self.requests_mock.add(
responses.POST,
f'{url}/api/token',
json=mock_auth,
status=200
)
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key',
SecretAccessKey='secret-key',
SessionToken='session-token',
Expiration="2019-05-28T23:58:07+00:00"
),
status=200
)
quilt3.session.login_with_token('123456')
mock_save_auth.assert_called_with({url: mock_auth})
mock_save_credentials.assert_called_with(dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time="2019-05-28T23:58:07+00:00"
))
@patch('quilt3.session._save_credentials')
@patch('quilt3.session._load_credentials')
def test_create_botocore_session(self, mock_load_credentials, mock_save_credentials):
def format_date(date):
return date.replace(tzinfo=datetime.timezone.utc, microsecond=0).isoformat()
# Test good credentials.
future_date = datetime.datetime.utcnow() + datetime.timedelta(hours=1)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(future_date)
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key'
assert credentials.secret_key == 'secret-key'
assert credentials.token == 'session-token'
mock_save_credentials.assert_not_called()
# Test expired credentials.
past_date = datetime.datetime.utcnow() - datetime.timedelta(minutes=5)
mock_load_credentials.return_value = dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time=format_date(past_date)
)
url = quilt3.session.get_registry_url()
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key2',
SecretAccessKey='secret-key2',
SessionToken='session-token2',
Expiration=format_date(future_date)
),
status=200
)
session = quilt3.session.create_botocore_session()
credentials = session.get_credentials()
assert credentials.access_key == 'access-key2'
assert credentials.secret_key == 'secret-key2'
assert credentials.token == 'session-token2'
mock_save_credentials.assert_called()
def <|fim_middle|>(self):
registry_url = quilt3.session.get_registry_url()
other_registry_url = registry_url + 'other'
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789,
)
with patch('quilt3.session._load_auth', return_value={registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() == 'https://example.com'
mocked_load_auth.assert_called_once()
with patch('quilt3.session._load_auth', return_value={other_registry_url: mock_auth}) as mocked_load_auth:
assert quilt3.logged_in() is None
mocked_load_auth.assert_called_once()
<|fim▁end|> | test_logged_in |
<|file_name|>many_many_relation.py<|end_file_name|><|fim▁begin|>from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
# demo many to many relationship
# http://docs.sqlalchemy.org/en/rel_0_9/orm/basic_relationships.html#many-to-many
engine = create_engine('sqlite:///manymany.db')
Base = declarative_base()
# Association table linking the two tables
# Also see: http://docs.sqlalchemy.org/en/rel_0_9/orm/basic_relationships.html#association-object
member_club_mapping = Table('member_club_mapping', Base.metadata,
Column('member_id', Integer, ForeignKey('member.id')),
Column('club_id', Integer, ForeignKey('club.id')))
class Member(Base):
__tablename__ = 'member'
id = Column(Integer, primary_key=True)
first_name = Column(String)
last_name = Column(String)
clubs = relationship('Club', back_populates='members',
secondary=member_club_mapping)
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
class Club(Base):
__tablename__ = 'club'
id = Column(Integer, primary_key=True)
name = Column(String)
members = relationship('Member', back_populates='clubs',
secondary=member_club_mapping)
def __init__(self, name):
self.name = name
# create tables
Base.metadata.create_all(engine)
# create a Session
Session = sessionmaker(bind=engine)
session = Session()
# Populate
member1 = Member('John', 'Doe')
club1 = Club('Club dub')
club1.members.append(member1)
session.add(club1)
club2 = Club('Club dub dub')
club2.members.append(member1)
session.add(club2)
club3 = Club('Club dub step')
session.add(club3)
member2 = Member('Jane', 'Allen')
member2.clubs.extend([club1, club2])
session.add(member2)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print Club
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
print 'After removing members with first name: Jane'
# Remove a record
record = session.query(Member).filter(Member.first_name == 'Jane').all()
for r in record:
session.delete(r)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:<|fim▁hole|> print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
print 'After removing the club, Club dub'
# Remove a record
record = session.query(Club).filter(Club.name == 'Club dub').all()
for r in record:
session.delete(r)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]<|fim▁end|> | |
<|file_name|>many_many_relation.py<|end_file_name|><|fim▁begin|>from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
# demo many to many relationship
# http://docs.sqlalchemy.org/en/rel_0_9/orm/basic_relationships.html#many-to-many
engine = create_engine('sqlite:///manymany.db')
Base = declarative_base()
# Association table linking the two tables
# Also see: http://docs.sqlalchemy.org/en/rel_0_9/orm/basic_relationships.html#association-object
member_club_mapping = Table('member_club_mapping', Base.metadata,
Column('member_id', Integer, ForeignKey('member.id')),
Column('club_id', Integer, ForeignKey('club.id')))
class Member(Base):
<|fim_middle|>
class Club(Base):
__tablename__ = 'club'
id = Column(Integer, primary_key=True)
name = Column(String)
members = relationship('Member', back_populates='clubs',
secondary=member_club_mapping)
def __init__(self, name):
self.name = name
# create tables
Base.metadata.create_all(engine)
# create a Session
Session = sessionmaker(bind=engine)
session = Session()
# Populate
member1 = Member('John', 'Doe')
club1 = Club('Club dub')
club1.members.append(member1)
session.add(club1)
club2 = Club('Club dub dub')
club2.members.append(member1)
session.add(club2)
club3 = Club('Club dub step')
session.add(club3)
member2 = Member('Jane', 'Allen')
member2.clubs.extend([club1, club2])
session.add(member2)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print Club
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
print 'After removing members with first name: Jane'
# Remove a record
record = session.query(Member).filter(Member.first_name == 'Jane').all()
for r in record:
session.delete(r)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
print 'After removing the club, Club dub'
# Remove a record
record = session.query(Club).filter(Club.name == 'Club dub').all()
for r in record:
session.delete(r)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
<|fim▁end|> | __tablename__ = 'member'
id = Column(Integer, primary_key=True)
first_name = Column(String)
last_name = Column(String)
clubs = relationship('Club', back_populates='members',
secondary=member_club_mapping)
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name |
<|file_name|>many_many_relation.py<|end_file_name|><|fim▁begin|>from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
# demo many to many relationship
# http://docs.sqlalchemy.org/en/rel_0_9/orm/basic_relationships.html#many-to-many
engine = create_engine('sqlite:///manymany.db')
Base = declarative_base()
# Association table linking the two tables
# Also see: http://docs.sqlalchemy.org/en/rel_0_9/orm/basic_relationships.html#association-object
member_club_mapping = Table('member_club_mapping', Base.metadata,
Column('member_id', Integer, ForeignKey('member.id')),
Column('club_id', Integer, ForeignKey('club.id')))
class Member(Base):
__tablename__ = 'member'
id = Column(Integer, primary_key=True)
first_name = Column(String)
last_name = Column(String)
clubs = relationship('Club', back_populates='members',
secondary=member_club_mapping)
def __init__(self, first_name, last_name):
<|fim_middle|>
class Club(Base):
__tablename__ = 'club'
id = Column(Integer, primary_key=True)
name = Column(String)
members = relationship('Member', back_populates='clubs',
secondary=member_club_mapping)
def __init__(self, name):
self.name = name
# create tables
Base.metadata.create_all(engine)
# create a Session
Session = sessionmaker(bind=engine)
session = Session()
# Populate
member1 = Member('John', 'Doe')
club1 = Club('Club dub')
club1.members.append(member1)
session.add(club1)
club2 = Club('Club dub dub')
club2.members.append(member1)
session.add(club2)
club3 = Club('Club dub step')
session.add(club3)
member2 = Member('Jane', 'Allen')
member2.clubs.extend([club1, club2])
session.add(member2)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print Club
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
print 'After removing members with first name: Jane'
# Remove a record
record = session.query(Member).filter(Member.first_name == 'Jane').all()
for r in record:
session.delete(r)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
print 'After removing the club, Club dub'
# Remove a record
record = session.query(Club).filter(Club.name == 'Club dub').all()
for r in record:
session.delete(r)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
<|fim▁end|> | self.first_name = first_name
self.last_name = last_name |
<|file_name|>many_many_relation.py<|end_file_name|><|fim▁begin|>from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
# demo many to many relationship
# http://docs.sqlalchemy.org/en/rel_0_9/orm/basic_relationships.html#many-to-many
engine = create_engine('sqlite:///manymany.db')
Base = declarative_base()
# Association table linking the two tables
# Also see: http://docs.sqlalchemy.org/en/rel_0_9/orm/basic_relationships.html#association-object
member_club_mapping = Table('member_club_mapping', Base.metadata,
Column('member_id', Integer, ForeignKey('member.id')),
Column('club_id', Integer, ForeignKey('club.id')))
class Member(Base):
__tablename__ = 'member'
id = Column(Integer, primary_key=True)
first_name = Column(String)
last_name = Column(String)
clubs = relationship('Club', back_populates='members',
secondary=member_club_mapping)
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
class Club(Base):
<|fim_middle|>
# create tables
Base.metadata.create_all(engine)
# create a Session
Session = sessionmaker(bind=engine)
session = Session()
# Populate
member1 = Member('John', 'Doe')
club1 = Club('Club dub')
club1.members.append(member1)
session.add(club1)
club2 = Club('Club dub dub')
club2.members.append(member1)
session.add(club2)
club3 = Club('Club dub step')
session.add(club3)
member2 = Member('Jane', 'Allen')
member2.clubs.extend([club1, club2])
session.add(member2)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print Club
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
print 'After removing members with first name: Jane'
# Remove a record
record = session.query(Member).filter(Member.first_name == 'Jane').all()
for r in record:
session.delete(r)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
print 'After removing the club, Club dub'
# Remove a record
record = session.query(Club).filter(Club.name == 'Club dub').all()
for r in record:
session.delete(r)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
<|fim▁end|> | __tablename__ = 'club'
id = Column(Integer, primary_key=True)
name = Column(String)
members = relationship('Member', back_populates='clubs',
secondary=member_club_mapping)
def __init__(self, name):
self.name = name |
<|file_name|>many_many_relation.py<|end_file_name|><|fim▁begin|>from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
# demo many to many relationship
# http://docs.sqlalchemy.org/en/rel_0_9/orm/basic_relationships.html#many-to-many
engine = create_engine('sqlite:///manymany.db')
Base = declarative_base()
# Association table linking the two tables
# Also see: http://docs.sqlalchemy.org/en/rel_0_9/orm/basic_relationships.html#association-object
member_club_mapping = Table('member_club_mapping', Base.metadata,
Column('member_id', Integer, ForeignKey('member.id')),
Column('club_id', Integer, ForeignKey('club.id')))
class Member(Base):
__tablename__ = 'member'
id = Column(Integer, primary_key=True)
first_name = Column(String)
last_name = Column(String)
clubs = relationship('Club', back_populates='members',
secondary=member_club_mapping)
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
class Club(Base):
__tablename__ = 'club'
id = Column(Integer, primary_key=True)
name = Column(String)
members = relationship('Member', back_populates='clubs',
secondary=member_club_mapping)
def __init__(self, name):
<|fim_middle|>
# create tables
Base.metadata.create_all(engine)
# create a Session
Session = sessionmaker(bind=engine)
session = Session()
# Populate
member1 = Member('John', 'Doe')
club1 = Club('Club dub')
club1.members.append(member1)
session.add(club1)
club2 = Club('Club dub dub')
club2.members.append(member1)
session.add(club2)
club3 = Club('Club dub step')
session.add(club3)
member2 = Member('Jane', 'Allen')
member2.clubs.extend([club1, club2])
session.add(member2)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print Club
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
print 'After removing members with first name: Jane'
# Remove a record
record = session.query(Member).filter(Member.first_name == 'Jane').all()
for r in record:
session.delete(r)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
print 'After removing the club, Club dub'
# Remove a record
record = session.query(Club).filter(Club.name == 'Club dub').all()
for r in record:
session.delete(r)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
<|fim▁end|> | self.name = name |
<|file_name|>many_many_relation.py<|end_file_name|><|fim▁begin|>from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
# demo many to many relationship
# http://docs.sqlalchemy.org/en/rel_0_9/orm/basic_relationships.html#many-to-many
engine = create_engine('sqlite:///manymany.db')
Base = declarative_base()
# Association table linking the two tables
# Also see: http://docs.sqlalchemy.org/en/rel_0_9/orm/basic_relationships.html#association-object
member_club_mapping = Table('member_club_mapping', Base.metadata,
Column('member_id', Integer, ForeignKey('member.id')),
Column('club_id', Integer, ForeignKey('club.id')))
class Member(Base):
__tablename__ = 'member'
id = Column(Integer, primary_key=True)
first_name = Column(String)
last_name = Column(String)
clubs = relationship('Club', back_populates='members',
secondary=member_club_mapping)
def <|fim_middle|>(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
class Club(Base):
__tablename__ = 'club'
id = Column(Integer, primary_key=True)
name = Column(String)
members = relationship('Member', back_populates='clubs',
secondary=member_club_mapping)
def __init__(self, name):
self.name = name
# create tables
Base.metadata.create_all(engine)
# create a Session
Session = sessionmaker(bind=engine)
session = Session()
# Populate
member1 = Member('John', 'Doe')
club1 = Club('Club dub')
club1.members.append(member1)
session.add(club1)
club2 = Club('Club dub dub')
club2.members.append(member1)
session.add(club2)
club3 = Club('Club dub step')
session.add(club3)
member2 = Member('Jane', 'Allen')
member2.clubs.extend([club1, club2])
session.add(member2)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print Club
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
print 'After removing members with first name: Jane'
# Remove a record
record = session.query(Member).filter(Member.first_name == 'Jane').all()
for r in record:
session.delete(r)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
print 'After removing the club, Club dub'
# Remove a record
record = session.query(Club).filter(Club.name == 'Club dub').all()
for r in record:
session.delete(r)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
<|fim▁end|> | __init__ |
<|file_name|>many_many_relation.py<|end_file_name|><|fim▁begin|>from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
# demo many to many relationship
# http://docs.sqlalchemy.org/en/rel_0_9/orm/basic_relationships.html#many-to-many
engine = create_engine('sqlite:///manymany.db')
Base = declarative_base()
# Association table linking the two tables
# Also see: http://docs.sqlalchemy.org/en/rel_0_9/orm/basic_relationships.html#association-object
member_club_mapping = Table('member_club_mapping', Base.metadata,
Column('member_id', Integer, ForeignKey('member.id')),
Column('club_id', Integer, ForeignKey('club.id')))
class Member(Base):
__tablename__ = 'member'
id = Column(Integer, primary_key=True)
first_name = Column(String)
last_name = Column(String)
clubs = relationship('Club', back_populates='members',
secondary=member_club_mapping)
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
class Club(Base):
__tablename__ = 'club'
id = Column(Integer, primary_key=True)
name = Column(String)
members = relationship('Member', back_populates='clubs',
secondary=member_club_mapping)
def <|fim_middle|>(self, name):
self.name = name
# create tables
Base.metadata.create_all(engine)
# create a Session
Session = sessionmaker(bind=engine)
session = Session()
# Populate
member1 = Member('John', 'Doe')
club1 = Club('Club dub')
club1.members.append(member1)
session.add(club1)
club2 = Club('Club dub dub')
club2.members.append(member1)
session.add(club2)
club3 = Club('Club dub step')
session.add(club3)
member2 = Member('Jane', 'Allen')
member2.clubs.extend([club1, club2])
session.add(member2)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print Club
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
print 'After removing members with first name: Jane'
# Remove a record
record = session.query(Member).filter(Member.first_name == 'Jane').all()
for r in record:
session.delete(r)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
print 'After removing the club, Club dub'
# Remove a record
record = session.query(Club).filter(Club.name == 'Club dub').all()
for r in record:
session.delete(r)
session.commit()
# query and print Member
res = session.query(Member).all()
for member in res:
print member.first_name, member.last_name , [club.name for club in member.clubs]
# query and print
res = session.query(Club).all()
for club in res:
print club.name, [(member.first_name, member.last_name) for member in club.members]
<|fim▁end|> | __init__ |
<|file_name|>pos_config.py<|end_file_name|><|fim▁begin|># Copyright 2015 ACSONE SA/NV
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
<|fim▁hole|>class PosConfig(models.Model):
_inherit = "pos.config"
account_analytic_id = fields.Many2one(
comodel_name="account.analytic.account", string="Analytic Account"
)<|fim▁end|> | |
<|file_name|>pos_config.py<|end_file_name|><|fim▁begin|># Copyright 2015 ACSONE SA/NV
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class PosConfig(models.Model):
<|fim_middle|>
<|fim▁end|> | _inherit = "pos.config"
account_analytic_id = fields.Many2one(
comodel_name="account.analytic.account", string="Analytic Account"
) |
<|file_name|>fastq_to_fasta.py<|end_file_name|><|fim▁begin|>import os
import sys
from Bio import SeqIO
f = open(sys.argv[1], 'rU')
out = open(sys.argv[2], 'w')
for records in SeqIO.parse(f, 'fastq'):<|fim▁hole|><|fim▁end|> | SeqIO.write(records, out, 'fasta') |
<|file_name|>_sql_virtual_machine_management_client.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.<|fim▁hole|># Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import SqlVirtualMachineManagementClientConfiguration
from .operations import AvailabilityGroupListenersOperations, Operations, SqlVirtualMachineGroupsOperations, SqlVirtualMachinesOperations
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class SqlVirtualMachineManagementClient:
"""The SQL virtual machine management API provides a RESTful set of web APIs that interact with Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables users to create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group listener.
:ivar availability_group_listeners: AvailabilityGroupListenersOperations operations
:vartype availability_group_listeners:
azure.mgmt.sqlvirtualmachine.aio.operations.AvailabilityGroupListenersOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.sqlvirtualmachine.aio.operations.Operations
:ivar sql_virtual_machine_groups: SqlVirtualMachineGroupsOperations operations
:vartype sql_virtual_machine_groups:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachineGroupsOperations
:ivar sql_virtual_machines: SqlVirtualMachinesOperations operations
:vartype sql_virtual_machines:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachinesOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Subscription ID that identifies an Azure subscription.
:type subscription_id: str
:param base_url: Service URL. Default value is 'https://management.azure.com'.
:type base_url: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = SqlVirtualMachineManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.availability_group_listeners = AvailabilityGroupListenersOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machine_groups = SqlVirtualMachineGroupsOperations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machines = SqlVirtualMachinesOperations(self._client, self._config, self._serialize, self._deserialize)
def _send_request(
self,
request: HttpRequest,
**kwargs: Any
) -> Awaitable[AsyncHttpResponse]:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
async def close(self) -> None:
await self._client.close()
async def __aenter__(self) -> "SqlVirtualMachineManagementClient":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)<|fim▁end|> | # Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator. |
<|file_name|>_sql_virtual_machine_management_client.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import SqlVirtualMachineManagementClientConfiguration
from .operations import AvailabilityGroupListenersOperations, Operations, SqlVirtualMachineGroupsOperations, SqlVirtualMachinesOperations
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class SqlVirtualMachineManagementClient:
<|fim_middle|>
<|fim▁end|> | """The SQL virtual machine management API provides a RESTful set of web APIs that interact with Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables users to create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group listener.
:ivar availability_group_listeners: AvailabilityGroupListenersOperations operations
:vartype availability_group_listeners:
azure.mgmt.sqlvirtualmachine.aio.operations.AvailabilityGroupListenersOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.sqlvirtualmachine.aio.operations.Operations
:ivar sql_virtual_machine_groups: SqlVirtualMachineGroupsOperations operations
:vartype sql_virtual_machine_groups:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachineGroupsOperations
:ivar sql_virtual_machines: SqlVirtualMachinesOperations operations
:vartype sql_virtual_machines:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachinesOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Subscription ID that identifies an Azure subscription.
:type subscription_id: str
:param base_url: Service URL. Default value is 'https://management.azure.com'.
:type base_url: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = SqlVirtualMachineManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.availability_group_listeners = AvailabilityGroupListenersOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machine_groups = SqlVirtualMachineGroupsOperations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machines = SqlVirtualMachinesOperations(self._client, self._config, self._serialize, self._deserialize)
def _send_request(
self,
request: HttpRequest,
**kwargs: Any
) -> Awaitable[AsyncHttpResponse]:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
async def close(self) -> None:
await self._client.close()
async def __aenter__(self) -> "SqlVirtualMachineManagementClient":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details) |
<|file_name|>_sql_virtual_machine_management_client.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import SqlVirtualMachineManagementClientConfiguration
from .operations import AvailabilityGroupListenersOperations, Operations, SqlVirtualMachineGroupsOperations, SqlVirtualMachinesOperations
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class SqlVirtualMachineManagementClient:
"""The SQL virtual machine management API provides a RESTful set of web APIs that interact with Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables users to create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group listener.
:ivar availability_group_listeners: AvailabilityGroupListenersOperations operations
:vartype availability_group_listeners:
azure.mgmt.sqlvirtualmachine.aio.operations.AvailabilityGroupListenersOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.sqlvirtualmachine.aio.operations.Operations
:ivar sql_virtual_machine_groups: SqlVirtualMachineGroupsOperations operations
:vartype sql_virtual_machine_groups:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachineGroupsOperations
:ivar sql_virtual_machines: SqlVirtualMachinesOperations operations
:vartype sql_virtual_machines:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachinesOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Subscription ID that identifies an Azure subscription.
:type subscription_id: str
:param base_url: Service URL. Default value is 'https://management.azure.com'.
:type base_url: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
<|fim_middle|>
def _send_request(
self,
request: HttpRequest,
**kwargs: Any
) -> Awaitable[AsyncHttpResponse]:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
async def close(self) -> None:
await self._client.close()
async def __aenter__(self) -> "SqlVirtualMachineManagementClient":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)
<|fim▁end|> | self._config = SqlVirtualMachineManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.availability_group_listeners = AvailabilityGroupListenersOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machine_groups = SqlVirtualMachineGroupsOperations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machines = SqlVirtualMachinesOperations(self._client, self._config, self._serialize, self._deserialize) |
<|file_name|>_sql_virtual_machine_management_client.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import SqlVirtualMachineManagementClientConfiguration
from .operations import AvailabilityGroupListenersOperations, Operations, SqlVirtualMachineGroupsOperations, SqlVirtualMachinesOperations
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class SqlVirtualMachineManagementClient:
"""The SQL virtual machine management API provides a RESTful set of web APIs that interact with Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables users to create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group listener.
:ivar availability_group_listeners: AvailabilityGroupListenersOperations operations
:vartype availability_group_listeners:
azure.mgmt.sqlvirtualmachine.aio.operations.AvailabilityGroupListenersOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.sqlvirtualmachine.aio.operations.Operations
:ivar sql_virtual_machine_groups: SqlVirtualMachineGroupsOperations operations
:vartype sql_virtual_machine_groups:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachineGroupsOperations
:ivar sql_virtual_machines: SqlVirtualMachinesOperations operations
:vartype sql_virtual_machines:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachinesOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Subscription ID that identifies an Azure subscription.
:type subscription_id: str
:param base_url: Service URL. Default value is 'https://management.azure.com'.
:type base_url: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = SqlVirtualMachineManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.availability_group_listeners = AvailabilityGroupListenersOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machine_groups = SqlVirtualMachineGroupsOperations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machines = SqlVirtualMachinesOperations(self._client, self._config, self._serialize, self._deserialize)
def _send_request(
self,
request: HttpRequest,
**kwargs: Any
) -> Awaitable[AsyncHttpResponse]:
<|fim_middle|>
async def close(self) -> None:
await self._client.close()
async def __aenter__(self) -> "SqlVirtualMachineManagementClient":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)
<|fim▁end|> | """Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs) |
<|file_name|>_sql_virtual_machine_management_client.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import SqlVirtualMachineManagementClientConfiguration
from .operations import AvailabilityGroupListenersOperations, Operations, SqlVirtualMachineGroupsOperations, SqlVirtualMachinesOperations
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class SqlVirtualMachineManagementClient:
"""The SQL virtual machine management API provides a RESTful set of web APIs that interact with Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables users to create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group listener.
:ivar availability_group_listeners: AvailabilityGroupListenersOperations operations
:vartype availability_group_listeners:
azure.mgmt.sqlvirtualmachine.aio.operations.AvailabilityGroupListenersOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.sqlvirtualmachine.aio.operations.Operations
:ivar sql_virtual_machine_groups: SqlVirtualMachineGroupsOperations operations
:vartype sql_virtual_machine_groups:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachineGroupsOperations
:ivar sql_virtual_machines: SqlVirtualMachinesOperations operations
:vartype sql_virtual_machines:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachinesOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Subscription ID that identifies an Azure subscription.
:type subscription_id: str
:param base_url: Service URL. Default value is 'https://management.azure.com'.
:type base_url: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = SqlVirtualMachineManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.availability_group_listeners = AvailabilityGroupListenersOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machine_groups = SqlVirtualMachineGroupsOperations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machines = SqlVirtualMachinesOperations(self._client, self._config, self._serialize, self._deserialize)
def _send_request(
self,
request: HttpRequest,
**kwargs: Any
) -> Awaitable[AsyncHttpResponse]:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
async def close(self) -> None:
<|fim_middle|>
async def __aenter__(self) -> "SqlVirtualMachineManagementClient":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)
<|fim▁end|> | await self._client.close() |
<|file_name|>_sql_virtual_machine_management_client.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import SqlVirtualMachineManagementClientConfiguration
from .operations import AvailabilityGroupListenersOperations, Operations, SqlVirtualMachineGroupsOperations, SqlVirtualMachinesOperations
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class SqlVirtualMachineManagementClient:
"""The SQL virtual machine management API provides a RESTful set of web APIs that interact with Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables users to create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group listener.
:ivar availability_group_listeners: AvailabilityGroupListenersOperations operations
:vartype availability_group_listeners:
azure.mgmt.sqlvirtualmachine.aio.operations.AvailabilityGroupListenersOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.sqlvirtualmachine.aio.operations.Operations
:ivar sql_virtual_machine_groups: SqlVirtualMachineGroupsOperations operations
:vartype sql_virtual_machine_groups:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachineGroupsOperations
:ivar sql_virtual_machines: SqlVirtualMachinesOperations operations
:vartype sql_virtual_machines:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachinesOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Subscription ID that identifies an Azure subscription.
:type subscription_id: str
:param base_url: Service URL. Default value is 'https://management.azure.com'.
:type base_url: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = SqlVirtualMachineManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.availability_group_listeners = AvailabilityGroupListenersOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machine_groups = SqlVirtualMachineGroupsOperations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machines = SqlVirtualMachinesOperations(self._client, self._config, self._serialize, self._deserialize)
def _send_request(
self,
request: HttpRequest,
**kwargs: Any
) -> Awaitable[AsyncHttpResponse]:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
async def close(self) -> None:
await self._client.close()
async def __aenter__(self) -> "SqlVirtualMachineManagementClient":
<|fim_middle|>
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)
<|fim▁end|> | await self._client.__aenter__()
return self |
<|file_name|>_sql_virtual_machine_management_client.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import SqlVirtualMachineManagementClientConfiguration
from .operations import AvailabilityGroupListenersOperations, Operations, SqlVirtualMachineGroupsOperations, SqlVirtualMachinesOperations
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class SqlVirtualMachineManagementClient:
"""The SQL virtual machine management API provides a RESTful set of web APIs that interact with Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables users to create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group listener.
:ivar availability_group_listeners: AvailabilityGroupListenersOperations operations
:vartype availability_group_listeners:
azure.mgmt.sqlvirtualmachine.aio.operations.AvailabilityGroupListenersOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.sqlvirtualmachine.aio.operations.Operations
:ivar sql_virtual_machine_groups: SqlVirtualMachineGroupsOperations operations
:vartype sql_virtual_machine_groups:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachineGroupsOperations
:ivar sql_virtual_machines: SqlVirtualMachinesOperations operations
:vartype sql_virtual_machines:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachinesOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Subscription ID that identifies an Azure subscription.
:type subscription_id: str
:param base_url: Service URL. Default value is 'https://management.azure.com'.
:type base_url: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = SqlVirtualMachineManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.availability_group_listeners = AvailabilityGroupListenersOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machine_groups = SqlVirtualMachineGroupsOperations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machines = SqlVirtualMachinesOperations(self._client, self._config, self._serialize, self._deserialize)
def _send_request(
self,
request: HttpRequest,
**kwargs: Any
) -> Awaitable[AsyncHttpResponse]:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
async def close(self) -> None:
await self._client.close()
async def __aenter__(self) -> "SqlVirtualMachineManagementClient":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
<|fim_middle|>
<|fim▁end|> | await self._client.__aexit__(*exc_details) |
<|file_name|>_sql_virtual_machine_management_client.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import SqlVirtualMachineManagementClientConfiguration
from .operations import AvailabilityGroupListenersOperations, Operations, SqlVirtualMachineGroupsOperations, SqlVirtualMachinesOperations
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
<|fim_middle|>
class SqlVirtualMachineManagementClient:
"""The SQL virtual machine management API provides a RESTful set of web APIs that interact with Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables users to create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group listener.
:ivar availability_group_listeners: AvailabilityGroupListenersOperations operations
:vartype availability_group_listeners:
azure.mgmt.sqlvirtualmachine.aio.operations.AvailabilityGroupListenersOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.sqlvirtualmachine.aio.operations.Operations
:ivar sql_virtual_machine_groups: SqlVirtualMachineGroupsOperations operations
:vartype sql_virtual_machine_groups:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachineGroupsOperations
:ivar sql_virtual_machines: SqlVirtualMachinesOperations operations
:vartype sql_virtual_machines:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachinesOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Subscription ID that identifies an Azure subscription.
:type subscription_id: str
:param base_url: Service URL. Default value is 'https://management.azure.com'.
:type base_url: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = SqlVirtualMachineManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.availability_group_listeners = AvailabilityGroupListenersOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machine_groups = SqlVirtualMachineGroupsOperations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machines = SqlVirtualMachinesOperations(self._client, self._config, self._serialize, self._deserialize)
def _send_request(
self,
request: HttpRequest,
**kwargs: Any
) -> Awaitable[AsyncHttpResponse]:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
async def close(self) -> None:
await self._client.close()
async def __aenter__(self) -> "SqlVirtualMachineManagementClient":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)
<|fim▁end|> | from azure.core.credentials_async import AsyncTokenCredential |
<|file_name|>_sql_virtual_machine_management_client.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import SqlVirtualMachineManagementClientConfiguration
from .operations import AvailabilityGroupListenersOperations, Operations, SqlVirtualMachineGroupsOperations, SqlVirtualMachinesOperations
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class SqlVirtualMachineManagementClient:
"""The SQL virtual machine management API provides a RESTful set of web APIs that interact with Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables users to create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group listener.
:ivar availability_group_listeners: AvailabilityGroupListenersOperations operations
:vartype availability_group_listeners:
azure.mgmt.sqlvirtualmachine.aio.operations.AvailabilityGroupListenersOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.sqlvirtualmachine.aio.operations.Operations
:ivar sql_virtual_machine_groups: SqlVirtualMachineGroupsOperations operations
:vartype sql_virtual_machine_groups:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachineGroupsOperations
:ivar sql_virtual_machines: SqlVirtualMachinesOperations operations
:vartype sql_virtual_machines:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachinesOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Subscription ID that identifies an Azure subscription.
:type subscription_id: str
:param base_url: Service URL. Default value is 'https://management.azure.com'.
:type base_url: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def <|fim_middle|>(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = SqlVirtualMachineManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.availability_group_listeners = AvailabilityGroupListenersOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machine_groups = SqlVirtualMachineGroupsOperations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machines = SqlVirtualMachinesOperations(self._client, self._config, self._serialize, self._deserialize)
def _send_request(
self,
request: HttpRequest,
**kwargs: Any
) -> Awaitable[AsyncHttpResponse]:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
async def close(self) -> None:
await self._client.close()
async def __aenter__(self) -> "SqlVirtualMachineManagementClient":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)
<|fim▁end|> | __init__ |
<|file_name|>_sql_virtual_machine_management_client.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import SqlVirtualMachineManagementClientConfiguration
from .operations import AvailabilityGroupListenersOperations, Operations, SqlVirtualMachineGroupsOperations, SqlVirtualMachinesOperations
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class SqlVirtualMachineManagementClient:
"""The SQL virtual machine management API provides a RESTful set of web APIs that interact with Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables users to create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group listener.
:ivar availability_group_listeners: AvailabilityGroupListenersOperations operations
:vartype availability_group_listeners:
azure.mgmt.sqlvirtualmachine.aio.operations.AvailabilityGroupListenersOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.sqlvirtualmachine.aio.operations.Operations
:ivar sql_virtual_machine_groups: SqlVirtualMachineGroupsOperations operations
:vartype sql_virtual_machine_groups:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachineGroupsOperations
:ivar sql_virtual_machines: SqlVirtualMachinesOperations operations
:vartype sql_virtual_machines:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachinesOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Subscription ID that identifies an Azure subscription.
:type subscription_id: str
:param base_url: Service URL. Default value is 'https://management.azure.com'.
:type base_url: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = SqlVirtualMachineManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.availability_group_listeners = AvailabilityGroupListenersOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machine_groups = SqlVirtualMachineGroupsOperations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machines = SqlVirtualMachinesOperations(self._client, self._config, self._serialize, self._deserialize)
def <|fim_middle|>(
self,
request: HttpRequest,
**kwargs: Any
) -> Awaitable[AsyncHttpResponse]:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
async def close(self) -> None:
await self._client.close()
async def __aenter__(self) -> "SqlVirtualMachineManagementClient":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)
<|fim▁end|> | _send_request |
<|file_name|>_sql_virtual_machine_management_client.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import SqlVirtualMachineManagementClientConfiguration
from .operations import AvailabilityGroupListenersOperations, Operations, SqlVirtualMachineGroupsOperations, SqlVirtualMachinesOperations
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class SqlVirtualMachineManagementClient:
"""The SQL virtual machine management API provides a RESTful set of web APIs that interact with Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables users to create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group listener.
:ivar availability_group_listeners: AvailabilityGroupListenersOperations operations
:vartype availability_group_listeners:
azure.mgmt.sqlvirtualmachine.aio.operations.AvailabilityGroupListenersOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.sqlvirtualmachine.aio.operations.Operations
:ivar sql_virtual_machine_groups: SqlVirtualMachineGroupsOperations operations
:vartype sql_virtual_machine_groups:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachineGroupsOperations
:ivar sql_virtual_machines: SqlVirtualMachinesOperations operations
:vartype sql_virtual_machines:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachinesOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Subscription ID that identifies an Azure subscription.
:type subscription_id: str
:param base_url: Service URL. Default value is 'https://management.azure.com'.
:type base_url: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = SqlVirtualMachineManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.availability_group_listeners = AvailabilityGroupListenersOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machine_groups = SqlVirtualMachineGroupsOperations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machines = SqlVirtualMachinesOperations(self._client, self._config, self._serialize, self._deserialize)
def _send_request(
self,
request: HttpRequest,
**kwargs: Any
) -> Awaitable[AsyncHttpResponse]:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
async def <|fim_middle|>(self) -> None:
await self._client.close()
async def __aenter__(self) -> "SqlVirtualMachineManagementClient":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)
<|fim▁end|> | close |
<|file_name|>_sql_virtual_machine_management_client.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import SqlVirtualMachineManagementClientConfiguration
from .operations import AvailabilityGroupListenersOperations, Operations, SqlVirtualMachineGroupsOperations, SqlVirtualMachinesOperations
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class SqlVirtualMachineManagementClient:
"""The SQL virtual machine management API provides a RESTful set of web APIs that interact with Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables users to create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group listener.
:ivar availability_group_listeners: AvailabilityGroupListenersOperations operations
:vartype availability_group_listeners:
azure.mgmt.sqlvirtualmachine.aio.operations.AvailabilityGroupListenersOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.sqlvirtualmachine.aio.operations.Operations
:ivar sql_virtual_machine_groups: SqlVirtualMachineGroupsOperations operations
:vartype sql_virtual_machine_groups:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachineGroupsOperations
:ivar sql_virtual_machines: SqlVirtualMachinesOperations operations
:vartype sql_virtual_machines:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachinesOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Subscription ID that identifies an Azure subscription.
:type subscription_id: str
:param base_url: Service URL. Default value is 'https://management.azure.com'.
:type base_url: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = SqlVirtualMachineManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.availability_group_listeners = AvailabilityGroupListenersOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machine_groups = SqlVirtualMachineGroupsOperations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machines = SqlVirtualMachinesOperations(self._client, self._config, self._serialize, self._deserialize)
def _send_request(
self,
request: HttpRequest,
**kwargs: Any
) -> Awaitable[AsyncHttpResponse]:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
async def close(self) -> None:
await self._client.close()
async def <|fim_middle|>(self) -> "SqlVirtualMachineManagementClient":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)
<|fim▁end|> | __aenter__ |
<|file_name|>_sql_virtual_machine_management_client.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.mgmt.core import AsyncARMPipelineClient
from msrest import Deserializer, Serializer
from .. import models
from ._configuration import SqlVirtualMachineManagementClientConfiguration
from .operations import AvailabilityGroupListenersOperations, Operations, SqlVirtualMachineGroupsOperations, SqlVirtualMachinesOperations
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class SqlVirtualMachineManagementClient:
"""The SQL virtual machine management API provides a RESTful set of web APIs that interact with Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables users to create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group listener.
:ivar availability_group_listeners: AvailabilityGroupListenersOperations operations
:vartype availability_group_listeners:
azure.mgmt.sqlvirtualmachine.aio.operations.AvailabilityGroupListenersOperations
:ivar operations: Operations operations
:vartype operations: azure.mgmt.sqlvirtualmachine.aio.operations.Operations
:ivar sql_virtual_machine_groups: SqlVirtualMachineGroupsOperations operations
:vartype sql_virtual_machine_groups:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachineGroupsOperations
:ivar sql_virtual_machines: SqlVirtualMachinesOperations operations
:vartype sql_virtual_machines:
azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachinesOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Subscription ID that identifies an Azure subscription.
:type subscription_id: str
:param base_url: Service URL. Default value is 'https://management.azure.com'.
:type base_url: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = SqlVirtualMachineManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.availability_group_listeners = AvailabilityGroupListenersOperations(self._client, self._config, self._serialize, self._deserialize)
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machine_groups = SqlVirtualMachineGroupsOperations(self._client, self._config, self._serialize, self._deserialize)
self.sql_virtual_machines = SqlVirtualMachinesOperations(self._client, self._config, self._serialize, self._deserialize)
def _send_request(
self,
request: HttpRequest,
**kwargs: Any
) -> Awaitable[AsyncHttpResponse]:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = await client._send_request(request)
<AsyncHttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.AsyncHttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
async def close(self) -> None:
await self._client.close()
async def __aenter__(self) -> "SqlVirtualMachineManagementClient":
await self._client.__aenter__()
return self
async def <|fim_middle|>(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)
<|fim▁end|> | __aexit__ |
<|file_name|>test_convert.py<|end_file_name|><|fim▁begin|>#
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""File format specific behavior."""
from weblate.formats.convert import (
HTMLFormat,
IDMLFormat,
OpenDocumentFormat,
PlainTextFormat,
WindowsRCFormat,
)
from weblate.formats.helpers import BytesIOMode
from weblate.formats.tests.test_formats import AutoFormatTest
from weblate.trans.tests.utils import get_test_file
IDML_FILE = get_test_file("en.idml")
HTML_FILE = get_test_file("cs.html")
OPENDOCUMENT_FILE = get_test_file("cs.odt")
TEST_RC = get_test_file("cs-CZ.rc")
TEST_TXT = get_test_file("cs.txt")
class ConvertFormatTest(AutoFormatTest):
NEW_UNIT_MATCH = None
EXPECTED_FLAGS = ""
def parse_file(self, filename):
return self.FORMAT(filename, template_store=self.FORMAT(filename))
<|fim▁hole|>class HTMLFormatTest(ConvertFormatTest):
FORMAT = HTMLFormat
FILE = HTML_FILE
MIME = "text/html"
EXT = "html"
COUNT = 5
MASK = "*/translations.html"
EXPECTED_PATH = "cs_CZ/translations.html"
FIND_CONTEXT = "+html.body.p:5-1"
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"<body>"
NEW_UNIT_MATCH = None
BASE = HTML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
class OpenDocumentFormatTest(ConvertFormatTest):
FORMAT = OpenDocumentFormat
FILE = OPENDOCUMENT_FILE
MIME = "application/vnd.oasis.opendocument.text"
EXT = "odt"
COUNT = 4
MASK = "*/translations.odt"
EXPECTED_PATH = "cs_CZ/translations.odt"
FIND_CONTEXT = (
"odf///office:document-content[0]/office:body[0]/office:text[0]/text:p[1]"
)
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = OPENDOCUMENT_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
OpenDocumentFormat.convertfile(BytesIOMode("test.odt", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class IDMLFormatTest(ConvertFormatTest):
FORMAT = IDMLFormat
FILE = IDML_FILE
MIME = "application/octet-stream"
EXT = "idml"
COUNT = 6
MASK = "*/translations.idml"
EXPECTED_PATH = "cs_CZ/translations.idml"
FIND_CONTEXT = (
"idPkg:Story[0]/{}Story[0]/{}XMLElement[0]/{}ParagraphStyleRange[0]"
"Stories/Story_mainmainmainmainmainmainmainmainmainmainmainu188.xml"
)
FIND_MATCH = """<g id="0"><g id="1">THE HEADLINE HERE</g></g>"""
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = IDML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
IDMLFormat.convertfile(BytesIOMode("test.idml", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class WindowsRCFormatTest(ConvertFormatTest):
FORMAT = WindowsRCFormat
FILE = TEST_RC
BASE = TEST_RC
MIME = "text/plain"
EXT = "rc"
COUNT = 5
MASK = "rc/*.rc"
EXPECTED_PATH = "rc/cs-CZ.rc"
MATCH = "STRINGTABLE"
FIND_CONTEXT = "STRINGTABLE.IDS_MSG1"
FIND_MATCH = "Hello, world!\n"
EDIT_OFFSET = 1
class PlainTextFormatTest(ConvertFormatTest):
FORMAT = PlainTextFormat
FILE = TEST_TXT
BASE = TEST_TXT
MIME = "text/plain"
EXT = "txt"
COUNT = 5
MASK = "txt/*.txt"
EXPECTED_PATH = "txt/cs_CZ.txt"
MATCH = "Hello"
FIND_CONTEXT = "cs.txt:2"
FIND_MATCH = "Hello, world!"
EDIT_OFFSET = 1<|fim▁end|> | |
<|file_name|>test_convert.py<|end_file_name|><|fim▁begin|>#
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""File format specific behavior."""
from weblate.formats.convert import (
HTMLFormat,
IDMLFormat,
OpenDocumentFormat,
PlainTextFormat,
WindowsRCFormat,
)
from weblate.formats.helpers import BytesIOMode
from weblate.formats.tests.test_formats import AutoFormatTest
from weblate.trans.tests.utils import get_test_file
IDML_FILE = get_test_file("en.idml")
HTML_FILE = get_test_file("cs.html")
OPENDOCUMENT_FILE = get_test_file("cs.odt")
TEST_RC = get_test_file("cs-CZ.rc")
TEST_TXT = get_test_file("cs.txt")
class ConvertFormatTest(AutoFormatTest):
NEW_U<|fim_middle|>
ass HTMLFormatTest(ConvertFormatTest):
FORMAT = HTMLFormat
FILE = HTML_FILE
MIME = "text/html"
EXT = "html"
COUNT = 5
MASK = "*/translations.html"
EXPECTED_PATH = "cs_CZ/translations.html"
FIND_CONTEXT = "+html.body.p:5-1"
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"<body>"
NEW_UNIT_MATCH = None
BASE = HTML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
class OpenDocumentFormatTest(ConvertFormatTest):
FORMAT = OpenDocumentFormat
FILE = OPENDOCUMENT_FILE
MIME = "application/vnd.oasis.opendocument.text"
EXT = "odt"
COUNT = 4
MASK = "*/translations.odt"
EXPECTED_PATH = "cs_CZ/translations.odt"
FIND_CONTEXT = (
"odf///office:document-content[0]/office:body[0]/office:text[0]/text:p[1]"
)
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = OPENDOCUMENT_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
OpenDocumentFormat.convertfile(BytesIOMode("test.odt", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class IDMLFormatTest(ConvertFormatTest):
FORMAT = IDMLFormat
FILE = IDML_FILE
MIME = "application/octet-stream"
EXT = "idml"
COUNT = 6
MASK = "*/translations.idml"
EXPECTED_PATH = "cs_CZ/translations.idml"
FIND_CONTEXT = (
"idPkg:Story[0]/{}Story[0]/{}XMLElement[0]/{}ParagraphStyleRange[0]"
"Stories/Story_mainmainmainmainmainmainmainmainmainmainmainu188.xml"
)
FIND_MATCH = """<g id="0"><g id="1">THE HEADLINE HERE</g></g>"""
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = IDML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
IDMLFormat.convertfile(BytesIOMode("test.idml", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class WindowsRCFormatTest(ConvertFormatTest):
FORMAT = WindowsRCFormat
FILE = TEST_RC
BASE = TEST_RC
MIME = "text/plain"
EXT = "rc"
COUNT = 5
MASK = "rc/*.rc"
EXPECTED_PATH = "rc/cs-CZ.rc"
MATCH = "STRINGTABLE"
FIND_CONTEXT = "STRINGTABLE.IDS_MSG1"
FIND_MATCH = "Hello, world!\n"
EDIT_OFFSET = 1
class PlainTextFormatTest(ConvertFormatTest):
FORMAT = PlainTextFormat
FILE = TEST_TXT
BASE = TEST_TXT
MIME = "text/plain"
EXT = "txt"
COUNT = 5
MASK = "txt/*.txt"
EXPECTED_PATH = "txt/cs_CZ.txt"
MATCH = "Hello"
FIND_CONTEXT = "cs.txt:2"
FIND_MATCH = "Hello, world!"
EDIT_OFFSET = 1
<|fim▁end|> | NIT_MATCH = None
EXPECTED_FLAGS = ""
def parse_file(self, filename):
return self.FORMAT(filename, template_store=self.FORMAT(filename))
cl |
<|file_name|>test_convert.py<|end_file_name|><|fim▁begin|>#
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""File format specific behavior."""
from weblate.formats.convert import (
HTMLFormat,
IDMLFormat,
OpenDocumentFormat,
PlainTextFormat,
WindowsRCFormat,
)
from weblate.formats.helpers import BytesIOMode
from weblate.formats.tests.test_formats import AutoFormatTest
from weblate.trans.tests.utils import get_test_file
IDML_FILE = get_test_file("en.idml")
HTML_FILE = get_test_file("cs.html")
OPENDOCUMENT_FILE = get_test_file("cs.odt")
TEST_RC = get_test_file("cs-CZ.rc")
TEST_TXT = get_test_file("cs.txt")
class ConvertFormatTest(AutoFormatTest):
NEW_UNIT_MATCH = None
EXPECTED_FLAGS = ""
def parse_file(self, filename):
retur<|fim_middle|>
ass HTMLFormatTest(ConvertFormatTest):
FORMAT = HTMLFormat
FILE = HTML_FILE
MIME = "text/html"
EXT = "html"
COUNT = 5
MASK = "*/translations.html"
EXPECTED_PATH = "cs_CZ/translations.html"
FIND_CONTEXT = "+html.body.p:5-1"
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"<body>"
NEW_UNIT_MATCH = None
BASE = HTML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
class OpenDocumentFormatTest(ConvertFormatTest):
FORMAT = OpenDocumentFormat
FILE = OPENDOCUMENT_FILE
MIME = "application/vnd.oasis.opendocument.text"
EXT = "odt"
COUNT = 4
MASK = "*/translations.odt"
EXPECTED_PATH = "cs_CZ/translations.odt"
FIND_CONTEXT = (
"odf///office:document-content[0]/office:body[0]/office:text[0]/text:p[1]"
)
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = OPENDOCUMENT_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
OpenDocumentFormat.convertfile(BytesIOMode("test.odt", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class IDMLFormatTest(ConvertFormatTest):
FORMAT = IDMLFormat
FILE = IDML_FILE
MIME = "application/octet-stream"
EXT = "idml"
COUNT = 6
MASK = "*/translations.idml"
EXPECTED_PATH = "cs_CZ/translations.idml"
FIND_CONTEXT = (
"idPkg:Story[0]/{}Story[0]/{}XMLElement[0]/{}ParagraphStyleRange[0]"
"Stories/Story_mainmainmainmainmainmainmainmainmainmainmainu188.xml"
)
FIND_MATCH = """<g id="0"><g id="1">THE HEADLINE HERE</g></g>"""
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = IDML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
IDMLFormat.convertfile(BytesIOMode("test.idml", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class WindowsRCFormatTest(ConvertFormatTest):
FORMAT = WindowsRCFormat
FILE = TEST_RC
BASE = TEST_RC
MIME = "text/plain"
EXT = "rc"
COUNT = 5
MASK = "rc/*.rc"
EXPECTED_PATH = "rc/cs-CZ.rc"
MATCH = "STRINGTABLE"
FIND_CONTEXT = "STRINGTABLE.IDS_MSG1"
FIND_MATCH = "Hello, world!\n"
EDIT_OFFSET = 1
class PlainTextFormatTest(ConvertFormatTest):
FORMAT = PlainTextFormat
FILE = TEST_TXT
BASE = TEST_TXT
MIME = "text/plain"
EXT = "txt"
COUNT = 5
MASK = "txt/*.txt"
EXPECTED_PATH = "txt/cs_CZ.txt"
MATCH = "Hello"
FIND_CONTEXT = "cs.txt:2"
FIND_MATCH = "Hello, world!"
EDIT_OFFSET = 1
<|fim▁end|> | n self.FORMAT(filename, template_store=self.FORMAT(filename))
cl |
<|file_name|>test_convert.py<|end_file_name|><|fim▁begin|>#
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""File format specific behavior."""
from weblate.formats.convert import (
HTMLFormat,
IDMLFormat,
OpenDocumentFormat,
PlainTextFormat,
WindowsRCFormat,
)
from weblate.formats.helpers import BytesIOMode
from weblate.formats.tests.test_formats import AutoFormatTest
from weblate.trans.tests.utils import get_test_file
IDML_FILE = get_test_file("en.idml")
HTML_FILE = get_test_file("cs.html")
OPENDOCUMENT_FILE = get_test_file("cs.odt")
TEST_RC = get_test_file("cs-CZ.rc")
TEST_TXT = get_test_file("cs.txt")
class ConvertFormatTest(AutoFormatTest):
NEW_UNIT_MATCH = None
EXPECTED_FLAGS = ""
def parse_file(self, filename):
return self.FORMAT(filename, template_store=self.FORMAT(filename))
class HTMLFormatTest(ConvertFormatTest):
FORMA<|fim_middle|>
ass OpenDocumentFormatTest(ConvertFormatTest):
FORMAT = OpenDocumentFormat
FILE = OPENDOCUMENT_FILE
MIME = "application/vnd.oasis.opendocument.text"
EXT = "odt"
COUNT = 4
MASK = "*/translations.odt"
EXPECTED_PATH = "cs_CZ/translations.odt"
FIND_CONTEXT = (
"odf///office:document-content[0]/office:body[0]/office:text[0]/text:p[1]"
)
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = OPENDOCUMENT_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
OpenDocumentFormat.convertfile(BytesIOMode("test.odt", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class IDMLFormatTest(ConvertFormatTest):
FORMAT = IDMLFormat
FILE = IDML_FILE
MIME = "application/octet-stream"
EXT = "idml"
COUNT = 6
MASK = "*/translations.idml"
EXPECTED_PATH = "cs_CZ/translations.idml"
FIND_CONTEXT = (
"idPkg:Story[0]/{}Story[0]/{}XMLElement[0]/{}ParagraphStyleRange[0]"
"Stories/Story_mainmainmainmainmainmainmainmainmainmainmainu188.xml"
)
FIND_MATCH = """<g id="0"><g id="1">THE HEADLINE HERE</g></g>"""
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = IDML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
IDMLFormat.convertfile(BytesIOMode("test.idml", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class WindowsRCFormatTest(ConvertFormatTest):
FORMAT = WindowsRCFormat
FILE = TEST_RC
BASE = TEST_RC
MIME = "text/plain"
EXT = "rc"
COUNT = 5
MASK = "rc/*.rc"
EXPECTED_PATH = "rc/cs-CZ.rc"
MATCH = "STRINGTABLE"
FIND_CONTEXT = "STRINGTABLE.IDS_MSG1"
FIND_MATCH = "Hello, world!\n"
EDIT_OFFSET = 1
class PlainTextFormatTest(ConvertFormatTest):
FORMAT = PlainTextFormat
FILE = TEST_TXT
BASE = TEST_TXT
MIME = "text/plain"
EXT = "txt"
COUNT = 5
MASK = "txt/*.txt"
EXPECTED_PATH = "txt/cs_CZ.txt"
MATCH = "Hello"
FIND_CONTEXT = "cs.txt:2"
FIND_MATCH = "Hello, world!"
EDIT_OFFSET = 1
<|fim▁end|> | T = HTMLFormat
FILE = HTML_FILE
MIME = "text/html"
EXT = "html"
COUNT = 5
MASK = "*/translations.html"
EXPECTED_PATH = "cs_CZ/translations.html"
FIND_CONTEXT = "+html.body.p:5-1"
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"<body>"
NEW_UNIT_MATCH = None
BASE = HTML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
cl |
<|file_name|>test_convert.py<|end_file_name|><|fim▁begin|>#
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""File format specific behavior."""
from weblate.formats.convert import (
HTMLFormat,
IDMLFormat,
OpenDocumentFormat,
PlainTextFormat,
WindowsRCFormat,
)
from weblate.formats.helpers import BytesIOMode
from weblate.formats.tests.test_formats import AutoFormatTest
from weblate.trans.tests.utils import get_test_file
IDML_FILE = get_test_file("en.idml")
HTML_FILE = get_test_file("cs.html")
OPENDOCUMENT_FILE = get_test_file("cs.odt")
TEST_RC = get_test_file("cs-CZ.rc")
TEST_TXT = get_test_file("cs.txt")
class ConvertFormatTest(AutoFormatTest):
NEW_UNIT_MATCH = None
EXPECTED_FLAGS = ""
def parse_file(self, filename):
return self.FORMAT(filename, template_store=self.FORMAT(filename))
class HTMLFormatTest(ConvertFormatTest):
FORMAT = HTMLFormat
FILE = HTML_FILE
MIME = "text/html"
EXT = "html"
COUNT = 5
MASK = "*/translations.html"
EXPECTED_PATH = "cs_CZ/translations.html"
FIND_CONTEXT = "+html.body.p:5-1"
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"<body>"
NEW_UNIT_MATCH = None
BASE = HTML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
class OpenDocumentFormatTest(ConvertFormatTest):
FORMA<|fim_middle|>
ass IDMLFormatTest(ConvertFormatTest):
FORMAT = IDMLFormat
FILE = IDML_FILE
MIME = "application/octet-stream"
EXT = "idml"
COUNT = 6
MASK = "*/translations.idml"
EXPECTED_PATH = "cs_CZ/translations.idml"
FIND_CONTEXT = (
"idPkg:Story[0]/{}Story[0]/{}XMLElement[0]/{}ParagraphStyleRange[0]"
"Stories/Story_mainmainmainmainmainmainmainmainmainmainmainu188.xml"
)
FIND_MATCH = """<g id="0"><g id="1">THE HEADLINE HERE</g></g>"""
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = IDML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
IDMLFormat.convertfile(BytesIOMode("test.idml", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class WindowsRCFormatTest(ConvertFormatTest):
FORMAT = WindowsRCFormat
FILE = TEST_RC
BASE = TEST_RC
MIME = "text/plain"
EXT = "rc"
COUNT = 5
MASK = "rc/*.rc"
EXPECTED_PATH = "rc/cs-CZ.rc"
MATCH = "STRINGTABLE"
FIND_CONTEXT = "STRINGTABLE.IDS_MSG1"
FIND_MATCH = "Hello, world!\n"
EDIT_OFFSET = 1
class PlainTextFormatTest(ConvertFormatTest):
FORMAT = PlainTextFormat
FILE = TEST_TXT
BASE = TEST_TXT
MIME = "text/plain"
EXT = "txt"
COUNT = 5
MASK = "txt/*.txt"
EXPECTED_PATH = "txt/cs_CZ.txt"
MATCH = "Hello"
FIND_CONTEXT = "cs.txt:2"
FIND_MATCH = "Hello, world!"
EDIT_OFFSET = 1
<|fim▁end|> | T = OpenDocumentFormat
FILE = OPENDOCUMENT_FILE
MIME = "application/vnd.oasis.opendocument.text"
EXT = "odt"
COUNT = 4
MASK = "*/translations.odt"
EXPECTED_PATH = "cs_CZ/translations.odt"
FIND_CONTEXT = (
"odf///office:document-content[0]/office:body[0]/office:text[0]/text:p[1]"
)
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = OPENDOCUMENT_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
OpenDocumentFormat.convertfile(BytesIOMode("test.odt", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
cl |
<|file_name|>test_convert.py<|end_file_name|><|fim▁begin|>#
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""File format specific behavior."""
from weblate.formats.convert import (
HTMLFormat,
IDMLFormat,
OpenDocumentFormat,
PlainTextFormat,
WindowsRCFormat,
)
from weblate.formats.helpers import BytesIOMode
from weblate.formats.tests.test_formats import AutoFormatTest
from weblate.trans.tests.utils import get_test_file
IDML_FILE = get_test_file("en.idml")
HTML_FILE = get_test_file("cs.html")
OPENDOCUMENT_FILE = get_test_file("cs.odt")
TEST_RC = get_test_file("cs-CZ.rc")
TEST_TXT = get_test_file("cs.txt")
class ConvertFormatTest(AutoFormatTest):
NEW_UNIT_MATCH = None
EXPECTED_FLAGS = ""
def parse_file(self, filename):
return self.FORMAT(filename, template_store=self.FORMAT(filename))
class HTMLFormatTest(ConvertFormatTest):
FORMAT = HTMLFormat
FILE = HTML_FILE
MIME = "text/html"
EXT = "html"
COUNT = 5
MASK = "*/translations.html"
EXPECTED_PATH = "cs_CZ/translations.html"
FIND_CONTEXT = "+html.body.p:5-1"
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"<body>"
NEW_UNIT_MATCH = None
BASE = HTML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
class OpenDocumentFormatTest(ConvertFormatTest):
FORMAT = OpenDocumentFormat
FILE = OPENDOCUMENT_FILE
MIME = "application/vnd.oasis.opendocument.text"
EXT = "odt"
COUNT = 4
MASK = "*/translations.odt"
EXPECTED_PATH = "cs_CZ/translations.odt"
FIND_CONTEXT = (
"odf///office:document-content[0]/office:body[0]/office:text[0]/text:p[1]"
)
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = OPENDOCUMENT_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
retur<|fim_middle|>
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class IDMLFormatTest(ConvertFormatTest):
FORMAT = IDMLFormat
FILE = IDML_FILE
MIME = "application/octet-stream"
EXT = "idml"
COUNT = 6
MASK = "*/translations.idml"
EXPECTED_PATH = "cs_CZ/translations.idml"
FIND_CONTEXT = (
"idPkg:Story[0]/{}Story[0]/{}XMLElement[0]/{}ParagraphStyleRange[0]"
"Stories/Story_mainmainmainmainmainmainmainmainmainmainmainu188.xml"
)
FIND_MATCH = """<g id="0"><g id="1">THE HEADLINE HERE</g></g>"""
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = IDML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
IDMLFormat.convertfile(BytesIOMode("test.idml", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class WindowsRCFormatTest(ConvertFormatTest):
FORMAT = WindowsRCFormat
FILE = TEST_RC
BASE = TEST_RC
MIME = "text/plain"
EXT = "rc"
COUNT = 5
MASK = "rc/*.rc"
EXPECTED_PATH = "rc/cs-CZ.rc"
MATCH = "STRINGTABLE"
FIND_CONTEXT = "STRINGTABLE.IDS_MSG1"
FIND_MATCH = "Hello, world!\n"
EDIT_OFFSET = 1
class PlainTextFormatTest(ConvertFormatTest):
FORMAT = PlainTextFormat
FILE = TEST_TXT
BASE = TEST_TXT
MIME = "text/plain"
EXT = "txt"
COUNT = 5
MASK = "txt/*.txt"
EXPECTED_PATH = "txt/cs_CZ.txt"
MATCH = "Hello"
FIND_CONTEXT = "cs.txt:2"
FIND_MATCH = "Hello, world!"
EDIT_OFFSET = 1
<|fim▁end|> | n bytes(
OpenDocumentFormat.convertfile(BytesIOMode("test.odt", content), None)
).decode()
|
<|file_name|>test_convert.py<|end_file_name|><|fim▁begin|>#
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""File format specific behavior."""
from weblate.formats.convert import (
HTMLFormat,
IDMLFormat,
OpenDocumentFormat,
PlainTextFormat,
WindowsRCFormat,
)
from weblate.formats.helpers import BytesIOMode
from weblate.formats.tests.test_formats import AutoFormatTest
from weblate.trans.tests.utils import get_test_file
IDML_FILE = get_test_file("en.idml")
HTML_FILE = get_test_file("cs.html")
OPENDOCUMENT_FILE = get_test_file("cs.odt")
TEST_RC = get_test_file("cs-CZ.rc")
TEST_TXT = get_test_file("cs.txt")
class ConvertFormatTest(AutoFormatTest):
NEW_UNIT_MATCH = None
EXPECTED_FLAGS = ""
def parse_file(self, filename):
return self.FORMAT(filename, template_store=self.FORMAT(filename))
class HTMLFormatTest(ConvertFormatTest):
FORMAT = HTMLFormat
FILE = HTML_FILE
MIME = "text/html"
EXT = "html"
COUNT = 5
MASK = "*/translations.html"
EXPECTED_PATH = "cs_CZ/translations.html"
FIND_CONTEXT = "+html.body.p:5-1"
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"<body>"
NEW_UNIT_MATCH = None
BASE = HTML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
class OpenDocumentFormatTest(ConvertFormatTest):
FORMAT = OpenDocumentFormat
FILE = OPENDOCUMENT_FILE
MIME = "application/vnd.oasis.opendocument.text"
EXT = "odt"
COUNT = 4
MASK = "*/translations.odt"
EXPECTED_PATH = "cs_CZ/translations.odt"
FIND_CONTEXT = (
"odf///office:document-content[0]/office:body[0]/office:text[0]/text:p[1]"
)
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = OPENDOCUMENT_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
OpenDocumentFormat.convertfile(BytesIOMode("test.odt", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.<|fim_middle|>
ass IDMLFormatTest(ConvertFormatTest):
FORMAT = IDMLFormat
FILE = IDML_FILE
MIME = "application/octet-stream"
EXT = "idml"
COUNT = 6
MASK = "*/translations.idml"
EXPECTED_PATH = "cs_CZ/translations.idml"
FIND_CONTEXT = (
"idPkg:Story[0]/{}Story[0]/{}XMLElement[0]/{}ParagraphStyleRange[0]"
"Stories/Story_mainmainmainmainmainmainmainmainmainmainmainu188.xml"
)
FIND_MATCH = """<g id="0"><g id="1">THE HEADLINE HERE</g></g>"""
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = IDML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
IDMLFormat.convertfile(BytesIOMode("test.idml", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class WindowsRCFormatTest(ConvertFormatTest):
FORMAT = WindowsRCFormat
FILE = TEST_RC
BASE = TEST_RC
MIME = "text/plain"
EXT = "rc"
COUNT = 5
MASK = "rc/*.rc"
EXPECTED_PATH = "rc/cs-CZ.rc"
MATCH = "STRINGTABLE"
FIND_CONTEXT = "STRINGTABLE.IDS_MSG1"
FIND_MATCH = "Hello, world!\n"
EDIT_OFFSET = 1
class PlainTextFormatTest(ConvertFormatTest):
FORMAT = PlainTextFormat
FILE = TEST_TXT
BASE = TEST_TXT
MIME = "text/plain"
EXT = "txt"
COUNT = 5
MASK = "txt/*.txt"
EXPECTED_PATH = "txt/cs_CZ.txt"
MATCH = "Hello"
FIND_CONTEXT = "cs.txt:2"
FIND_MATCH = "Hello, world!"
EDIT_OFFSET = 1
<|fim▁end|> | assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
cl |
<|file_name|>test_convert.py<|end_file_name|><|fim▁begin|>#
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""File format specific behavior."""
from weblate.formats.convert import (
HTMLFormat,
IDMLFormat,
OpenDocumentFormat,
PlainTextFormat,
WindowsRCFormat,
)
from weblate.formats.helpers import BytesIOMode
from weblate.formats.tests.test_formats import AutoFormatTest
from weblate.trans.tests.utils import get_test_file
IDML_FILE = get_test_file("en.idml")
HTML_FILE = get_test_file("cs.html")
OPENDOCUMENT_FILE = get_test_file("cs.odt")
TEST_RC = get_test_file("cs-CZ.rc")
TEST_TXT = get_test_file("cs.txt")
class ConvertFormatTest(AutoFormatTest):
NEW_UNIT_MATCH = None
EXPECTED_FLAGS = ""
def parse_file(self, filename):
return self.FORMAT(filename, template_store=self.FORMAT(filename))
class HTMLFormatTest(ConvertFormatTest):
FORMAT = HTMLFormat
FILE = HTML_FILE
MIME = "text/html"
EXT = "html"
COUNT = 5
MASK = "*/translations.html"
EXPECTED_PATH = "cs_CZ/translations.html"
FIND_CONTEXT = "+html.body.p:5-1"
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"<body>"
NEW_UNIT_MATCH = None
BASE = HTML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
class OpenDocumentFormatTest(ConvertFormatTest):
FORMAT = OpenDocumentFormat
FILE = OPENDOCUMENT_FILE
MIME = "application/vnd.oasis.opendocument.text"
EXT = "odt"
COUNT = 4
MASK = "*/translations.odt"
EXPECTED_PATH = "cs_CZ/translations.odt"
FIND_CONTEXT = (
"odf///office:document-content[0]/office:body[0]/office:text[0]/text:p[1]"
)
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = OPENDOCUMENT_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
OpenDocumentFormat.convertfile(BytesIOMode("test.odt", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class IDMLFormatTest(ConvertFormatTest):
FORMA<|fim_middle|>
ass WindowsRCFormatTest(ConvertFormatTest):
FORMAT = WindowsRCFormat
FILE = TEST_RC
BASE = TEST_RC
MIME = "text/plain"
EXT = "rc"
COUNT = 5
MASK = "rc/*.rc"
EXPECTED_PATH = "rc/cs-CZ.rc"
MATCH = "STRINGTABLE"
FIND_CONTEXT = "STRINGTABLE.IDS_MSG1"
FIND_MATCH = "Hello, world!\n"
EDIT_OFFSET = 1
class PlainTextFormatTest(ConvertFormatTest):
FORMAT = PlainTextFormat
FILE = TEST_TXT
BASE = TEST_TXT
MIME = "text/plain"
EXT = "txt"
COUNT = 5
MASK = "txt/*.txt"
EXPECTED_PATH = "txt/cs_CZ.txt"
MATCH = "Hello"
FIND_CONTEXT = "cs.txt:2"
FIND_MATCH = "Hello, world!"
EDIT_OFFSET = 1
<|fim▁end|> | T = IDMLFormat
FILE = IDML_FILE
MIME = "application/octet-stream"
EXT = "idml"
COUNT = 6
MASK = "*/translations.idml"
EXPECTED_PATH = "cs_CZ/translations.idml"
FIND_CONTEXT = (
"idPkg:Story[0]/{}Story[0]/{}XMLElement[0]/{}ParagraphStyleRange[0]"
"Stories/Story_mainmainmainmainmainmainmainmainmainmainmainu188.xml"
)
FIND_MATCH = """<g id="0"><g id="1">THE HEADLINE HERE</g></g>"""
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = IDML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
IDMLFormat.convertfile(BytesIOMode("test.idml", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
cl |
<|file_name|>test_convert.py<|end_file_name|><|fim▁begin|>#
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""File format specific behavior."""
from weblate.formats.convert import (
HTMLFormat,
IDMLFormat,
OpenDocumentFormat,
PlainTextFormat,
WindowsRCFormat,
)
from weblate.formats.helpers import BytesIOMode
from weblate.formats.tests.test_formats import AutoFormatTest
from weblate.trans.tests.utils import get_test_file
IDML_FILE = get_test_file("en.idml")
HTML_FILE = get_test_file("cs.html")
OPENDOCUMENT_FILE = get_test_file("cs.odt")
TEST_RC = get_test_file("cs-CZ.rc")
TEST_TXT = get_test_file("cs.txt")
class ConvertFormatTest(AutoFormatTest):
NEW_UNIT_MATCH = None
EXPECTED_FLAGS = ""
def parse_file(self, filename):
return self.FORMAT(filename, template_store=self.FORMAT(filename))
class HTMLFormatTest(ConvertFormatTest):
FORMAT = HTMLFormat
FILE = HTML_FILE
MIME = "text/html"
EXT = "html"
COUNT = 5
MASK = "*/translations.html"
EXPECTED_PATH = "cs_CZ/translations.html"
FIND_CONTEXT = "+html.body.p:5-1"
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"<body>"
NEW_UNIT_MATCH = None
BASE = HTML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
class OpenDocumentFormatTest(ConvertFormatTest):
FORMAT = OpenDocumentFormat
FILE = OPENDOCUMENT_FILE
MIME = "application/vnd.oasis.opendocument.text"
EXT = "odt"
COUNT = 4
MASK = "*/translations.odt"
EXPECTED_PATH = "cs_CZ/translations.odt"
FIND_CONTEXT = (
"odf///office:document-content[0]/office:body[0]/office:text[0]/text:p[1]"
)
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = OPENDOCUMENT_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
OpenDocumentFormat.convertfile(BytesIOMode("test.odt", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class IDMLFormatTest(ConvertFormatTest):
FORMAT = IDMLFormat
FILE = IDML_FILE
MIME = "application/octet-stream"
EXT = "idml"
COUNT = 6
MASK = "*/translations.idml"
EXPECTED_PATH = "cs_CZ/translations.idml"
FIND_CONTEXT = (
"idPkg:Story[0]/{}Story[0]/{}XMLElement[0]/{}ParagraphStyleRange[0]"
"Stories/Story_mainmainmainmainmainmainmainmainmainmainmainu188.xml"
)
FIND_MATCH = """<g id="0"><g id="1">THE HEADLINE HERE</g></g>"""
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = IDML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
retur<|fim_middle|>
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class WindowsRCFormatTest(ConvertFormatTest):
FORMAT = WindowsRCFormat
FILE = TEST_RC
BASE = TEST_RC
MIME = "text/plain"
EXT = "rc"
COUNT = 5
MASK = "rc/*.rc"
EXPECTED_PATH = "rc/cs-CZ.rc"
MATCH = "STRINGTABLE"
FIND_CONTEXT = "STRINGTABLE.IDS_MSG1"
FIND_MATCH = "Hello, world!\n"
EDIT_OFFSET = 1
class PlainTextFormatTest(ConvertFormatTest):
FORMAT = PlainTextFormat
FILE = TEST_TXT
BASE = TEST_TXT
MIME = "text/plain"
EXT = "txt"
COUNT = 5
MASK = "txt/*.txt"
EXPECTED_PATH = "txt/cs_CZ.txt"
MATCH = "Hello"
FIND_CONTEXT = "cs.txt:2"
FIND_MATCH = "Hello, world!"
EDIT_OFFSET = 1
<|fim▁end|> | n bytes(
IDMLFormat.convertfile(BytesIOMode("test.idml", content), None)
).decode()
|
<|file_name|>test_convert.py<|end_file_name|><|fim▁begin|>#
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""File format specific behavior."""
from weblate.formats.convert import (
HTMLFormat,
IDMLFormat,
OpenDocumentFormat,
PlainTextFormat,
WindowsRCFormat,
)
from weblate.formats.helpers import BytesIOMode
from weblate.formats.tests.test_formats import AutoFormatTest
from weblate.trans.tests.utils import get_test_file
IDML_FILE = get_test_file("en.idml")
HTML_FILE = get_test_file("cs.html")
OPENDOCUMENT_FILE = get_test_file("cs.odt")
TEST_RC = get_test_file("cs-CZ.rc")
TEST_TXT = get_test_file("cs.txt")
class ConvertFormatTest(AutoFormatTest):
NEW_UNIT_MATCH = None
EXPECTED_FLAGS = ""
def parse_file(self, filename):
return self.FORMAT(filename, template_store=self.FORMAT(filename))
class HTMLFormatTest(ConvertFormatTest):
FORMAT = HTMLFormat
FILE = HTML_FILE
MIME = "text/html"
EXT = "html"
COUNT = 5
MASK = "*/translations.html"
EXPECTED_PATH = "cs_CZ/translations.html"
FIND_CONTEXT = "+html.body.p:5-1"
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"<body>"
NEW_UNIT_MATCH = None
BASE = HTML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
class OpenDocumentFormatTest(ConvertFormatTest):
FORMAT = OpenDocumentFormat
FILE = OPENDOCUMENT_FILE
MIME = "application/vnd.oasis.opendocument.text"
EXT = "odt"
COUNT = 4
MASK = "*/translations.odt"
EXPECTED_PATH = "cs_CZ/translations.odt"
FIND_CONTEXT = (
"odf///office:document-content[0]/office:body[0]/office:text[0]/text:p[1]"
)
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = OPENDOCUMENT_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
OpenDocumentFormat.convertfile(BytesIOMode("test.odt", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class IDMLFormatTest(ConvertFormatTest):
FORMAT = IDMLFormat
FILE = IDML_FILE
MIME = "application/octet-stream"
EXT = "idml"
COUNT = 6
MASK = "*/translations.idml"
EXPECTED_PATH = "cs_CZ/translations.idml"
FIND_CONTEXT = (
"idPkg:Story[0]/{}Story[0]/{}XMLElement[0]/{}ParagraphStyleRange[0]"
"Stories/Story_mainmainmainmainmainmainmainmainmainmainmainu188.xml"
)
FIND_MATCH = """<g id="0"><g id="1">THE HEADLINE HERE</g></g>"""
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = IDML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
IDMLFormat.convertfile(BytesIOMode("test.idml", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.<|fim_middle|>
ass WindowsRCFormatTest(ConvertFormatTest):
FORMAT = WindowsRCFormat
FILE = TEST_RC
BASE = TEST_RC
MIME = "text/plain"
EXT = "rc"
COUNT = 5
MASK = "rc/*.rc"
EXPECTED_PATH = "rc/cs-CZ.rc"
MATCH = "STRINGTABLE"
FIND_CONTEXT = "STRINGTABLE.IDS_MSG1"
FIND_MATCH = "Hello, world!\n"
EDIT_OFFSET = 1
class PlainTextFormatTest(ConvertFormatTest):
FORMAT = PlainTextFormat
FILE = TEST_TXT
BASE = TEST_TXT
MIME = "text/plain"
EXT = "txt"
COUNT = 5
MASK = "txt/*.txt"
EXPECTED_PATH = "txt/cs_CZ.txt"
MATCH = "Hello"
FIND_CONTEXT = "cs.txt:2"
FIND_MATCH = "Hello, world!"
EDIT_OFFSET = 1
<|fim▁end|> | assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
cl |
<|file_name|>test_convert.py<|end_file_name|><|fim▁begin|>#
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""File format specific behavior."""
from weblate.formats.convert import (
HTMLFormat,
IDMLFormat,
OpenDocumentFormat,
PlainTextFormat,
WindowsRCFormat,
)
from weblate.formats.helpers import BytesIOMode
from weblate.formats.tests.test_formats import AutoFormatTest
from weblate.trans.tests.utils import get_test_file
IDML_FILE = get_test_file("en.idml")
HTML_FILE = get_test_file("cs.html")
OPENDOCUMENT_FILE = get_test_file("cs.odt")
TEST_RC = get_test_file("cs-CZ.rc")
TEST_TXT = get_test_file("cs.txt")
class ConvertFormatTest(AutoFormatTest):
NEW_UNIT_MATCH = None
EXPECTED_FLAGS = ""
def parse_file(self, filename):
return self.FORMAT(filename, template_store=self.FORMAT(filename))
class HTMLFormatTest(ConvertFormatTest):
FORMAT = HTMLFormat
FILE = HTML_FILE
MIME = "text/html"
EXT = "html"
COUNT = 5
MASK = "*/translations.html"
EXPECTED_PATH = "cs_CZ/translations.html"
FIND_CONTEXT = "+html.body.p:5-1"
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"<body>"
NEW_UNIT_MATCH = None
BASE = HTML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
class OpenDocumentFormatTest(ConvertFormatTest):
FORMAT = OpenDocumentFormat
FILE = OPENDOCUMENT_FILE
MIME = "application/vnd.oasis.opendocument.text"
EXT = "odt"
COUNT = 4
MASK = "*/translations.odt"
EXPECTED_PATH = "cs_CZ/translations.odt"
FIND_CONTEXT = (
"odf///office:document-content[0]/office:body[0]/office:text[0]/text:p[1]"
)
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = OPENDOCUMENT_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
OpenDocumentFormat.convertfile(BytesIOMode("test.odt", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class IDMLFormatTest(ConvertFormatTest):
FORMAT = IDMLFormat
FILE = IDML_FILE
MIME = "application/octet-stream"
EXT = "idml"
COUNT = 6
MASK = "*/translations.idml"
EXPECTED_PATH = "cs_CZ/translations.idml"
FIND_CONTEXT = (
"idPkg:Story[0]/{}Story[0]/{}XMLElement[0]/{}ParagraphStyleRange[0]"
"Stories/Story_mainmainmainmainmainmainmainmainmainmainmainu188.xml"
)
FIND_MATCH = """<g id="0"><g id="1">THE HEADLINE HERE</g></g>"""
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = IDML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
IDMLFormat.convertfile(BytesIOMode("test.idml", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class WindowsRCFormatTest(ConvertFormatTest):
FORMA<|fim_middle|>
ass PlainTextFormatTest(ConvertFormatTest):
FORMAT = PlainTextFormat
FILE = TEST_TXT
BASE = TEST_TXT
MIME = "text/plain"
EXT = "txt"
COUNT = 5
MASK = "txt/*.txt"
EXPECTED_PATH = "txt/cs_CZ.txt"
MATCH = "Hello"
FIND_CONTEXT = "cs.txt:2"
FIND_MATCH = "Hello, world!"
EDIT_OFFSET = 1
<|fim▁end|> | T = WindowsRCFormat
FILE = TEST_RC
BASE = TEST_RC
MIME = "text/plain"
EXT = "rc"
COUNT = 5
MASK = "rc/*.rc"
EXPECTED_PATH = "rc/cs-CZ.rc"
MATCH = "STRINGTABLE"
FIND_CONTEXT = "STRINGTABLE.IDS_MSG1"
FIND_MATCH = "Hello, world!\n"
EDIT_OFFSET = 1
cl |
<|file_name|>test_convert.py<|end_file_name|><|fim▁begin|>#
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""File format specific behavior."""
from weblate.formats.convert import (
HTMLFormat,
IDMLFormat,
OpenDocumentFormat,
PlainTextFormat,
WindowsRCFormat,
)
from weblate.formats.helpers import BytesIOMode
from weblate.formats.tests.test_formats import AutoFormatTest
from weblate.trans.tests.utils import get_test_file
IDML_FILE = get_test_file("en.idml")
HTML_FILE = get_test_file("cs.html")
OPENDOCUMENT_FILE = get_test_file("cs.odt")
TEST_RC = get_test_file("cs-CZ.rc")
TEST_TXT = get_test_file("cs.txt")
class ConvertFormatTest(AutoFormatTest):
NEW_UNIT_MATCH = None
EXPECTED_FLAGS = ""
def parse_file(self, filename):
return self.FORMAT(filename, template_store=self.FORMAT(filename))
class HTMLFormatTest(ConvertFormatTest):
FORMAT = HTMLFormat
FILE = HTML_FILE
MIME = "text/html"
EXT = "html"
COUNT = 5
MASK = "*/translations.html"
EXPECTED_PATH = "cs_CZ/translations.html"
FIND_CONTEXT = "+html.body.p:5-1"
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"<body>"
NEW_UNIT_MATCH = None
BASE = HTML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
class OpenDocumentFormatTest(ConvertFormatTest):
FORMAT = OpenDocumentFormat
FILE = OPENDOCUMENT_FILE
MIME = "application/vnd.oasis.opendocument.text"
EXT = "odt"
COUNT = 4
MASK = "*/translations.odt"
EXPECTED_PATH = "cs_CZ/translations.odt"
FIND_CONTEXT = (
"odf///office:document-content[0]/office:body[0]/office:text[0]/text:p[1]"
)
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = OPENDOCUMENT_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
OpenDocumentFormat.convertfile(BytesIOMode("test.odt", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class IDMLFormatTest(ConvertFormatTest):
FORMAT = IDMLFormat
FILE = IDML_FILE
MIME = "application/octet-stream"
EXT = "idml"
COUNT = 6
MASK = "*/translations.idml"
EXPECTED_PATH = "cs_CZ/translations.idml"
FIND_CONTEXT = (
"idPkg:Story[0]/{}Story[0]/{}XMLElement[0]/{}ParagraphStyleRange[0]"
"Stories/Story_mainmainmainmainmainmainmainmainmainmainmainu188.xml"
)
FIND_MATCH = """<g id="0"><g id="1">THE HEADLINE HERE</g></g>"""
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = IDML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
IDMLFormat.convertfile(BytesIOMode("test.idml", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class WindowsRCFormatTest(ConvertFormatTest):
FORMAT = WindowsRCFormat
FILE = TEST_RC
BASE = TEST_RC
MIME = "text/plain"
EXT = "rc"
COUNT = 5
MASK = "rc/*.rc"
EXPECTED_PATH = "rc/cs-CZ.rc"
MATCH = "STRINGTABLE"
FIND_CONTEXT = "STRINGTABLE.IDS_MSG1"
FIND_MATCH = "Hello, world!\n"
EDIT_OFFSET = 1
class PlainTextFormatTest(ConvertFormatTest):
FORMA<|fim_middle|>
<|fim▁end|> | T = PlainTextFormat
FILE = TEST_TXT
BASE = TEST_TXT
MIME = "text/plain"
EXT = "txt"
COUNT = 5
MASK = "txt/*.txt"
EXPECTED_PATH = "txt/cs_CZ.txt"
MATCH = "Hello"
FIND_CONTEXT = "cs.txt:2"
FIND_MATCH = "Hello, world!"
EDIT_OFFSET = 1
|
<|file_name|>test_convert.py<|end_file_name|><|fim▁begin|>#
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""File format specific behavior."""
from weblate.formats.convert import (
HTMLFormat,
IDMLFormat,
OpenDocumentFormat,
PlainTextFormat,
WindowsRCFormat,
)
from weblate.formats.helpers import BytesIOMode
from weblate.formats.tests.test_formats import AutoFormatTest
from weblate.trans.tests.utils import get_test_file
IDML_FILE = get_test_file("en.idml")
HTML_FILE = get_test_file("cs.html")
OPENDOCUMENT_FILE = get_test_file("cs.odt")
TEST_RC = get_test_file("cs-CZ.rc")
TEST_TXT = get_test_file("cs.txt")
class ConvertFormatTest(AutoFormatTest):
NEW_UNIT_MATCH = None
EXPECTED_FLAGS = ""
def parse<|fim_middle|>, filename):
return self.FORMAT(filename, template_store=self.FORMAT(filename))
class HTMLFormatTest(ConvertFormatTest):
FORMAT = HTMLFormat
FILE = HTML_FILE
MIME = "text/html"
EXT = "html"
COUNT = 5
MASK = "*/translations.html"
EXPECTED_PATH = "cs_CZ/translations.html"
FIND_CONTEXT = "+html.body.p:5-1"
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"<body>"
NEW_UNIT_MATCH = None
BASE = HTML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
class OpenDocumentFormatTest(ConvertFormatTest):
FORMAT = OpenDocumentFormat
FILE = OPENDOCUMENT_FILE
MIME = "application/vnd.oasis.opendocument.text"
EXT = "odt"
COUNT = 4
MASK = "*/translations.odt"
EXPECTED_PATH = "cs_CZ/translations.odt"
FIND_CONTEXT = (
"odf///office:document-content[0]/office:body[0]/office:text[0]/text:p[1]"
)
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = OPENDOCUMENT_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
OpenDocumentFormat.convertfile(BytesIOMode("test.odt", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class IDMLFormatTest(ConvertFormatTest):
FORMAT = IDMLFormat
FILE = IDML_FILE
MIME = "application/octet-stream"
EXT = "idml"
COUNT = 6
MASK = "*/translations.idml"
EXPECTED_PATH = "cs_CZ/translations.idml"
FIND_CONTEXT = (
"idPkg:Story[0]/{}Story[0]/{}XMLElement[0]/{}ParagraphStyleRange[0]"
"Stories/Story_mainmainmainmainmainmainmainmainmainmainmainu188.xml"
)
FIND_MATCH = """<g id="0"><g id="1">THE HEADLINE HERE</g></g>"""
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = IDML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
IDMLFormat.convertfile(BytesIOMode("test.idml", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class WindowsRCFormatTest(ConvertFormatTest):
FORMAT = WindowsRCFormat
FILE = TEST_RC
BASE = TEST_RC
MIME = "text/plain"
EXT = "rc"
COUNT = 5
MASK = "rc/*.rc"
EXPECTED_PATH = "rc/cs-CZ.rc"
MATCH = "STRINGTABLE"
FIND_CONTEXT = "STRINGTABLE.IDS_MSG1"
FIND_MATCH = "Hello, world!\n"
EDIT_OFFSET = 1
class PlainTextFormatTest(ConvertFormatTest):
FORMAT = PlainTextFormat
FILE = TEST_TXT
BASE = TEST_TXT
MIME = "text/plain"
EXT = "txt"
COUNT = 5
MASK = "txt/*.txt"
EXPECTED_PATH = "txt/cs_CZ.txt"
MATCH = "Hello"
FIND_CONTEXT = "cs.txt:2"
FIND_MATCH = "Hello, world!"
EDIT_OFFSET = 1
<|fim▁end|> | _file(self |
<|file_name|>test_convert.py<|end_file_name|><|fim▁begin|>#
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""File format specific behavior."""
from weblate.formats.convert import (
HTMLFormat,
IDMLFormat,
OpenDocumentFormat,
PlainTextFormat,
WindowsRCFormat,
)
from weblate.formats.helpers import BytesIOMode
from weblate.formats.tests.test_formats import AutoFormatTest
from weblate.trans.tests.utils import get_test_file
IDML_FILE = get_test_file("en.idml")
HTML_FILE = get_test_file("cs.html")
OPENDOCUMENT_FILE = get_test_file("cs.odt")
TEST_RC = get_test_file("cs-CZ.rc")
TEST_TXT = get_test_file("cs.txt")
class ConvertFormatTest(AutoFormatTest):
NEW_UNIT_MATCH = None
EXPECTED_FLAGS = ""
def parse_file(self, filename):
return self.FORMAT(filename, template_store=self.FORMAT(filename))
class HTMLFormatTest(ConvertFormatTest):
FORMAT = HTMLFormat
FILE = HTML_FILE
MIME = "text/html"
EXT = "html"
COUNT = 5
MASK = "*/translations.html"
EXPECTED_PATH = "cs_CZ/translations.html"
FIND_CONTEXT = "+html.body.p:5-1"
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"<body>"
NEW_UNIT_MATCH = None
BASE = HTML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
class OpenDocumentFormatTest(ConvertFormatTest):
FORMAT = OpenDocumentFormat
FILE = OPENDOCUMENT_FILE
MIME = "application/vnd.oasis.opendocument.text"
EXT = "odt"
COUNT = 4
MASK = "*/translations.odt"
EXPECTED_PATH = "cs_CZ/translations.odt"
FIND_CONTEXT = (
"odf///office:document-content[0]/office:body[0]/office:text[0]/text:p[1]"
)
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = OPENDOCUMENT_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extra<|fim_middle|>ent):
return bytes(
OpenDocumentFormat.convertfile(BytesIOMode("test.odt", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class IDMLFormatTest(ConvertFormatTest):
FORMAT = IDMLFormat
FILE = IDML_FILE
MIME = "application/octet-stream"
EXT = "idml"
COUNT = 6
MASK = "*/translations.idml"
EXPECTED_PATH = "cs_CZ/translations.idml"
FIND_CONTEXT = (
"idPkg:Story[0]/{}Story[0]/{}XMLElement[0]/{}ParagraphStyleRange[0]"
"Stories/Story_mainmainmainmainmainmainmainmainmainmainmainu188.xml"
)
FIND_MATCH = """<g id="0"><g id="1">THE HEADLINE HERE</g></g>"""
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = IDML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
IDMLFormat.convertfile(BytesIOMode("test.idml", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class WindowsRCFormatTest(ConvertFormatTest):
FORMAT = WindowsRCFormat
FILE = TEST_RC
BASE = TEST_RC
MIME = "text/plain"
EXT = "rc"
COUNT = 5
MASK = "rc/*.rc"
EXPECTED_PATH = "rc/cs-CZ.rc"
MATCH = "STRINGTABLE"
FIND_CONTEXT = "STRINGTABLE.IDS_MSG1"
FIND_MATCH = "Hello, world!\n"
EDIT_OFFSET = 1
class PlainTextFormatTest(ConvertFormatTest):
FORMAT = PlainTextFormat
FILE = TEST_TXT
BASE = TEST_TXT
MIME = "text/plain"
EXT = "txt"
COUNT = 5
MASK = "txt/*.txt"
EXPECTED_PATH = "txt/cs_CZ.txt"
MATCH = "Hello"
FIND_CONTEXT = "cs.txt:2"
FIND_MATCH = "Hello, world!"
EDIT_OFFSET = 1
<|fim▁end|> | ct_document(cont |
<|file_name|>test_convert.py<|end_file_name|><|fim▁begin|>#
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""File format specific behavior."""
from weblate.formats.convert import (
HTMLFormat,
IDMLFormat,
OpenDocumentFormat,
PlainTextFormat,
WindowsRCFormat,
)
from weblate.formats.helpers import BytesIOMode
from weblate.formats.tests.test_formats import AutoFormatTest
from weblate.trans.tests.utils import get_test_file
IDML_FILE = get_test_file("en.idml")
HTML_FILE = get_test_file("cs.html")
OPENDOCUMENT_FILE = get_test_file("cs.odt")
TEST_RC = get_test_file("cs-CZ.rc")
TEST_TXT = get_test_file("cs.txt")
class ConvertFormatTest(AutoFormatTest):
NEW_UNIT_MATCH = None
EXPECTED_FLAGS = ""
def parse_file(self, filename):
return self.FORMAT(filename, template_store=self.FORMAT(filename))
class HTMLFormatTest(ConvertFormatTest):
FORMAT = HTMLFormat
FILE = HTML_FILE
MIME = "text/html"
EXT = "html"
COUNT = 5
MASK = "*/translations.html"
EXPECTED_PATH = "cs_CZ/translations.html"
FIND_CONTEXT = "+html.body.p:5-1"
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"<body>"
NEW_UNIT_MATCH = None
BASE = HTML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
class OpenDocumentFormatTest(ConvertFormatTest):
FORMAT = OpenDocumentFormat
FILE = OPENDOCUMENT_FILE
MIME = "application/vnd.oasis.opendocument.text"
EXT = "odt"
COUNT = 4
MASK = "*/translations.odt"
EXPECTED_PATH = "cs_CZ/translations.odt"
FIND_CONTEXT = (
"odf///office:document-content[0]/office:body[0]/office:text[0]/text:p[1]"
)
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = OPENDOCUMENT_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
OpenDocumentFormat.convertfile(BytesIOMode("test.odt", content), None)
).decode()
def asser<|fim_middle|>, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class IDMLFormatTest(ConvertFormatTest):
FORMAT = IDMLFormat
FILE = IDML_FILE
MIME = "application/octet-stream"
EXT = "idml"
COUNT = 6
MASK = "*/translations.idml"
EXPECTED_PATH = "cs_CZ/translations.idml"
FIND_CONTEXT = (
"idPkg:Story[0]/{}Story[0]/{}XMLElement[0]/{}ParagraphStyleRange[0]"
"Stories/Story_mainmainmainmainmainmainmainmainmainmainmainu188.xml"
)
FIND_MATCH = """<g id="0"><g id="1">THE HEADLINE HERE</g></g>"""
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = IDML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
IDMLFormat.convertfile(BytesIOMode("test.idml", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class WindowsRCFormatTest(ConvertFormatTest):
FORMAT = WindowsRCFormat
FILE = TEST_RC
BASE = TEST_RC
MIME = "text/plain"
EXT = "rc"
COUNT = 5
MASK = "rc/*.rc"
EXPECTED_PATH = "rc/cs-CZ.rc"
MATCH = "STRINGTABLE"
FIND_CONTEXT = "STRINGTABLE.IDS_MSG1"
FIND_MATCH = "Hello, world!\n"
EDIT_OFFSET = 1
class PlainTextFormatTest(ConvertFormatTest):
FORMAT = PlainTextFormat
FILE = TEST_TXT
BASE = TEST_TXT
MIME = "text/plain"
EXT = "txt"
COUNT = 5
MASK = "txt/*.txt"
EXPECTED_PATH = "txt/cs_CZ.txt"
MATCH = "Hello"
FIND_CONTEXT = "cs.txt:2"
FIND_MATCH = "Hello, world!"
EDIT_OFFSET = 1
<|fim▁end|> | t_same(self |
<|file_name|>test_convert.py<|end_file_name|><|fim▁begin|>#
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""File format specific behavior."""
from weblate.formats.convert import (
HTMLFormat,
IDMLFormat,
OpenDocumentFormat,
PlainTextFormat,
WindowsRCFormat,
)
from weblate.formats.helpers import BytesIOMode
from weblate.formats.tests.test_formats import AutoFormatTest
from weblate.trans.tests.utils import get_test_file
IDML_FILE = get_test_file("en.idml")
HTML_FILE = get_test_file("cs.html")
OPENDOCUMENT_FILE = get_test_file("cs.odt")
TEST_RC = get_test_file("cs-CZ.rc")
TEST_TXT = get_test_file("cs.txt")
class ConvertFormatTest(AutoFormatTest):
NEW_UNIT_MATCH = None
EXPECTED_FLAGS = ""
def parse_file(self, filename):
return self.FORMAT(filename, template_store=self.FORMAT(filename))
class HTMLFormatTest(ConvertFormatTest):
FORMAT = HTMLFormat
FILE = HTML_FILE
MIME = "text/html"
EXT = "html"
COUNT = 5
MASK = "*/translations.html"
EXPECTED_PATH = "cs_CZ/translations.html"
FIND_CONTEXT = "+html.body.p:5-1"
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"<body>"
NEW_UNIT_MATCH = None
BASE = HTML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
class OpenDocumentFormatTest(ConvertFormatTest):
FORMAT = OpenDocumentFormat
FILE = OPENDOCUMENT_FILE
MIME = "application/vnd.oasis.opendocument.text"
EXT = "odt"
COUNT = 4
MASK = "*/translations.odt"
EXPECTED_PATH = "cs_CZ/translations.odt"
FIND_CONTEXT = (
"odf///office:document-content[0]/office:body[0]/office:text[0]/text:p[1]"
)
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = OPENDOCUMENT_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
OpenDocumentFormat.convertfile(BytesIOMode("test.odt", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class IDMLFormatTest(ConvertFormatTest):
FORMAT = IDMLFormat
FILE = IDML_FILE
MIME = "application/octet-stream"
EXT = "idml"
COUNT = 6
MASK = "*/translations.idml"
EXPECTED_PATH = "cs_CZ/translations.idml"
FIND_CONTEXT = (
"idPkg:Story[0]/{}Story[0]/{}XMLElement[0]/{}ParagraphStyleRange[0]"
"Stories/Story_mainmainmainmainmainmainmainmainmainmainmainu188.xml"
)
FIND_MATCH = """<g id="0"><g id="1">THE HEADLINE HERE</g></g>"""
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = IDML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extra<|fim_middle|>ent):
return bytes(
IDMLFormat.convertfile(BytesIOMode("test.idml", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class WindowsRCFormatTest(ConvertFormatTest):
FORMAT = WindowsRCFormat
FILE = TEST_RC
BASE = TEST_RC
MIME = "text/plain"
EXT = "rc"
COUNT = 5
MASK = "rc/*.rc"
EXPECTED_PATH = "rc/cs-CZ.rc"
MATCH = "STRINGTABLE"
FIND_CONTEXT = "STRINGTABLE.IDS_MSG1"
FIND_MATCH = "Hello, world!\n"
EDIT_OFFSET = 1
class PlainTextFormatTest(ConvertFormatTest):
FORMAT = PlainTextFormat
FILE = TEST_TXT
BASE = TEST_TXT
MIME = "text/plain"
EXT = "txt"
COUNT = 5
MASK = "txt/*.txt"
EXPECTED_PATH = "txt/cs_CZ.txt"
MATCH = "Hello"
FIND_CONTEXT = "cs.txt:2"
FIND_MATCH = "Hello, world!"
EDIT_OFFSET = 1
<|fim▁end|> | ct_document(cont |
<|file_name|>test_convert.py<|end_file_name|><|fim▁begin|>#
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""File format specific behavior."""
from weblate.formats.convert import (
HTMLFormat,
IDMLFormat,
OpenDocumentFormat,
PlainTextFormat,
WindowsRCFormat,
)
from weblate.formats.helpers import BytesIOMode
from weblate.formats.tests.test_formats import AutoFormatTest
from weblate.trans.tests.utils import get_test_file
IDML_FILE = get_test_file("en.idml")
HTML_FILE = get_test_file("cs.html")
OPENDOCUMENT_FILE = get_test_file("cs.odt")
TEST_RC = get_test_file("cs-CZ.rc")
TEST_TXT = get_test_file("cs.txt")
class ConvertFormatTest(AutoFormatTest):
NEW_UNIT_MATCH = None
EXPECTED_FLAGS = ""
def parse_file(self, filename):
return self.FORMAT(filename, template_store=self.FORMAT(filename))
class HTMLFormatTest(ConvertFormatTest):
FORMAT = HTMLFormat
FILE = HTML_FILE
MIME = "text/html"
EXT = "html"
COUNT = 5
MASK = "*/translations.html"
EXPECTED_PATH = "cs_CZ/translations.html"
FIND_CONTEXT = "+html.body.p:5-1"
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"<body>"
NEW_UNIT_MATCH = None
BASE = HTML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
class OpenDocumentFormatTest(ConvertFormatTest):
FORMAT = OpenDocumentFormat
FILE = OPENDOCUMENT_FILE
MIME = "application/vnd.oasis.opendocument.text"
EXT = "odt"
COUNT = 4
MASK = "*/translations.odt"
EXPECTED_PATH = "cs_CZ/translations.odt"
FIND_CONTEXT = (
"odf///office:document-content[0]/office:body[0]/office:text[0]/text:p[1]"
)
FIND_MATCH = "Orangutan has five bananas."
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = OPENDOCUMENT_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
OpenDocumentFormat.convertfile(BytesIOMode("test.odt", content), None)
).decode()
def assert_same(self, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class IDMLFormatTest(ConvertFormatTest):
FORMAT = IDMLFormat
FILE = IDML_FILE
MIME = "application/octet-stream"
EXT = "idml"
COUNT = 6
MASK = "*/translations.idml"
EXPECTED_PATH = "cs_CZ/translations.idml"
FIND_CONTEXT = (
"idPkg:Story[0]/{}Story[0]/{}XMLElement[0]/{}ParagraphStyleRange[0]"
"Stories/Story_mainmainmainmainmainmainmainmainmainmainmainu188.xml"
)
FIND_MATCH = """<g id="0"><g id="1">THE HEADLINE HERE</g></g>"""
MATCH = b"PK"
NEW_UNIT_MATCH = None
BASE = IDML_FILE
EXPECTED_FLAGS = ""
EDIT_OFFSET = 1
@staticmethod
def extract_document(content):
return bytes(
IDMLFormat.convertfile(BytesIOMode("test.idml", content), None)
).decode()
def asser<|fim_middle|>, newdata, testdata):
self.assertEqual(
self.extract_document(newdata),
self.extract_document(testdata),
)
class WindowsRCFormatTest(ConvertFormatTest):
FORMAT = WindowsRCFormat
FILE = TEST_RC
BASE = TEST_RC
MIME = "text/plain"
EXT = "rc"
COUNT = 5
MASK = "rc/*.rc"
EXPECTED_PATH = "rc/cs-CZ.rc"
MATCH = "STRINGTABLE"
FIND_CONTEXT = "STRINGTABLE.IDS_MSG1"
FIND_MATCH = "Hello, world!\n"
EDIT_OFFSET = 1
class PlainTextFormatTest(ConvertFormatTest):
FORMAT = PlainTextFormat
FILE = TEST_TXT
BASE = TEST_TXT
MIME = "text/plain"
EXT = "txt"
COUNT = 5
MASK = "txt/*.txt"
EXPECTED_PATH = "txt/cs_CZ.txt"
MATCH = "Hello"
FIND_CONTEXT = "cs.txt:2"
FIND_MATCH = "Hello, world!"
EDIT_OFFSET = 1
<|fim▁end|> | t_same(self |
<|file_name|>get_completions_test.py<|end_file_name|><|fim▁begin|># coding: utf-8
#
# Copyright (C) 2015 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ycmd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ycmd. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import * # noqa
from nose.tools import eq_
from hamcrest import ( assert_that, has_item, has_items, has_entry,
has_entries, contains, empty, contains_string )
from ycmd.utils import ReadFile
from ycmd.tests.python import PathToTestFile, SharedYcmd
from ycmd.tests.test_utils import ( BuildRequest, CompletionEntryMatcher,
CompletionLocationMatcher )
import http.client
@SharedYcmd
def GetCompletions_Basic_test( app ):
filepath = PathToTestFile( 'basic.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
line_num = 7,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results,
has_items(
CompletionEntryMatcher( 'a' ),
CompletionEntryMatcher( 'b' ),
CompletionLocationMatcher( 'line_num', 3 ),
CompletionLocationMatcher( 'line_num', 4 ),
CompletionLocationMatcher( 'column_num', 10 ),
CompletionLocationMatcher( 'filepath', filepath ) ) )
@SharedYcmd
def GetCompletions_UnicodeDescription_test( app ):
filepath = PathToTestFile( 'unicode.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
force_semantic = True,
line_num = 5,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results, has_item(
has_entry( 'detailed_info', contains_string( u'aafäö' ) ) ) )
def RunTest( app, test ):
"""
Method to run a simple completion test and verify the result
test is a dictionary containing:
'request': kwargs for BuildRequest
'expect': {
'response': server response code (e.g. httplib.OK)
'data': matcher for the server response json
}
"""
contents = ReadFile( test[ 'request' ][ 'filepath' ] )
def CombineRequest( request, data ):
kw = request
request.update( data )
return BuildRequest( **kw )
app.post_json( '/event_notification',
CombineRequest( test[ 'request' ], {
'event_name': 'FileReadyToParse',
'contents': contents,
} ) )
# We ignore errors here and we check the response code ourself.
# This is to allow testing of requests returning errors.
response = app.post_json( '/completions',
CombineRequest( test[ 'request' ], {
'contents': contents
} ),
expect_errors = True )
eq_( response.status_code, test[ 'expect' ][ 'response' ] )
assert_that( response.json, test[ 'expect' ][ 'data' ] )<|fim▁hole|>
@SharedYcmd
def GetCompletions_NoSuggestions_Fallback_test( app ):
# Python completer doesn't raise NO_COMPLETIONS_MESSAGE, so this is a
# different code path to the Clang completer cases
# TESTCASE2 (general_fallback/lang_python.py)
RunTest( app, {
'description': 'param jedi does not know about (id). query="a_p"',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'general_fallback',
'lang_python.py' ),
'line_num' : 28,
'column_num': 20,
'force_semantic': False,
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'a_parameter', '[ID]' ),
CompletionEntryMatcher( 'another_parameter', '[ID]' ),
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_Unicode_InLine_test( app ):
RunTest( app, {
'description': 'return completions for strings with multi-byte chars',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'unicode.py' ),
'line_num' : 7,
'column_num': 14
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'center', 'function: builtins.str.center' )
),
'errors': empty(),
} )
},
} )<|fim▁end|> | |
<|file_name|>get_completions_test.py<|end_file_name|><|fim▁begin|># coding: utf-8
#
# Copyright (C) 2015 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ycmd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ycmd. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import * # noqa
from nose.tools import eq_
from hamcrest import ( assert_that, has_item, has_items, has_entry,
has_entries, contains, empty, contains_string )
from ycmd.utils import ReadFile
from ycmd.tests.python import PathToTestFile, SharedYcmd
from ycmd.tests.test_utils import ( BuildRequest, CompletionEntryMatcher,
CompletionLocationMatcher )
import http.client
@SharedYcmd
def GetCompletions_Basic_test( app ):
<|fim_middle|>
@SharedYcmd
def GetCompletions_UnicodeDescription_test( app ):
filepath = PathToTestFile( 'unicode.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
force_semantic = True,
line_num = 5,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results, has_item(
has_entry( 'detailed_info', contains_string( u'aafäö' ) ) ) )
def RunTest( app, test ):
"""
Method to run a simple completion test and verify the result
test is a dictionary containing:
'request': kwargs for BuildRequest
'expect': {
'response': server response code (e.g. httplib.OK)
'data': matcher for the server response json
}
"""
contents = ReadFile( test[ 'request' ][ 'filepath' ] )
def CombineRequest( request, data ):
kw = request
request.update( data )
return BuildRequest( **kw )
app.post_json( '/event_notification',
CombineRequest( test[ 'request' ], {
'event_name': 'FileReadyToParse',
'contents': contents,
} ) )
# We ignore errors here and we check the response code ourself.
# This is to allow testing of requests returning errors.
response = app.post_json( '/completions',
CombineRequest( test[ 'request' ], {
'contents': contents
} ),
expect_errors = True )
eq_( response.status_code, test[ 'expect' ][ 'response' ] )
assert_that( response.json, test[ 'expect' ][ 'data' ] )
@SharedYcmd
def GetCompletions_NoSuggestions_Fallback_test( app ):
# Python completer doesn't raise NO_COMPLETIONS_MESSAGE, so this is a
# different code path to the Clang completer cases
# TESTCASE2 (general_fallback/lang_python.py)
RunTest( app, {
'description': 'param jedi does not know about (id). query="a_p"',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'general_fallback',
'lang_python.py' ),
'line_num' : 28,
'column_num': 20,
'force_semantic': False,
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'a_parameter', '[ID]' ),
CompletionEntryMatcher( 'another_parameter', '[ID]' ),
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_Unicode_InLine_test( app ):
RunTest( app, {
'description': 'return completions for strings with multi-byte chars',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'unicode.py' ),
'line_num' : 7,
'column_num': 14
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'center', 'function: builtins.str.center' )
),
'errors': empty(),
} )
},
} )
<|fim▁end|> | filepath = PathToTestFile( 'basic.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
line_num = 7,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results,
has_items(
CompletionEntryMatcher( 'a' ),
CompletionEntryMatcher( 'b' ),
CompletionLocationMatcher( 'line_num', 3 ),
CompletionLocationMatcher( 'line_num', 4 ),
CompletionLocationMatcher( 'column_num', 10 ),
CompletionLocationMatcher( 'filepath', filepath ) ) ) |
<|file_name|>get_completions_test.py<|end_file_name|><|fim▁begin|># coding: utf-8
#
# Copyright (C) 2015 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ycmd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ycmd. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import * # noqa
from nose.tools import eq_
from hamcrest import ( assert_that, has_item, has_items, has_entry,
has_entries, contains, empty, contains_string )
from ycmd.utils import ReadFile
from ycmd.tests.python import PathToTestFile, SharedYcmd
from ycmd.tests.test_utils import ( BuildRequest, CompletionEntryMatcher,
CompletionLocationMatcher )
import http.client
@SharedYcmd
def GetCompletions_Basic_test( app ):
filepath = PathToTestFile( 'basic.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
line_num = 7,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results,
has_items(
CompletionEntryMatcher( 'a' ),
CompletionEntryMatcher( 'b' ),
CompletionLocationMatcher( 'line_num', 3 ),
CompletionLocationMatcher( 'line_num', 4 ),
CompletionLocationMatcher( 'column_num', 10 ),
CompletionLocationMatcher( 'filepath', filepath ) ) )
@SharedYcmd
def GetCompletions_UnicodeDescription_test( app ):
<|fim_middle|>
def RunTest( app, test ):
"""
Method to run a simple completion test and verify the result
test is a dictionary containing:
'request': kwargs for BuildRequest
'expect': {
'response': server response code (e.g. httplib.OK)
'data': matcher for the server response json
}
"""
contents = ReadFile( test[ 'request' ][ 'filepath' ] )
def CombineRequest( request, data ):
kw = request
request.update( data )
return BuildRequest( **kw )
app.post_json( '/event_notification',
CombineRequest( test[ 'request' ], {
'event_name': 'FileReadyToParse',
'contents': contents,
} ) )
# We ignore errors here and we check the response code ourself.
# This is to allow testing of requests returning errors.
response = app.post_json( '/completions',
CombineRequest( test[ 'request' ], {
'contents': contents
} ),
expect_errors = True )
eq_( response.status_code, test[ 'expect' ][ 'response' ] )
assert_that( response.json, test[ 'expect' ][ 'data' ] )
@SharedYcmd
def GetCompletions_NoSuggestions_Fallback_test( app ):
# Python completer doesn't raise NO_COMPLETIONS_MESSAGE, so this is a
# different code path to the Clang completer cases
# TESTCASE2 (general_fallback/lang_python.py)
RunTest( app, {
'description': 'param jedi does not know about (id). query="a_p"',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'general_fallback',
'lang_python.py' ),
'line_num' : 28,
'column_num': 20,
'force_semantic': False,
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'a_parameter', '[ID]' ),
CompletionEntryMatcher( 'another_parameter', '[ID]' ),
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_Unicode_InLine_test( app ):
RunTest( app, {
'description': 'return completions for strings with multi-byte chars',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'unicode.py' ),
'line_num' : 7,
'column_num': 14
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'center', 'function: builtins.str.center' )
),
'errors': empty(),
} )
},
} )
<|fim▁end|> | filepath = PathToTestFile( 'unicode.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
force_semantic = True,
line_num = 5,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results, has_item(
has_entry( 'detailed_info', contains_string( u'aafäö' ) ) ) )
|
<|file_name|>get_completions_test.py<|end_file_name|><|fim▁begin|># coding: utf-8
#
# Copyright (C) 2015 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ycmd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ycmd. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import * # noqa
from nose.tools import eq_
from hamcrest import ( assert_that, has_item, has_items, has_entry,
has_entries, contains, empty, contains_string )
from ycmd.utils import ReadFile
from ycmd.tests.python import PathToTestFile, SharedYcmd
from ycmd.tests.test_utils import ( BuildRequest, CompletionEntryMatcher,
CompletionLocationMatcher )
import http.client
@SharedYcmd
def GetCompletions_Basic_test( app ):
filepath = PathToTestFile( 'basic.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
line_num = 7,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results,
has_items(
CompletionEntryMatcher( 'a' ),
CompletionEntryMatcher( 'b' ),
CompletionLocationMatcher( 'line_num', 3 ),
CompletionLocationMatcher( 'line_num', 4 ),
CompletionLocationMatcher( 'column_num', 10 ),
CompletionLocationMatcher( 'filepath', filepath ) ) )
@SharedYcmd
def GetCompletions_UnicodeDescription_test( app ):
filepath = PathToTestFile( 'unicode.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
force_semantic = True,
line_num = 5,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results, has_item(
has_entry( 'detailed_info', contains_string( u'aafäö' ) ) ) )
def RunTest( app, test ):
""<|fim_middle|>
@SharedYcmd
def GetCompletions_NoSuggestions_Fallback_test( app ):
# Python completer doesn't raise NO_COMPLETIONS_MESSAGE, so this is a
# different code path to the Clang completer cases
# TESTCASE2 (general_fallback/lang_python.py)
RunTest( app, {
'description': 'param jedi does not know about (id). query="a_p"',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'general_fallback',
'lang_python.py' ),
'line_num' : 28,
'column_num': 20,
'force_semantic': False,
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'a_parameter', '[ID]' ),
CompletionEntryMatcher( 'another_parameter', '[ID]' ),
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_Unicode_InLine_test( app ):
RunTest( app, {
'description': 'return completions for strings with multi-byte chars',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'unicode.py' ),
'line_num' : 7,
'column_num': 14
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'center', 'function: builtins.str.center' )
),
'errors': empty(),
} )
},
} )
<|fim▁end|> | "
Method to run a simple completion test and verify the result
test is a dictionary containing:
'request': kwargs for BuildRequest
'expect': {
'response': server response code (e.g. httplib.OK)
'data': matcher for the server response json
}
"""
contents = ReadFile( test[ 'request' ][ 'filepath' ] )
def CombineRequest( request, data ):
kw = request
request.update( data )
return BuildRequest( **kw )
app.post_json( '/event_notification',
CombineRequest( test[ 'request' ], {
'event_name': 'FileReadyToParse',
'contents': contents,
} ) )
# We ignore errors here and we check the response code ourself.
# This is to allow testing of requests returning errors.
response = app.post_json( '/completions',
CombineRequest( test[ 'request' ], {
'contents': contents
} ),
expect_errors = True )
eq_( response.status_code, test[ 'expect' ][ 'response' ] )
assert_that( response.json, test[ 'expect' ][ 'data' ] )
|
<|file_name|>get_completions_test.py<|end_file_name|><|fim▁begin|># coding: utf-8
#
# Copyright (C) 2015 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ycmd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ycmd. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import * # noqa
from nose.tools import eq_
from hamcrest import ( assert_that, has_item, has_items, has_entry,
has_entries, contains, empty, contains_string )
from ycmd.utils import ReadFile
from ycmd.tests.python import PathToTestFile, SharedYcmd
from ycmd.tests.test_utils import ( BuildRequest, CompletionEntryMatcher,
CompletionLocationMatcher )
import http.client
@SharedYcmd
def GetCompletions_Basic_test( app ):
filepath = PathToTestFile( 'basic.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
line_num = 7,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results,
has_items(
CompletionEntryMatcher( 'a' ),
CompletionEntryMatcher( 'b' ),
CompletionLocationMatcher( 'line_num', 3 ),
CompletionLocationMatcher( 'line_num', 4 ),
CompletionLocationMatcher( 'column_num', 10 ),
CompletionLocationMatcher( 'filepath', filepath ) ) )
@SharedYcmd
def GetCompletions_UnicodeDescription_test( app ):
filepath = PathToTestFile( 'unicode.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
force_semantic = True,
line_num = 5,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results, has_item(
has_entry( 'detailed_info', contains_string( u'aafäö' ) ) ) )
def RunTest( app, test ):
"""
Method to run a simple completion test and verify the result
test is a dictionary containing:
'request': kwargs for BuildRequest
'expect': {
'response': server response code (e.g. httplib.OK)
'data': matcher for the server response json
}
"""
contents = ReadFile( test[ 'request' ][ 'filepath' ] )
def CombineRequest( request, data ):
kw<|fim_middle|>
app.post_json( '/event_notification',
CombineRequest( test[ 'request' ], {
'event_name': 'FileReadyToParse',
'contents': contents,
} ) )
# We ignore errors here and we check the response code ourself.
# This is to allow testing of requests returning errors.
response = app.post_json( '/completions',
CombineRequest( test[ 'request' ], {
'contents': contents
} ),
expect_errors = True )
eq_( response.status_code, test[ 'expect' ][ 'response' ] )
assert_that( response.json, test[ 'expect' ][ 'data' ] )
@SharedYcmd
def GetCompletions_NoSuggestions_Fallback_test( app ):
# Python completer doesn't raise NO_COMPLETIONS_MESSAGE, so this is a
# different code path to the Clang completer cases
# TESTCASE2 (general_fallback/lang_python.py)
RunTest( app, {
'description': 'param jedi does not know about (id). query="a_p"',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'general_fallback',
'lang_python.py' ),
'line_num' : 28,
'column_num': 20,
'force_semantic': False,
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'a_parameter', '[ID]' ),
CompletionEntryMatcher( 'another_parameter', '[ID]' ),
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_Unicode_InLine_test( app ):
RunTest( app, {
'description': 'return completions for strings with multi-byte chars',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'unicode.py' ),
'line_num' : 7,
'column_num': 14
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'center', 'function: builtins.str.center' )
),
'errors': empty(),
} )
},
} )
<|fim▁end|> | = request
request.update( data )
return BuildRequest( **kw )
|
<|file_name|>get_completions_test.py<|end_file_name|><|fim▁begin|># coding: utf-8
#
# Copyright (C) 2015 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ycmd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ycmd. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import * # noqa
from nose.tools import eq_
from hamcrest import ( assert_that, has_item, has_items, has_entry,
has_entries, contains, empty, contains_string )
from ycmd.utils import ReadFile
from ycmd.tests.python import PathToTestFile, SharedYcmd
from ycmd.tests.test_utils import ( BuildRequest, CompletionEntryMatcher,
CompletionLocationMatcher )
import http.client
@SharedYcmd
def GetCompletions_Basic_test( app ):
filepath = PathToTestFile( 'basic.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
line_num = 7,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results,
has_items(
CompletionEntryMatcher( 'a' ),
CompletionEntryMatcher( 'b' ),
CompletionLocationMatcher( 'line_num', 3 ),
CompletionLocationMatcher( 'line_num', 4 ),
CompletionLocationMatcher( 'column_num', 10 ),
CompletionLocationMatcher( 'filepath', filepath ) ) )
@SharedYcmd
def GetCompletions_UnicodeDescription_test( app ):
filepath = PathToTestFile( 'unicode.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
force_semantic = True,
line_num = 5,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results, has_item(
has_entry( 'detailed_info', contains_string( u'aafäö' ) ) ) )
def RunTest( app, test ):
"""
Method to run a simple completion test and verify the result
test is a dictionary containing:
'request': kwargs for BuildRequest
'expect': {
'response': server response code (e.g. httplib.OK)
'data': matcher for the server response json
}
"""
contents = ReadFile( test[ 'request' ][ 'filepath' ] )
def CombineRequest( request, data ):
kw = request
request.update( data )
return BuildRequest( **kw )
app.post_json( '/event_notification',
CombineRequest( test[ 'request' ], {
'event_name': 'FileReadyToParse',
'contents': contents,
} ) )
# We ignore errors here and we check the response code ourself.
# This is to allow testing of requests returning errors.
response = app.post_json( '/completions',
CombineRequest( test[ 'request' ], {
'contents': contents
} ),
expect_errors = True )
eq_( response.status_code, test[ 'expect' ][ 'response' ] )
assert_that( response.json, test[ 'expect' ][ 'data' ] )
@SharedYcmd
def GetCompletions_NoSuggestions_Fallback_test( app ):
# Python completer doesn't raise NO_COMPLETIONS_MESSAGE, so this is a
# different code path to the Clang completer cases
# TESTCASE2 (general_fallback/lang_python.py)
Ru<|fim_middle|>
@SharedYcmd
def GetCompletions_Unicode_InLine_test( app ):
RunTest( app, {
'description': 'return completions for strings with multi-byte chars',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'unicode.py' ),
'line_num' : 7,
'column_num': 14
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'center', 'function: builtins.str.center' )
),
'errors': empty(),
} )
},
} )
<|fim▁end|> | nTest( app, {
'description': 'param jedi does not know about (id). query="a_p"',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'general_fallback',
'lang_python.py' ),
'line_num' : 28,
'column_num': 20,
'force_semantic': False,
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'a_parameter', '[ID]' ),
CompletionEntryMatcher( 'another_parameter', '[ID]' ),
),
'errors': empty(),
} )
},
} )
|
<|file_name|>get_completions_test.py<|end_file_name|><|fim▁begin|># coding: utf-8
#
# Copyright (C) 2015 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ycmd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ycmd. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import * # noqa
from nose.tools import eq_
from hamcrest import ( assert_that, has_item, has_items, has_entry,
has_entries, contains, empty, contains_string )
from ycmd.utils import ReadFile
from ycmd.tests.python import PathToTestFile, SharedYcmd
from ycmd.tests.test_utils import ( BuildRequest, CompletionEntryMatcher,
CompletionLocationMatcher )
import http.client
@SharedYcmd
def GetCompletions_Basic_test( app ):
filepath = PathToTestFile( 'basic.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
line_num = 7,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results,
has_items(
CompletionEntryMatcher( 'a' ),
CompletionEntryMatcher( 'b' ),
CompletionLocationMatcher( 'line_num', 3 ),
CompletionLocationMatcher( 'line_num', 4 ),
CompletionLocationMatcher( 'column_num', 10 ),
CompletionLocationMatcher( 'filepath', filepath ) ) )
@SharedYcmd
def GetCompletions_UnicodeDescription_test( app ):
filepath = PathToTestFile( 'unicode.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
force_semantic = True,
line_num = 5,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results, has_item(
has_entry( 'detailed_info', contains_string( u'aafäö' ) ) ) )
def RunTest( app, test ):
"""
Method to run a simple completion test and verify the result
test is a dictionary containing:
'request': kwargs for BuildRequest
'expect': {
'response': server response code (e.g. httplib.OK)
'data': matcher for the server response json
}
"""
contents = ReadFile( test[ 'request' ][ 'filepath' ] )
def CombineRequest( request, data ):
kw = request
request.update( data )
return BuildRequest( **kw )
app.post_json( '/event_notification',
CombineRequest( test[ 'request' ], {
'event_name': 'FileReadyToParse',
'contents': contents,
} ) )
# We ignore errors here and we check the response code ourself.
# This is to allow testing of requests returning errors.
response = app.post_json( '/completions',
CombineRequest( test[ 'request' ], {
'contents': contents
} ),
expect_errors = True )
eq_( response.status_code, test[ 'expect' ][ 'response' ] )
assert_that( response.json, test[ 'expect' ][ 'data' ] )
@SharedYcmd
def GetCompletions_NoSuggestions_Fallback_test( app ):
# Python completer doesn't raise NO_COMPLETIONS_MESSAGE, so this is a
# different code path to the Clang completer cases
# TESTCASE2 (general_fallback/lang_python.py)
RunTest( app, {
'description': 'param jedi does not know about (id). query="a_p"',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'general_fallback',
'lang_python.py' ),
'line_num' : 28,
'column_num': 20,
'force_semantic': False,
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'a_parameter', '[ID]' ),
CompletionEntryMatcher( 'another_parameter', '[ID]' ),
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_Unicode_InLine_test( app ):
Ru<|fim_middle|>
<|fim▁end|> | nTest( app, {
'description': 'return completions for strings with multi-byte chars',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'unicode.py' ),
'line_num' : 7,
'column_num': 14
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'center', 'function: builtins.str.center' )
),
'errors': empty(),
} )
},
} )
|
<|file_name|>get_completions_test.py<|end_file_name|><|fim▁begin|># coding: utf-8
#
# Copyright (C) 2015 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ycmd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ycmd. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import * # noqa
from nose.tools import eq_
from hamcrest import ( assert_that, has_item, has_items, has_entry,
has_entries, contains, empty, contains_string )
from ycmd.utils import ReadFile
from ycmd.tests.python import PathToTestFile, SharedYcmd
from ycmd.tests.test_utils import ( BuildRequest, CompletionEntryMatcher,
CompletionLocationMatcher )
import http.client
@SharedYcmd
def <|fim_middle|>( app ):
filepath = PathToTestFile( 'basic.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
line_num = 7,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results,
has_items(
CompletionEntryMatcher( 'a' ),
CompletionEntryMatcher( 'b' ),
CompletionLocationMatcher( 'line_num', 3 ),
CompletionLocationMatcher( 'line_num', 4 ),
CompletionLocationMatcher( 'column_num', 10 ),
CompletionLocationMatcher( 'filepath', filepath ) ) )
@SharedYcmd
def GetCompletions_UnicodeDescription_test( app ):
filepath = PathToTestFile( 'unicode.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
force_semantic = True,
line_num = 5,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results, has_item(
has_entry( 'detailed_info', contains_string( u'aafäö' ) ) ) )
def RunTest( app, test ):
"""
Method to run a simple completion test and verify the result
test is a dictionary containing:
'request': kwargs for BuildRequest
'expect': {
'response': server response code (e.g. httplib.OK)
'data': matcher for the server response json
}
"""
contents = ReadFile( test[ 'request' ][ 'filepath' ] )
def CombineRequest( request, data ):
kw = request
request.update( data )
return BuildRequest( **kw )
app.post_json( '/event_notification',
CombineRequest( test[ 'request' ], {
'event_name': 'FileReadyToParse',
'contents': contents,
} ) )
# We ignore errors here and we check the response code ourself.
# This is to allow testing of requests returning errors.
response = app.post_json( '/completions',
CombineRequest( test[ 'request' ], {
'contents': contents
} ),
expect_errors = True )
eq_( response.status_code, test[ 'expect' ][ 'response' ] )
assert_that( response.json, test[ 'expect' ][ 'data' ] )
@SharedYcmd
def GetCompletions_NoSuggestions_Fallback_test( app ):
# Python completer doesn't raise NO_COMPLETIONS_MESSAGE, so this is a
# different code path to the Clang completer cases
# TESTCASE2 (general_fallback/lang_python.py)
RunTest( app, {
'description': 'param jedi does not know about (id). query="a_p"',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'general_fallback',
'lang_python.py' ),
'line_num' : 28,
'column_num': 20,
'force_semantic': False,
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'a_parameter', '[ID]' ),
CompletionEntryMatcher( 'another_parameter', '[ID]' ),
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_Unicode_InLine_test( app ):
RunTest( app, {
'description': 'return completions for strings with multi-byte chars',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'unicode.py' ),
'line_num' : 7,
'column_num': 14
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'center', 'function: builtins.str.center' )
),
'errors': empty(),
} )
},
} )
<|fim▁end|> | GetCompletions_Basic_test |
<|file_name|>get_completions_test.py<|end_file_name|><|fim▁begin|># coding: utf-8
#
# Copyright (C) 2015 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ycmd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ycmd. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import * # noqa
from nose.tools import eq_
from hamcrest import ( assert_that, has_item, has_items, has_entry,
has_entries, contains, empty, contains_string )
from ycmd.utils import ReadFile
from ycmd.tests.python import PathToTestFile, SharedYcmd
from ycmd.tests.test_utils import ( BuildRequest, CompletionEntryMatcher,
CompletionLocationMatcher )
import http.client
@SharedYcmd
def GetCompletions_Basic_test( app ):
filepath = PathToTestFile( 'basic.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
line_num = 7,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results,
has_items(
CompletionEntryMatcher( 'a' ),
CompletionEntryMatcher( 'b' ),
CompletionLocationMatcher( 'line_num', 3 ),
CompletionLocationMatcher( 'line_num', 4 ),
CompletionLocationMatcher( 'column_num', 10 ),
CompletionLocationMatcher( 'filepath', filepath ) ) )
@SharedYcmd
def <|fim_middle|>( app ):
filepath = PathToTestFile( 'unicode.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
force_semantic = True,
line_num = 5,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results, has_item(
has_entry( 'detailed_info', contains_string( u'aafäö' ) ) ) )
def RunTest( app, test ):
"""
Method to run a simple completion test and verify the result
test is a dictionary containing:
'request': kwargs for BuildRequest
'expect': {
'response': server response code (e.g. httplib.OK)
'data': matcher for the server response json
}
"""
contents = ReadFile( test[ 'request' ][ 'filepath' ] )
def CombineRequest( request, data ):
kw = request
request.update( data )
return BuildRequest( **kw )
app.post_json( '/event_notification',
CombineRequest( test[ 'request' ], {
'event_name': 'FileReadyToParse',
'contents': contents,
} ) )
# We ignore errors here and we check the response code ourself.
# This is to allow testing of requests returning errors.
response = app.post_json( '/completions',
CombineRequest( test[ 'request' ], {
'contents': contents
} ),
expect_errors = True )
eq_( response.status_code, test[ 'expect' ][ 'response' ] )
assert_that( response.json, test[ 'expect' ][ 'data' ] )
@SharedYcmd
def GetCompletions_NoSuggestions_Fallback_test( app ):
# Python completer doesn't raise NO_COMPLETIONS_MESSAGE, so this is a
# different code path to the Clang completer cases
# TESTCASE2 (general_fallback/lang_python.py)
RunTest( app, {
'description': 'param jedi does not know about (id). query="a_p"',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'general_fallback',
'lang_python.py' ),
'line_num' : 28,
'column_num': 20,
'force_semantic': False,
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'a_parameter', '[ID]' ),
CompletionEntryMatcher( 'another_parameter', '[ID]' ),
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_Unicode_InLine_test( app ):
RunTest( app, {
'description': 'return completions for strings with multi-byte chars',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'unicode.py' ),
'line_num' : 7,
'column_num': 14
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'center', 'function: builtins.str.center' )
),
'errors': empty(),
} )
},
} )
<|fim▁end|> | GetCompletions_UnicodeDescription_test |
<|file_name|>get_completions_test.py<|end_file_name|><|fim▁begin|># coding: utf-8
#
# Copyright (C) 2015 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ycmd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ycmd. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import * # noqa
from nose.tools import eq_
from hamcrest import ( assert_that, has_item, has_items, has_entry,
has_entries, contains, empty, contains_string )
from ycmd.utils import ReadFile
from ycmd.tests.python import PathToTestFile, SharedYcmd
from ycmd.tests.test_utils import ( BuildRequest, CompletionEntryMatcher,
CompletionLocationMatcher )
import http.client
@SharedYcmd
def GetCompletions_Basic_test( app ):
filepath = PathToTestFile( 'basic.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
line_num = 7,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results,
has_items(
CompletionEntryMatcher( 'a' ),
CompletionEntryMatcher( 'b' ),
CompletionLocationMatcher( 'line_num', 3 ),
CompletionLocationMatcher( 'line_num', 4 ),
CompletionLocationMatcher( 'column_num', 10 ),
CompletionLocationMatcher( 'filepath', filepath ) ) )
@SharedYcmd
def GetCompletions_UnicodeDescription_test( app ):
filepath = PathToTestFile( 'unicode.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
force_semantic = True,
line_num = 5,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results, has_item(
has_entry( 'detailed_info', contains_string( u'aafäö' ) ) ) )
def Ru<|fim_middle|>app, test ):
"""
Method to run a simple completion test and verify the result
test is a dictionary containing:
'request': kwargs for BuildRequest
'expect': {
'response': server response code (e.g. httplib.OK)
'data': matcher for the server response json
}
"""
contents = ReadFile( test[ 'request' ][ 'filepath' ] )
def CombineRequest( request, data ):
kw = request
request.update( data )
return BuildRequest( **kw )
app.post_json( '/event_notification',
CombineRequest( test[ 'request' ], {
'event_name': 'FileReadyToParse',
'contents': contents,
} ) )
# We ignore errors here and we check the response code ourself.
# This is to allow testing of requests returning errors.
response = app.post_json( '/completions',
CombineRequest( test[ 'request' ], {
'contents': contents
} ),
expect_errors = True )
eq_( response.status_code, test[ 'expect' ][ 'response' ] )
assert_that( response.json, test[ 'expect' ][ 'data' ] )
@SharedYcmd
def GetCompletions_NoSuggestions_Fallback_test( app ):
# Python completer doesn't raise NO_COMPLETIONS_MESSAGE, so this is a
# different code path to the Clang completer cases
# TESTCASE2 (general_fallback/lang_python.py)
RunTest( app, {
'description': 'param jedi does not know about (id). query="a_p"',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'general_fallback',
'lang_python.py' ),
'line_num' : 28,
'column_num': 20,
'force_semantic': False,
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'a_parameter', '[ID]' ),
CompletionEntryMatcher( 'another_parameter', '[ID]' ),
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_Unicode_InLine_test( app ):
RunTest( app, {
'description': 'return completions for strings with multi-byte chars',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'unicode.py' ),
'line_num' : 7,
'column_num': 14
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'center', 'function: builtins.str.center' )
),
'errors': empty(),
} )
},
} )
<|fim▁end|> | nTest( |
<|file_name|>get_completions_test.py<|end_file_name|><|fim▁begin|># coding: utf-8
#
# Copyright (C) 2015 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ycmd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ycmd. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import * # noqa
from nose.tools import eq_
from hamcrest import ( assert_that, has_item, has_items, has_entry,
has_entries, contains, empty, contains_string )
from ycmd.utils import ReadFile
from ycmd.tests.python import PathToTestFile, SharedYcmd
from ycmd.tests.test_utils import ( BuildRequest, CompletionEntryMatcher,
CompletionLocationMatcher )
import http.client
@SharedYcmd
def GetCompletions_Basic_test( app ):
filepath = PathToTestFile( 'basic.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
line_num = 7,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results,
has_items(
CompletionEntryMatcher( 'a' ),
CompletionEntryMatcher( 'b' ),
CompletionLocationMatcher( 'line_num', 3 ),
CompletionLocationMatcher( 'line_num', 4 ),
CompletionLocationMatcher( 'column_num', 10 ),
CompletionLocationMatcher( 'filepath', filepath ) ) )
@SharedYcmd
def GetCompletions_UnicodeDescription_test( app ):
filepath = PathToTestFile( 'unicode.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
force_semantic = True,
line_num = 5,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results, has_item(
has_entry( 'detailed_info', contains_string( u'aafäö' ) ) ) )
def RunTest( app, test ):
"""
Method to run a simple completion test and verify the result
test is a dictionary containing:
'request': kwargs for BuildRequest
'expect': {
'response': server response code (e.g. httplib.OK)
'data': matcher for the server response json
}
"""
contents = ReadFile( test[ 'request' ][ 'filepath' ] )
def Co<|fim_middle|>request, data ):
kw = request
request.update( data )
return BuildRequest( **kw )
app.post_json( '/event_notification',
CombineRequest( test[ 'request' ], {
'event_name': 'FileReadyToParse',
'contents': contents,
} ) )
# We ignore errors here and we check the response code ourself.
# This is to allow testing of requests returning errors.
response = app.post_json( '/completions',
CombineRequest( test[ 'request' ], {
'contents': contents
} ),
expect_errors = True )
eq_( response.status_code, test[ 'expect' ][ 'response' ] )
assert_that( response.json, test[ 'expect' ][ 'data' ] )
@SharedYcmd
def GetCompletions_NoSuggestions_Fallback_test( app ):
# Python completer doesn't raise NO_COMPLETIONS_MESSAGE, so this is a
# different code path to the Clang completer cases
# TESTCASE2 (general_fallback/lang_python.py)
RunTest( app, {
'description': 'param jedi does not know about (id). query="a_p"',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'general_fallback',
'lang_python.py' ),
'line_num' : 28,
'column_num': 20,
'force_semantic': False,
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'a_parameter', '[ID]' ),
CompletionEntryMatcher( 'another_parameter', '[ID]' ),
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_Unicode_InLine_test( app ):
RunTest( app, {
'description': 'return completions for strings with multi-byte chars',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'unicode.py' ),
'line_num' : 7,
'column_num': 14
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'center', 'function: builtins.str.center' )
),
'errors': empty(),
} )
},
} )
<|fim▁end|> | mbineRequest( |
<|file_name|>get_completions_test.py<|end_file_name|><|fim▁begin|># coding: utf-8
#
# Copyright (C) 2015 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ycmd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ycmd. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import * # noqa
from nose.tools import eq_
from hamcrest import ( assert_that, has_item, has_items, has_entry,
has_entries, contains, empty, contains_string )
from ycmd.utils import ReadFile
from ycmd.tests.python import PathToTestFile, SharedYcmd
from ycmd.tests.test_utils import ( BuildRequest, CompletionEntryMatcher,
CompletionLocationMatcher )
import http.client
@SharedYcmd
def GetCompletions_Basic_test( app ):
filepath = PathToTestFile( 'basic.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
line_num = 7,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results,
has_items(
CompletionEntryMatcher( 'a' ),
CompletionEntryMatcher( 'b' ),
CompletionLocationMatcher( 'line_num', 3 ),
CompletionLocationMatcher( 'line_num', 4 ),
CompletionLocationMatcher( 'column_num', 10 ),
CompletionLocationMatcher( 'filepath', filepath ) ) )
@SharedYcmd
def GetCompletions_UnicodeDescription_test( app ):
filepath = PathToTestFile( 'unicode.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
force_semantic = True,
line_num = 5,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results, has_item(
has_entry( 'detailed_info', contains_string( u'aafäö' ) ) ) )
def RunTest( app, test ):
"""
Method to run a simple completion test and verify the result
test is a dictionary containing:
'request': kwargs for BuildRequest
'expect': {
'response': server response code (e.g. httplib.OK)
'data': matcher for the server response json
}
"""
contents = ReadFile( test[ 'request' ][ 'filepath' ] )
def CombineRequest( request, data ):
kw = request
request.update( data )
return BuildRequest( **kw )
app.post_json( '/event_notification',
CombineRequest( test[ 'request' ], {
'event_name': 'FileReadyToParse',
'contents': contents,
} ) )
# We ignore errors here and we check the response code ourself.
# This is to allow testing of requests returning errors.
response = app.post_json( '/completions',
CombineRequest( test[ 'request' ], {
'contents': contents
} ),
expect_errors = True )
eq_( response.status_code, test[ 'expect' ][ 'response' ] )
assert_that( response.json, test[ 'expect' ][ 'data' ] )
@SharedYcmd
def Ge<|fim_middle|>app ):
# Python completer doesn't raise NO_COMPLETIONS_MESSAGE, so this is a
# different code path to the Clang completer cases
# TESTCASE2 (general_fallback/lang_python.py)
RunTest( app, {
'description': 'param jedi does not know about (id). query="a_p"',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'general_fallback',
'lang_python.py' ),
'line_num' : 28,
'column_num': 20,
'force_semantic': False,
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'a_parameter', '[ID]' ),
CompletionEntryMatcher( 'another_parameter', '[ID]' ),
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_Unicode_InLine_test( app ):
RunTest( app, {
'description': 'return completions for strings with multi-byte chars',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'unicode.py' ),
'line_num' : 7,
'column_num': 14
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'center', 'function: builtins.str.center' )
),
'errors': empty(),
} )
},
} )
<|fim▁end|> | tCompletions_NoSuggestions_Fallback_test( |
<|file_name|>get_completions_test.py<|end_file_name|><|fim▁begin|># coding: utf-8
#
# Copyright (C) 2015 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ycmd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ycmd. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import * # noqa
from nose.tools import eq_
from hamcrest import ( assert_that, has_item, has_items, has_entry,
has_entries, contains, empty, contains_string )
from ycmd.utils import ReadFile
from ycmd.tests.python import PathToTestFile, SharedYcmd
from ycmd.tests.test_utils import ( BuildRequest, CompletionEntryMatcher,
CompletionLocationMatcher )
import http.client
@SharedYcmd
def GetCompletions_Basic_test( app ):
filepath = PathToTestFile( 'basic.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
line_num = 7,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results,
has_items(
CompletionEntryMatcher( 'a' ),
CompletionEntryMatcher( 'b' ),
CompletionLocationMatcher( 'line_num', 3 ),
CompletionLocationMatcher( 'line_num', 4 ),
CompletionLocationMatcher( 'column_num', 10 ),
CompletionLocationMatcher( 'filepath', filepath ) ) )
@SharedYcmd
def GetCompletions_UnicodeDescription_test( app ):
filepath = PathToTestFile( 'unicode.py' )
completion_data = BuildRequest( filepath = filepath,
filetype = 'python',
contents = ReadFile( filepath ),
force_semantic = True,
line_num = 5,
column_num = 3)
results = app.post_json( '/completions',
completion_data ).json[ 'completions' ]
assert_that( results, has_item(
has_entry( 'detailed_info', contains_string( u'aafäö' ) ) ) )
def RunTest( app, test ):
"""
Method to run a simple completion test and verify the result
test is a dictionary containing:
'request': kwargs for BuildRequest
'expect': {
'response': server response code (e.g. httplib.OK)
'data': matcher for the server response json
}
"""
contents = ReadFile( test[ 'request' ][ 'filepath' ] )
def CombineRequest( request, data ):
kw = request
request.update( data )
return BuildRequest( **kw )
app.post_json( '/event_notification',
CombineRequest( test[ 'request' ], {
'event_name': 'FileReadyToParse',
'contents': contents,
} ) )
# We ignore errors here and we check the response code ourself.
# This is to allow testing of requests returning errors.
response = app.post_json( '/completions',
CombineRequest( test[ 'request' ], {
'contents': contents
} ),
expect_errors = True )
eq_( response.status_code, test[ 'expect' ][ 'response' ] )
assert_that( response.json, test[ 'expect' ][ 'data' ] )
@SharedYcmd
def GetCompletions_NoSuggestions_Fallback_test( app ):
# Python completer doesn't raise NO_COMPLETIONS_MESSAGE, so this is a
# different code path to the Clang completer cases
# TESTCASE2 (general_fallback/lang_python.py)
RunTest( app, {
'description': 'param jedi does not know about (id). query="a_p"',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'general_fallback',
'lang_python.py' ),
'line_num' : 28,
'column_num': 20,
'force_semantic': False,
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'a_parameter', '[ID]' ),
CompletionEntryMatcher( 'another_parameter', '[ID]' ),
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def Ge<|fim_middle|>app ):
RunTest( app, {
'description': 'return completions for strings with multi-byte chars',
'request': {
'filetype' : 'python',
'filepath' : PathToTestFile( 'unicode.py' ),
'line_num' : 7,
'column_num': 14
},
'expect': {
'response': http.client.OK,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'center', 'function: builtins.str.center' )
),
'errors': empty(),
} )
},
} )
<|fim▁end|> | tCompletions_Unicode_InLine_test( |
<|file_name|>0295_doc_tslug.py<|end_file_name|><|fim▁begin|># Generated by Django 2.2 on 2019-06-20 09:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('scoping', '0294_titlevecmodel'),<|fim▁hole|> operations = [
migrations.AddField(
model_name='doc',
name='tslug',
field=models.TextField(null=True),
),
]<|fim▁end|> | ]
|
<|file_name|>0295_doc_tslug.py<|end_file_name|><|fim▁begin|># Generated by Django 2.2 on 2019-06-20 09:39
from django.db import migrations, models
class Migration(migrations.Migration):
<|fim_middle|>
<|fim▁end|> | dependencies = [
('scoping', '0294_titlevecmodel'),
]
operations = [
migrations.AddField(
model_name='doc',
name='tslug',
field=models.TextField(null=True),
),
] |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):<|fim▁hole|> for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1<|fim▁end|> | self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s' |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
<|fim_middle|>
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message')) |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
<|fim_middle|>
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message')) |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
<|fim_middle|>
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict() |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
<|fim_middle|>
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | self.db(self.db.World.id == wid).update(randomNumber=randomNumber) |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
<|fim_middle|>
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message')) |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
<|fim_middle|>
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message')) |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
<|fim_middle|>
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | super(RawDal, self).__init__()
self.world_updates = [] |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
<|fim_middle|>
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0] |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
<|fim_middle|>
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | self.world_updates.extend([randomNumber, wid]) |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
<|fim_middle|>
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates) |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
<|fim_middle|>
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message')) |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
<|fim_middle|>
<|fim▁end|> | try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1 |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
<|fim_middle|>
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | self.db.define_table('World', Field('randomNumber', 'integer')) |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
<|fim_middle|>
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | self.db.define_table('Fortune', Field('message')) |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def <|fim_middle|>(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | __init__ |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def <|fim_middle|>(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | get_world |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def <|fim_middle|>(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | update_world |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def <|fim_middle|>(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | get_fortunes |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def <|fim_middle|>(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | __init__ |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def <|fim_middle|>(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | get_world |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def <|fim_middle|>(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | update_world |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def <|fim_middle|>(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | flush_world_updates |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def <|fim_middle|>(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | get_fortunes |
<|file_name|>database.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def <|fim_middle|>(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
<|fim▁end|> | num_queries |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>class CheckBase(object):
"""
Base class for checks.
"""
hooks = []
# pylint: disable=W0105
"""Git hooks to which this class applies. A list of strings."""
def execute(self, hook):
"""
Executes the check.
:param hook: The name of the hook being run.
:type hook: :class:`str`
:returns: ``True`` if the check passed, ``False`` if not.
:rtype: :class:`bool`
<|fim▁hole|> pass<|fim▁end|> | """ |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>
class CheckBase(object):
<|fim_middle|>
<|fim▁end|> | """
Base class for checks.
"""
hooks = []
# pylint: disable=W0105
"""Git hooks to which this class applies. A list of strings."""
def execute(self, hook):
"""
Executes the check.
:param hook: The name of the hook being run.
:type hook: :class:`str`
:returns: ``True`` if the check passed, ``False`` if not.
:rtype: :class:`bool`
"""
pass |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>
class CheckBase(object):
"""
Base class for checks.
"""
hooks = []
# pylint: disable=W0105
"""Git hooks to which this class applies. A list of strings."""
def execute(self, hook):
<|fim_middle|>
<|fim▁end|> | """
Executes the check.
:param hook: The name of the hook being run.
:type hook: :class:`str`
:returns: ``True`` if the check passed, ``False`` if not.
:rtype: :class:`bool`
"""
pass |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>
class CheckBase(object):
"""
Base class for checks.
"""
hooks = []
# pylint: disable=W0105
"""Git hooks to which this class applies. A list of strings."""
def <|fim_middle|>(self, hook):
"""
Executes the check.
:param hook: The name of the hook being run.
:type hook: :class:`str`
:returns: ``True`` if the check passed, ``False`` if not.
:rtype: :class:`bool`
"""
pass
<|fim▁end|> | execute |
<|file_name|>problem404.py<|end_file_name|><|fim▁begin|><|fim▁hole|># Crisscross Ellipses
# ===================
# Published on Sunday, 2nd December 2012, 01:00 am
#
# Ea is an ellipse with an equation of the form x2 + 4y2 = 4a2. Ea' is the
# rotated image of Ea by θ degrees counterclockwise around the origin O(0, 0)
# for 0° θ 90°. b is the distance to the origin of the two intersection
# points closest to the origin and c is the distance of the two other
# intersection points. We call an ordered triplet (a, b, c) a canonical
# ellipsoidal triplet if a, b and c are positive integers. For example, (209,
# 247, 286) is a canonical ellipsoidal triplet. Let C(N) be the number of
# distinct canonical ellipsoidal triplets (a, b, c) for a N. It can be
# verified that C(103) = 7, C(104) = 106 and C(106) = 11845. Find C(1017).
import projecteuler as pe
def main():
pass
if __name__ == "__main__":
main()<|fim▁end|> | # -*- coding: utf-8 -*-
# ProjectEuler/src/python/problem404.py
# |
<|file_name|>problem404.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# ProjectEuler/src/python/problem404.py
#
# Crisscross Ellipses
# ===================
# Published on Sunday, 2nd December 2012, 01:00 am
#
# Ea is an ellipse with an equation of the form x2 + 4y2 = 4a2. Ea' is the
# rotated image of Ea by θ degrees counterclockwise around the origin O(0, 0)
# for 0° θ 90°. b is the distance to the origin of the two intersection
# points closest to the origin and c is the distance of the two other
# intersection points. We call an ordered triplet (a, b, c) a canonical
# ellipsoidal triplet if a, b and c are positive integers. For example, (209,
# 247, 286) is a canonical ellipsoidal triplet. Let C(N) be the number of
# distinct canonical ellipsoidal triplets (a, b, c) for a N. It can be
# verified that C(103) = 7, C(104) = 106 and C(106) = 11845. Find C(1017).
import projecteuler as pe
def main():
pass
<|fim_middle|>
_name__ == "__main__":
main()
<|fim▁end|> | if _ |
Subsets and Splits