hexsha
stringlengths
40
40
size
int64
4
996k
ext
stringclasses
8 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
4
996k
avg_line_length
float64
1.33
58.2k
max_line_length
int64
2
323k
alphanum_fraction
float64
0
0.97
content_no_comment
stringlengths
0
946k
is_comment_constant_removed
bool
2 classes
is_sharp_comment_removed
bool
1 class
f7fe5cc57b8dc3dbda90bbec12570fac6442abf1
778,605
py
Python
test/unit/test_cloudant_v1.py
IBM/cloudant-python-sdk
e5c6dfb7a0b932025e3249dece60658e390a4e8d
[ "Apache-2.0" ]
19
2020-11-10T13:50:54.000Z
2022-03-28T03:35:53.000Z
test/unit/test_cloudant_v1.py
IBM/cloudant-python-sdk
e5c6dfb7a0b932025e3249dece60658e390a4e8d
[ "Apache-2.0" ]
129
2020-08-19T14:20:18.000Z
2022-03-31T07:39:30.000Z
test/unit/test_cloudant_v1.py
IBM/cloudant-python-sdk
e5c6dfb7a0b932025e3249dece60658e390a4e8d
[ "Apache-2.0" ]
5
2020-06-29T15:25:41.000Z
2021-08-16T23:33:35.000Z
# -*- coding: utf-8 -*- # (C) Copyright IBM Corp. 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Unit Tests for CloudantV1 """ from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime import base64 import inspect import io import json import os import pytest import re import requests import requests.models import responses import tempfile import urllib import gzip from ibmcloudant.cloudant_v1 import * _service = CloudantV1( authenticator=NoAuthAuthenticator() ) _base_url = 'http://localhost:5984' _service.set_service_url(_base_url) ############################################################################## # Start of Service: Server ############################################################################## # region class TestNewInstance(): """ Test Class for new_instance """ def test_new_instance(self): """ new_instance() """ os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): """ new_instance_without_authenticator() """ with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestGetServerInformation(): """ Test Class for get_server_information """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_server_information_all_params(self): """ get_server_information() """ # Set up mock url = self.preprocess_url(_base_url + '/') mock_response = '{"couchdb": "couchdb", "features": ["features"], "vendor": {"name": "name", "variant": "variant", "version": "version"}, "version": "version", "features_flags": ["features_flags"]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Invoke method response = _service.get_server_information() # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_server_information_all_params_with_retries(self): # Enable retries and run test_get_server_information_all_params. _service.enable_retries() self.test_get_server_information_all_params() # Disable retries and run test_get_server_information_all_params. _service.disable_retries() self.test_get_server_information_all_params() class TestGetMembershipInformation(): """ Test Class for get_membership_information """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_membership_information_all_params(self): """ get_membership_information() """ # Set up mock url = self.preprocess_url(_base_url + '/_membership') mock_response = '{"all_nodes": ["all_nodes"], "cluster_nodes": ["cluster_nodes"]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Invoke method response = _service.get_membership_information() # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_membership_information_all_params_with_retries(self): # Enable retries and run test_get_membership_information_all_params. _service.enable_retries() self.test_get_membership_information_all_params() # Disable retries and run test_get_membership_information_all_params. _service.disable_retries() self.test_get_membership_information_all_params() class TestGetUuids(): """ Test Class for get_uuids """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_uuids_all_params(self): """ get_uuids() """ # Set up mock url = self.preprocess_url(_base_url + '/_uuids') mock_response = '{"uuids": ["uuids"]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values count = 1 # Invoke method response = _service.get_uuids( count=count, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'count={}'.format(count) in query_string def test_get_uuids_all_params_with_retries(self): # Enable retries and run test_get_uuids_all_params. _service.enable_retries() self.test_get_uuids_all_params() # Disable retries and run test_get_uuids_all_params. _service.disable_retries() self.test_get_uuids_all_params() @responses.activate def test_get_uuids_required_params(self): """ test_get_uuids_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/_uuids') mock_response = '{"uuids": ["uuids"]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Invoke method response = _service.get_uuids() # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_uuids_required_params_with_retries(self): # Enable retries and run test_get_uuids_required_params. _service.enable_retries() self.test_get_uuids_required_params() # Disable retries and run test_get_uuids_required_params. _service.disable_retries() self.test_get_uuids_required_params() class TestGetCapacityThroughputInformation(): """ Test Class for get_capacity_throughput_information """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_capacity_throughput_information_all_params(self): """ get_capacity_throughput_information() """ # Set up mock url = self.preprocess_url(_base_url + '/_api/v2/user/capacity/throughput') mock_response = '{"current": {"throughput": {"blocks": 0, "query": 0, "read": 0, "write": 0}}, "target": {"throughput": {"blocks": 0, "query": 0, "read": 0, "write": 0}}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Invoke method response = _service.get_capacity_throughput_information() # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_capacity_throughput_information_all_params_with_retries(self): # Enable retries and run test_get_capacity_throughput_information_all_params. _service.enable_retries() self.test_get_capacity_throughput_information_all_params() # Disable retries and run test_get_capacity_throughput_information_all_params. _service.disable_retries() self.test_get_capacity_throughput_information_all_params() class TestPutCapacityThroughputConfiguration(): """ Test Class for put_capacity_throughput_configuration """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_put_capacity_throughput_configuration_all_params(self): """ put_capacity_throughput_configuration() """ # Set up mock url = self.preprocess_url(_base_url + '/_api/v2/user/capacity/throughput') mock_response = '{"current": {"throughput": {"blocks": 0, "query": 0, "read": 0, "write": 0}}, "target": {"throughput": {"blocks": 0, "query": 0, "read": 0, "write": 0}}}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values blocks = 0 # Invoke method response = _service.put_capacity_throughput_configuration( blocks, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['blocks'] == 0 def test_put_capacity_throughput_configuration_all_params_with_retries(self): # Enable retries and run test_put_capacity_throughput_configuration_all_params. _service.enable_retries() self.test_put_capacity_throughput_configuration_all_params() # Disable retries and run test_put_capacity_throughput_configuration_all_params. _service.disable_retries() self.test_put_capacity_throughput_configuration_all_params() @responses.activate def test_put_capacity_throughput_configuration_value_error(self): """ test_put_capacity_throughput_configuration_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/_api/v2/user/capacity/throughput') mock_response = '{"current": {"throughput": {"blocks": 0, "query": 0, "read": 0, "write": 0}}, "target": {"throughput": {"blocks": 0, "query": 0, "read": 0, "write": 0}}}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values blocks = 0 # Pass in all but one required param and check for a ValueError req_param_dict = { "blocks": blocks, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.put_capacity_throughput_configuration(**req_copy) def test_put_capacity_throughput_configuration_value_error_with_retries(self): # Enable retries and run test_put_capacity_throughput_configuration_value_error. _service.enable_retries() self.test_put_capacity_throughput_configuration_value_error() # Disable retries and run test_put_capacity_throughput_configuration_value_error. _service.disable_retries() self.test_put_capacity_throughput_configuration_value_error() # endregion ############################################################################## # End of Service: Server ############################################################################## ############################################################################## # Start of Service: Changes ############################################################################## # region class TestNewInstance(): """ Test Class for new_instance """ def test_new_instance(self): """ new_instance() """ os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): """ new_instance_without_authenticator() """ with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestGetDbUpdates(): """ Test Class for get_db_updates """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_db_updates_all_params(self): """ get_db_updates() """ # Set up mock url = self.preprocess_url(_base_url + '/_db_updates') mock_response = '{"last_seq": "last_seq", "results": [{"account": "account", "db_name": "db_name", "seq": "seq", "type": "created"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values feed = 'normal' heartbeat = 0 timeout = 0 since = '0' # Invoke method response = _service.get_db_updates( feed=feed, heartbeat=heartbeat, timeout=timeout, since=since, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'feed={}'.format(feed) in query_string assert 'heartbeat={}'.format(heartbeat) in query_string assert 'timeout={}'.format(timeout) in query_string assert 'since={}'.format(since) in query_string def test_get_db_updates_all_params_with_retries(self): # Enable retries and run test_get_db_updates_all_params. _service.enable_retries() self.test_get_db_updates_all_params() # Disable retries and run test_get_db_updates_all_params. _service.disable_retries() self.test_get_db_updates_all_params() @responses.activate def test_get_db_updates_required_params(self): """ test_get_db_updates_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/_db_updates') mock_response = '{"last_seq": "last_seq", "results": [{"account": "account", "db_name": "db_name", "seq": "seq", "type": "created"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Invoke method response = _service.get_db_updates() # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_db_updates_required_params_with_retries(self): # Enable retries and run test_get_db_updates_required_params. _service.enable_retries() self.test_get_db_updates_required_params() # Disable retries and run test_get_db_updates_required_params. _service.disable_retries() self.test_get_db_updates_required_params() class TestPostChanges(): """ Test Class for post_changes """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_changes_all_params(self): """ post_changes() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_changes') mock_response = '{"last_seq": "last_seq", "pending": 7, "results": [{"changes": [{"rev": "rev"}], "deleted": false, "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "seq": "seq"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_ids = ['testString'] fields = ['testString'] selector = {} last_event_id = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False feed = 'normal' filter = 'testString' heartbeat = 0 include_docs = False limit = 0 seq_interval = 1 since = '0' style = 'main_only' timeout = 0 view = 'testString' # Invoke method response = _service.post_changes( db, doc_ids=doc_ids, fields=fields, selector=selector, last_event_id=last_event_id, att_encoding_info=att_encoding_info, attachments=attachments, conflicts=conflicts, descending=descending, feed=feed, filter=filter, heartbeat=heartbeat, include_docs=include_docs, limit=limit, seq_interval=seq_interval, since=since, style=style, timeout=timeout, view=view, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'conflicts={}'.format('true' if conflicts else 'false') in query_string assert 'descending={}'.format('true' if descending else 'false') in query_string assert 'feed={}'.format(feed) in query_string assert 'filter={}'.format(filter) in query_string assert 'heartbeat={}'.format(heartbeat) in query_string assert 'include_docs={}'.format('true' if include_docs else 'false') in query_string assert 'limit={}'.format(limit) in query_string assert 'seq_interval={}'.format(seq_interval) in query_string assert 'since={}'.format(since) in query_string assert 'style={}'.format(style) in query_string assert 'timeout={}'.format(timeout) in query_string assert 'view={}'.format(view) in query_string # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['doc_ids'] == ['testString'] assert req_body['fields'] == ['testString'] assert req_body['selector'] == {} def test_post_changes_all_params_with_retries(self): # Enable retries and run test_post_changes_all_params. _service.enable_retries() self.test_post_changes_all_params() # Disable retries and run test_post_changes_all_params. _service.disable_retries() self.test_post_changes_all_params() @responses.activate def test_post_changes_required_params(self): """ test_post_changes_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_changes') mock_response = '{"last_seq": "last_seq", "pending": 7, "results": [{"changes": [{"rev": "rev"}], "deleted": false, "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "seq": "seq"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_ids = ['testString'] fields = ['testString'] selector = {} # Invoke method response = _service.post_changes( db, doc_ids=doc_ids, fields=fields, selector=selector, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['doc_ids'] == ['testString'] assert req_body['fields'] == ['testString'] assert req_body['selector'] == {} def test_post_changes_required_params_with_retries(self): # Enable retries and run test_post_changes_required_params. _service.enable_retries() self.test_post_changes_required_params() # Disable retries and run test_post_changes_required_params. _service.disable_retries() self.test_post_changes_required_params() @responses.activate def test_post_changes_value_error(self): """ test_post_changes_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_changes') mock_response = '{"last_seq": "last_seq", "pending": 7, "results": [{"changes": [{"rev": "rev"}], "deleted": false, "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "seq": "seq"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_ids = ['testString'] fields = ['testString'] selector = {} # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_changes(**req_copy) def test_post_changes_value_error_with_retries(self): # Enable retries and run test_post_changes_value_error. _service.enable_retries() self.test_post_changes_value_error() # Disable retries and run test_post_changes_value_error. _service.disable_retries() self.test_post_changes_value_error() class TestPostChangesAsStream(): """ Test Class for post_changes_as_stream """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_changes_as_stream_all_params(self): """ post_changes_as_stream() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_changes') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_ids = ['0007741142412418284'] fields = ['testString'] selector = {} last_event_id = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False feed = 'normal' filter = 'testString' heartbeat = 0 include_docs = False limit = 0 seq_interval = 1 since = '0' style = 'main_only' timeout = 0 view = 'testString' # Invoke method response = _service.post_changes_as_stream( db, doc_ids=doc_ids, fields=fields, selector=selector, last_event_id=last_event_id, att_encoding_info=att_encoding_info, attachments=attachments, conflicts=conflicts, descending=descending, feed=feed, filter=filter, heartbeat=heartbeat, include_docs=include_docs, limit=limit, seq_interval=seq_interval, since=since, style=style, timeout=timeout, view=view, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'conflicts={}'.format('true' if conflicts else 'false') in query_string assert 'descending={}'.format('true' if descending else 'false') in query_string assert 'feed={}'.format(feed) in query_string assert 'filter={}'.format(filter) in query_string assert 'heartbeat={}'.format(heartbeat) in query_string assert 'include_docs={}'.format('true' if include_docs else 'false') in query_string assert 'limit={}'.format(limit) in query_string assert 'seq_interval={}'.format(seq_interval) in query_string assert 'since={}'.format(since) in query_string assert 'style={}'.format(style) in query_string assert 'timeout={}'.format(timeout) in query_string assert 'view={}'.format(view) in query_string # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['doc_ids'] == ['0007741142412418284'] assert req_body['fields'] == ['testString'] assert req_body['selector'] == {} # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_changes_as_stream_all_params_with_retries(self): # Enable retries and run test_post_changes_as_stream_all_params. _service.enable_retries() self.test_post_changes_as_stream_all_params() # Disable retries and run test_post_changes_as_stream_all_params. _service.disable_retries() self.test_post_changes_as_stream_all_params() @responses.activate def test_post_changes_as_stream_required_params(self): """ test_post_changes_as_stream_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_changes') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_ids = ['0007741142412418284'] fields = ['testString'] selector = {} # Invoke method response = _service.post_changes_as_stream( db, doc_ids=doc_ids, fields=fields, selector=selector, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['doc_ids'] == ['0007741142412418284'] assert req_body['fields'] == ['testString'] assert req_body['selector'] == {} # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_changes_as_stream_required_params_with_retries(self): # Enable retries and run test_post_changes_as_stream_required_params. _service.enable_retries() self.test_post_changes_as_stream_required_params() # Disable retries and run test_post_changes_as_stream_required_params. _service.disable_retries() self.test_post_changes_as_stream_required_params() @responses.activate def test_post_changes_as_stream_value_error(self): """ test_post_changes_as_stream_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_changes') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_ids = ['0007741142412418284'] fields = ['testString'] selector = {} # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_changes_as_stream(**req_copy) def test_post_changes_as_stream_value_error_with_retries(self): # Enable retries and run test_post_changes_as_stream_value_error. _service.enable_retries() self.test_post_changes_as_stream_value_error() # Disable retries and run test_post_changes_as_stream_value_error. _service.disable_retries() self.test_post_changes_as_stream_value_error() # endregion ############################################################################## # End of Service: Changes ############################################################################## ############################################################################## # Start of Service: Databases ############################################################################## # region class TestNewInstance(): """ Test Class for new_instance """ def test_new_instance(self): """ new_instance() """ os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): """ new_instance_without_authenticator() """ with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestHeadDatabase(): """ Test Class for head_database """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_head_database_all_params(self): """ head_database() """ # Set up mock url = self.preprocess_url(_base_url + '/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values db = 'testString' # Invoke method response = _service.head_database( db, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_head_database_all_params_with_retries(self): # Enable retries and run test_head_database_all_params. _service.enable_retries() self.test_head_database_all_params() # Disable retries and run test_head_database_all_params. _service.disable_retries() self.test_head_database_all_params() @responses.activate def test_head_database_value_error(self): """ test_head_database_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values db = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.head_database(**req_copy) def test_head_database_value_error_with_retries(self): # Enable retries and run test_head_database_value_error. _service.enable_retries() self.test_head_database_value_error() # Disable retries and run test_head_database_value_error. _service.disable_retries() self.test_head_database_value_error() class TestGetAllDbs(): """ Test Class for get_all_dbs """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_all_dbs_all_params(self): """ get_all_dbs() """ # Set up mock url = self.preprocess_url(_base_url + '/_all_dbs') mock_response = '["operation_response"]' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values descending = False endkey = 'testString' limit = 0 skip = 0 startkey = 'testString' # Invoke method response = _service.get_all_dbs( descending=descending, endkey=endkey, limit=limit, skip=skip, startkey=startkey, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'descending={}'.format('true' if descending else 'false') in query_string assert 'endkey={}'.format(endkey) in query_string assert 'limit={}'.format(limit) in query_string assert 'skip={}'.format(skip) in query_string assert 'startkey={}'.format(startkey) in query_string def test_get_all_dbs_all_params_with_retries(self): # Enable retries and run test_get_all_dbs_all_params. _service.enable_retries() self.test_get_all_dbs_all_params() # Disable retries and run test_get_all_dbs_all_params. _service.disable_retries() self.test_get_all_dbs_all_params() @responses.activate def test_get_all_dbs_required_params(self): """ test_get_all_dbs_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/_all_dbs') mock_response = '["operation_response"]' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Invoke method response = _service.get_all_dbs() # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_all_dbs_required_params_with_retries(self): # Enable retries and run test_get_all_dbs_required_params. _service.enable_retries() self.test_get_all_dbs_required_params() # Disable retries and run test_get_all_dbs_required_params. _service.disable_retries() self.test_get_all_dbs_required_params() class TestPostDbsInfo(): """ Test Class for post_dbs_info """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_dbs_info_all_params(self): """ post_dbs_info() """ # Set up mock url = self.preprocess_url(_base_url + '/_dbs_info') mock_response = '[{"error": "error", "info": {"cluster": {"n": 1, "q": 1, "r": 1, "w": 1}, "committed_update_seq": "committed_update_seq", "compact_running": false, "compacted_seq": "compacted_seq", "db_name": "db_name", "disk_format_version": 19, "doc_count": 0, "doc_del_count": 0, "engine": "engine", "props": {"partitioned": false}, "sizes": {"active": 6, "external": 8, "file": 4}, "update_seq": "update_seq", "uuid": "uuid"}, "key": "key"}]' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values keys = ['testString'] # Invoke method response = _service.post_dbs_info( keys, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['keys'] == ['testString'] def test_post_dbs_info_all_params_with_retries(self): # Enable retries and run test_post_dbs_info_all_params. _service.enable_retries() self.test_post_dbs_info_all_params() # Disable retries and run test_post_dbs_info_all_params. _service.disable_retries() self.test_post_dbs_info_all_params() @responses.activate def test_post_dbs_info_value_error(self): """ test_post_dbs_info_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/_dbs_info') mock_response = '[{"error": "error", "info": {"cluster": {"n": 1, "q": 1, "r": 1, "w": 1}, "committed_update_seq": "committed_update_seq", "compact_running": false, "compacted_seq": "compacted_seq", "db_name": "db_name", "disk_format_version": 19, "doc_count": 0, "doc_del_count": 0, "engine": "engine", "props": {"partitioned": false}, "sizes": {"active": 6, "external": 8, "file": 4}, "update_seq": "update_seq", "uuid": "uuid"}, "key": "key"}]' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values keys = ['testString'] # Pass in all but one required param and check for a ValueError req_param_dict = { "keys": keys, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_dbs_info(**req_copy) def test_post_dbs_info_value_error_with_retries(self): # Enable retries and run test_post_dbs_info_value_error. _service.enable_retries() self.test_post_dbs_info_value_error() # Disable retries and run test_post_dbs_info_value_error. _service.disable_retries() self.test_post_dbs_info_value_error() class TestDeleteDatabase(): """ Test Class for delete_database """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_delete_database_all_params(self): """ delete_database() """ # Set up mock url = self.preprocess_url(_base_url + '/testString') mock_response = '{"ok": true}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' # Invoke method response = _service.delete_database( db, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_delete_database_all_params_with_retries(self): # Enable retries and run test_delete_database_all_params. _service.enable_retries() self.test_delete_database_all_params() # Disable retries and run test_delete_database_all_params. _service.disable_retries() self.test_delete_database_all_params() @responses.activate def test_delete_database_value_error(self): """ test_delete_database_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString') mock_response = '{"ok": true}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_database(**req_copy) def test_delete_database_value_error_with_retries(self): # Enable retries and run test_delete_database_value_error. _service.enable_retries() self.test_delete_database_value_error() # Disable retries and run test_delete_database_value_error. _service.disable_retries() self.test_delete_database_value_error() class TestGetDatabaseInformation(): """ Test Class for get_database_information """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_database_information_all_params(self): """ get_database_information() """ # Set up mock url = self.preprocess_url(_base_url + '/testString') mock_response = '{"cluster": {"n": 1, "q": 1, "r": 1, "w": 1}, "committed_update_seq": "committed_update_seq", "compact_running": false, "compacted_seq": "compacted_seq", "db_name": "db_name", "disk_format_version": 19, "doc_count": 0, "doc_del_count": 0, "engine": "engine", "props": {"partitioned": false}, "sizes": {"active": 6, "external": 8, "file": 4}, "update_seq": "update_seq", "uuid": "uuid"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' # Invoke method response = _service.get_database_information( db, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_database_information_all_params_with_retries(self): # Enable retries and run test_get_database_information_all_params. _service.enable_retries() self.test_get_database_information_all_params() # Disable retries and run test_get_database_information_all_params. _service.disable_retries() self.test_get_database_information_all_params() @responses.activate def test_get_database_information_value_error(self): """ test_get_database_information_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString') mock_response = '{"cluster": {"n": 1, "q": 1, "r": 1, "w": 1}, "committed_update_seq": "committed_update_seq", "compact_running": false, "compacted_seq": "compacted_seq", "db_name": "db_name", "disk_format_version": 19, "doc_count": 0, "doc_del_count": 0, "engine": "engine", "props": {"partitioned": false}, "sizes": {"active": 6, "external": 8, "file": 4}, "update_seq": "update_seq", "uuid": "uuid"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_database_information(**req_copy) def test_get_database_information_value_error_with_retries(self): # Enable retries and run test_get_database_information_value_error. _service.enable_retries() self.test_get_database_information_value_error() # Disable retries and run test_get_database_information_value_error. _service.disable_retries() self.test_get_database_information_value_error() class TestPutDatabase(): """ Test Class for put_database """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_put_database_all_params(self): """ put_database() """ # Set up mock url = self.preprocess_url(_base_url + '/testString') mock_response = '{"ok": true}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Set up parameter values db = 'testString' partitioned = False q = 1 # Invoke method response = _service.put_database( db, partitioned=partitioned, q=q, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'partitioned={}'.format('true' if partitioned else 'false') in query_string assert 'q={}'.format(q) in query_string def test_put_database_all_params_with_retries(self): # Enable retries and run test_put_database_all_params. _service.enable_retries() self.test_put_database_all_params() # Disable retries and run test_put_database_all_params. _service.disable_retries() self.test_put_database_all_params() @responses.activate def test_put_database_required_params(self): """ test_put_database_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString') mock_response = '{"ok": true}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Set up parameter values db = 'testString' # Invoke method response = _service.put_database( db, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 def test_put_database_required_params_with_retries(self): # Enable retries and run test_put_database_required_params. _service.enable_retries() self.test_put_database_required_params() # Disable retries and run test_put_database_required_params. _service.disable_retries() self.test_put_database_required_params() @responses.activate def test_put_database_value_error(self): """ test_put_database_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString') mock_response = '{"ok": true}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Set up parameter values db = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.put_database(**req_copy) def test_put_database_value_error_with_retries(self): # Enable retries and run test_put_database_value_error. _service.enable_retries() self.test_put_database_value_error() # Disable retries and run test_put_database_value_error. _service.disable_retries() self.test_put_database_value_error() # endregion ############################################################################## # End of Service: Databases ############################################################################## ############################################################################## # Start of Service: Documents ############################################################################## # region class TestNewInstance(): """ Test Class for new_instance """ def test_new_instance(self): """ new_instance() """ os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): """ new_instance_without_authenticator() """ with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestHeadDocument(): """ Test Class for head_document """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_head_document_all_params(self): """ head_document() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values db = 'testString' doc_id = 'testString' if_none_match = 'testString' latest = False rev = 'testString' # Invoke method response = _service.head_document( db, doc_id, if_none_match=if_none_match, latest=latest, rev=rev, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'rev={}'.format(rev) in query_string def test_head_document_all_params_with_retries(self): # Enable retries and run test_head_document_all_params. _service.enable_retries() self.test_head_document_all_params() # Disable retries and run test_head_document_all_params. _service.disable_retries() self.test_head_document_all_params() @responses.activate def test_head_document_required_params(self): """ test_head_document_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Invoke method response = _service.head_document( db, doc_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_head_document_required_params_with_retries(self): # Enable retries and run test_head_document_required_params. _service.enable_retries() self.test_head_document_required_params() # Disable retries and run test_head_document_required_params. _service.disable_retries() self.test_head_document_required_params() @responses.activate def test_head_document_value_error(self): """ test_head_document_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.head_document(**req_copy) def test_head_document_value_error_with_retries(self): # Enable retries and run test_head_document_value_error. _service.enable_retries() self.test_head_document_value_error() # Disable retries and run test_head_document_value_error. _service.disable_retries() self.test_head_document_value_error() class TestPostDocument(): """ Test Class for post_document """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_document_all_params(self): """ post_document() """ # Set up mock url = self.preprocess_url(_base_url + '/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Document model document_model = {} document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' # Set up parameter values db = 'testString' document = document_model content_type = 'application/json' batch = 'ok' # Invoke method response = _service.post_document( db, document, content_type=content_type, batch=batch, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'batch={}'.format(batch) in query_string # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params def test_post_document_all_params_with_retries(self): # Enable retries and run test_post_document_all_params. _service.enable_retries() self.test_post_document_all_params() # Disable retries and run test_post_document_all_params. _service.disable_retries() self.test_post_document_all_params() @responses.activate def test_post_document_required_params(self): """ test_post_document_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Document model document_model = {} document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' # Set up parameter values db = 'testString' document = document_model # Invoke method response = _service.post_document( db, document, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params def test_post_document_required_params_with_retries(self): # Enable retries and run test_post_document_required_params. _service.enable_retries() self.test_post_document_required_params() # Disable retries and run test_post_document_required_params. _service.disable_retries() self.test_post_document_required_params() @responses.activate def test_post_document_value_error(self): """ test_post_document_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Document model document_model = {} document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' # Set up parameter values db = 'testString' document = document_model # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "document": document, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_document(**req_copy) def test_post_document_value_error_with_retries(self): # Enable retries and run test_post_document_value_error. _service.enable_retries() self.test_post_document_value_error() # Disable retries and run test_post_document_value_error. _service.disable_retries() self.test_post_document_value_error() class TestPostAllDocs(): """ Test Class for post_all_docs """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_all_docs_all_params(self): """ post_all_docs() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_all_docs') mock_response = '{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 0 skip = 0 update_seq = False endkey = 'testString' key = 'testString' keys = ['testString'] startkey = 'testString' # Invoke method response = _service.post_all_docs( db, att_encoding_info=att_encoding_info, attachments=attachments, conflicts=conflicts, descending=descending, include_docs=include_docs, inclusive_end=inclusive_end, limit=limit, skip=skip, update_seq=update_seq, endkey=endkey, key=key, keys=keys, startkey=startkey, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['att_encoding_info'] == False assert req_body['attachments'] == False assert req_body['conflicts'] == False assert req_body['descending'] == False assert req_body['include_docs'] == False assert req_body['inclusive_end'] == True assert req_body['limit'] == 0 assert req_body['skip'] == 0 assert req_body['update_seq'] == False assert req_body['endkey'] == 'testString' assert req_body['key'] == 'testString' assert req_body['keys'] == ['testString'] assert req_body['startkey'] == 'testString' def test_post_all_docs_all_params_with_retries(self): # Enable retries and run test_post_all_docs_all_params. _service.enable_retries() self.test_post_all_docs_all_params() # Disable retries and run test_post_all_docs_all_params. _service.disable_retries() self.test_post_all_docs_all_params() @responses.activate def test_post_all_docs_value_error(self): """ test_post_all_docs_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_all_docs') mock_response = '{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 0 skip = 0 update_seq = False endkey = 'testString' key = 'testString' keys = ['testString'] startkey = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_all_docs(**req_copy) def test_post_all_docs_value_error_with_retries(self): # Enable retries and run test_post_all_docs_value_error. _service.enable_retries() self.test_post_all_docs_value_error() # Disable retries and run test_post_all_docs_value_error. _service.disable_retries() self.test_post_all_docs_value_error() class TestPostAllDocsAsStream(): """ Test Class for post_all_docs_as_stream """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_all_docs_as_stream_all_params(self): """ post_all_docs_as_stream() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_all_docs') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' key = 'testString' keys = ['testString'] startkey = '0007741142412418284' # Invoke method response = _service.post_all_docs_as_stream( db, att_encoding_info=att_encoding_info, attachments=attachments, conflicts=conflicts, descending=descending, include_docs=include_docs, inclusive_end=inclusive_end, limit=limit, skip=skip, update_seq=update_seq, endkey=endkey, key=key, keys=keys, startkey=startkey, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['att_encoding_info'] == False assert req_body['attachments'] == False assert req_body['conflicts'] == False assert req_body['descending'] == False assert req_body['include_docs'] == False assert req_body['inclusive_end'] == True assert req_body['limit'] == 10 assert req_body['skip'] == 0 assert req_body['update_seq'] == False assert req_body['endkey'] == 'testString' assert req_body['key'] == 'testString' assert req_body['keys'] == ['testString'] assert req_body['startkey'] == '0007741142412418284' # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_all_docs_as_stream_all_params_with_retries(self): # Enable retries and run test_post_all_docs_as_stream_all_params. _service.enable_retries() self.test_post_all_docs_as_stream_all_params() # Disable retries and run test_post_all_docs_as_stream_all_params. _service.disable_retries() self.test_post_all_docs_as_stream_all_params() @responses.activate def test_post_all_docs_as_stream_value_error(self): """ test_post_all_docs_as_stream_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_all_docs') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' key = 'testString' keys = ['testString'] startkey = '0007741142412418284' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_all_docs_as_stream(**req_copy) def test_post_all_docs_as_stream_value_error_with_retries(self): # Enable retries and run test_post_all_docs_as_stream_value_error. _service.enable_retries() self.test_post_all_docs_as_stream_value_error() # Disable retries and run test_post_all_docs_as_stream_value_error. _service.disable_retries() self.test_post_all_docs_as_stream_value_error() class TestPostAllDocsQueries(): """ Test Class for post_all_docs_queries """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_all_docs_queries_all_params(self): """ post_all_docs_queries() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_all_docs/queries') mock_response = '{"results": [{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a AllDocsQuery model all_docs_query_model = {} all_docs_query_model['att_encoding_info'] = False all_docs_query_model['attachments'] = False all_docs_query_model['conflicts'] = False all_docs_query_model['descending'] = False all_docs_query_model['include_docs'] = False all_docs_query_model['inclusive_end'] = True all_docs_query_model['limit'] = 0 all_docs_query_model['skip'] = 0 all_docs_query_model['update_seq'] = False all_docs_query_model['endkey'] = 'testString' all_docs_query_model['key'] = 'testString' all_docs_query_model['keys'] = ['testString'] all_docs_query_model['startkey'] = 'testString' # Set up parameter values db = 'testString' queries = [all_docs_query_model] # Invoke method response = _service.post_all_docs_queries( db, queries, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['queries'] == [all_docs_query_model] def test_post_all_docs_queries_all_params_with_retries(self): # Enable retries and run test_post_all_docs_queries_all_params. _service.enable_retries() self.test_post_all_docs_queries_all_params() # Disable retries and run test_post_all_docs_queries_all_params. _service.disable_retries() self.test_post_all_docs_queries_all_params() @responses.activate def test_post_all_docs_queries_value_error(self): """ test_post_all_docs_queries_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_all_docs/queries') mock_response = '{"results": [{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a AllDocsQuery model all_docs_query_model = {} all_docs_query_model['att_encoding_info'] = False all_docs_query_model['attachments'] = False all_docs_query_model['conflicts'] = False all_docs_query_model['descending'] = False all_docs_query_model['include_docs'] = False all_docs_query_model['inclusive_end'] = True all_docs_query_model['limit'] = 0 all_docs_query_model['skip'] = 0 all_docs_query_model['update_seq'] = False all_docs_query_model['endkey'] = 'testString' all_docs_query_model['key'] = 'testString' all_docs_query_model['keys'] = ['testString'] all_docs_query_model['startkey'] = 'testString' # Set up parameter values db = 'testString' queries = [all_docs_query_model] # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "queries": queries, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_all_docs_queries(**req_copy) def test_post_all_docs_queries_value_error_with_retries(self): # Enable retries and run test_post_all_docs_queries_value_error. _service.enable_retries() self.test_post_all_docs_queries_value_error() # Disable retries and run test_post_all_docs_queries_value_error. _service.disable_retries() self.test_post_all_docs_queries_value_error() class TestPostAllDocsQueriesAsStream(): """ Test Class for post_all_docs_queries_as_stream """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_all_docs_queries_as_stream_all_params(self): """ post_all_docs_queries_as_stream() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_all_docs/queries') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a AllDocsQuery model all_docs_query_model = {} all_docs_query_model['att_encoding_info'] = False all_docs_query_model['attachments'] = False all_docs_query_model['conflicts'] = False all_docs_query_model['descending'] = False all_docs_query_model['include_docs'] = False all_docs_query_model['inclusive_end'] = True all_docs_query_model['limit'] = 0 all_docs_query_model['skip'] = 0 all_docs_query_model['update_seq'] = False all_docs_query_model['endkey'] = 'testString' all_docs_query_model['key'] = 'testString' all_docs_query_model['keys'] = ['small-appliances:1000042', 'small-appliances:1000043'] all_docs_query_model['startkey'] = 'testString' # Set up parameter values db = 'testString' queries = [all_docs_query_model] # Invoke method response = _service.post_all_docs_queries_as_stream( db, queries, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['queries'] == [all_docs_query_model] # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_all_docs_queries_as_stream_all_params_with_retries(self): # Enable retries and run test_post_all_docs_queries_as_stream_all_params. _service.enable_retries() self.test_post_all_docs_queries_as_stream_all_params() # Disable retries and run test_post_all_docs_queries_as_stream_all_params. _service.disable_retries() self.test_post_all_docs_queries_as_stream_all_params() @responses.activate def test_post_all_docs_queries_as_stream_value_error(self): """ test_post_all_docs_queries_as_stream_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_all_docs/queries') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a AllDocsQuery model all_docs_query_model = {} all_docs_query_model['att_encoding_info'] = False all_docs_query_model['attachments'] = False all_docs_query_model['conflicts'] = False all_docs_query_model['descending'] = False all_docs_query_model['include_docs'] = False all_docs_query_model['inclusive_end'] = True all_docs_query_model['limit'] = 0 all_docs_query_model['skip'] = 0 all_docs_query_model['update_seq'] = False all_docs_query_model['endkey'] = 'testString' all_docs_query_model['key'] = 'testString' all_docs_query_model['keys'] = ['small-appliances:1000042', 'small-appliances:1000043'] all_docs_query_model['startkey'] = 'testString' # Set up parameter values db = 'testString' queries = [all_docs_query_model] # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "queries": queries, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_all_docs_queries_as_stream(**req_copy) def test_post_all_docs_queries_as_stream_value_error_with_retries(self): # Enable retries and run test_post_all_docs_queries_as_stream_value_error. _service.enable_retries() self.test_post_all_docs_queries_as_stream_value_error() # Disable retries and run test_post_all_docs_queries_as_stream_value_error. _service.disable_retries() self.test_post_all_docs_queries_as_stream_value_error() class TestPostBulkDocs(): """ Test Class for post_bulk_docs """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_bulk_docs_all_params(self): """ post_bulk_docs() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_docs') mock_response = '[{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}]' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Document model document_model = {} document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' # Construct a dict representation of a BulkDocs model bulk_docs_model = {} bulk_docs_model['docs'] = [document_model] bulk_docs_model['new_edits'] = True # Set up parameter values db = 'testString' bulk_docs = bulk_docs_model # Invoke method response = _service.post_bulk_docs( db, bulk_docs, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body == bulk_docs def test_post_bulk_docs_all_params_with_retries(self): # Enable retries and run test_post_bulk_docs_all_params. _service.enable_retries() self.test_post_bulk_docs_all_params() # Disable retries and run test_post_bulk_docs_all_params. _service.disable_retries() self.test_post_bulk_docs_all_params() @responses.activate def test_post_bulk_docs_value_error(self): """ test_post_bulk_docs_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_docs') mock_response = '[{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}]' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Document model document_model = {} document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' # Construct a dict representation of a BulkDocs model bulk_docs_model = {} bulk_docs_model['docs'] = [document_model] bulk_docs_model['new_edits'] = True # Set up parameter values db = 'testString' bulk_docs = bulk_docs_model # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "bulk_docs": bulk_docs, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_bulk_docs(**req_copy) def test_post_bulk_docs_value_error_with_retries(self): # Enable retries and run test_post_bulk_docs_value_error. _service.enable_retries() self.test_post_bulk_docs_value_error() # Disable retries and run test_post_bulk_docs_value_error. _service.disable_retries() self.test_post_bulk_docs_value_error() class TestPostBulkGet(): """ Test Class for post_bulk_get """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_bulk_get_all_params(self): """ post_bulk_get() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = '{"results": [{"docs": [{"error": {"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}, "ok": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}}], "id": "id"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a BulkGetQueryDocument model bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'testString' bulk_get_query_document_model['rev'] = 'testString' # Set up parameter values db = 'testString' docs = [bulk_get_query_document_model] attachments = False att_encoding_info = False latest = False revs = False # Invoke method response = _service.post_bulk_get( db, docs, attachments=attachments, att_encoding_info=att_encoding_info, latest=latest, revs=revs, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'revs={}'.format('true' if revs else 'false') in query_string # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['docs'] == [bulk_get_query_document_model] def test_post_bulk_get_all_params_with_retries(self): # Enable retries and run test_post_bulk_get_all_params. _service.enable_retries() self.test_post_bulk_get_all_params() # Disable retries and run test_post_bulk_get_all_params. _service.disable_retries() self.test_post_bulk_get_all_params() @responses.activate def test_post_bulk_get_required_params(self): """ test_post_bulk_get_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = '{"results": [{"docs": [{"error": {"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}, "ok": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}}], "id": "id"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a BulkGetQueryDocument model bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'testString' bulk_get_query_document_model['rev'] = 'testString' # Set up parameter values db = 'testString' docs = [bulk_get_query_document_model] # Invoke method response = _service.post_bulk_get( db, docs, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['docs'] == [bulk_get_query_document_model] def test_post_bulk_get_required_params_with_retries(self): # Enable retries and run test_post_bulk_get_required_params. _service.enable_retries() self.test_post_bulk_get_required_params() # Disable retries and run test_post_bulk_get_required_params. _service.disable_retries() self.test_post_bulk_get_required_params() @responses.activate def test_post_bulk_get_value_error(self): """ test_post_bulk_get_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = '{"results": [{"docs": [{"error": {"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}, "ok": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}}], "id": "id"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a BulkGetQueryDocument model bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'testString' bulk_get_query_document_model['rev'] = 'testString' # Set up parameter values db = 'testString' docs = [bulk_get_query_document_model] # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "docs": docs, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_bulk_get(**req_copy) def test_post_bulk_get_value_error_with_retries(self): # Enable retries and run test_post_bulk_get_value_error. _service.enable_retries() self.test_post_bulk_get_value_error() # Disable retries and run test_post_bulk_get_value_error. _service.disable_retries() self.test_post_bulk_get_value_error() class TestPostBulkGetAsMixed(): """ Test Class for post_bulk_get_as_mixed """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_bulk_get_as_mixed_all_params(self): """ post_bulk_get_as_mixed() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = 'This is a mock binary response.' responses.add(responses.POST, url, body=mock_response, content_type='multipart/mixed', status=200) # Construct a dict representation of a BulkGetQueryDocument model bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'order00067' bulk_get_query_document_model['rev'] = '3-917fa2381192822767f010b95b45325b' # Set up parameter values db = 'testString' docs = [bulk_get_query_document_model] attachments = False att_encoding_info = False latest = False revs = False # Invoke method response = _service.post_bulk_get_as_mixed( db, docs, attachments=attachments, att_encoding_info=att_encoding_info, latest=latest, revs=revs, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'revs={}'.format('true' if revs else 'false') in query_string # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['docs'] == [bulk_get_query_document_model] def test_post_bulk_get_as_mixed_all_params_with_retries(self): # Enable retries and run test_post_bulk_get_as_mixed_all_params. _service.enable_retries() self.test_post_bulk_get_as_mixed_all_params() # Disable retries and run test_post_bulk_get_as_mixed_all_params. _service.disable_retries() self.test_post_bulk_get_as_mixed_all_params() @responses.activate def test_post_bulk_get_as_mixed_required_params(self): """ test_post_bulk_get_as_mixed_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = 'This is a mock binary response.' responses.add(responses.POST, url, body=mock_response, content_type='multipart/mixed', status=200) # Construct a dict representation of a BulkGetQueryDocument model bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'order00067' bulk_get_query_document_model['rev'] = '3-917fa2381192822767f010b95b45325b' # Set up parameter values db = 'testString' docs = [bulk_get_query_document_model] # Invoke method response = _service.post_bulk_get_as_mixed( db, docs, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['docs'] == [bulk_get_query_document_model] def test_post_bulk_get_as_mixed_required_params_with_retries(self): # Enable retries and run test_post_bulk_get_as_mixed_required_params. _service.enable_retries() self.test_post_bulk_get_as_mixed_required_params() # Disable retries and run test_post_bulk_get_as_mixed_required_params. _service.disable_retries() self.test_post_bulk_get_as_mixed_required_params() @responses.activate def test_post_bulk_get_as_mixed_value_error(self): """ test_post_bulk_get_as_mixed_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = 'This is a mock binary response.' responses.add(responses.POST, url, body=mock_response, content_type='multipart/mixed', status=200) # Construct a dict representation of a BulkGetQueryDocument model bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'order00067' bulk_get_query_document_model['rev'] = '3-917fa2381192822767f010b95b45325b' # Set up parameter values db = 'testString' docs = [bulk_get_query_document_model] # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "docs": docs, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_bulk_get_as_mixed(**req_copy) def test_post_bulk_get_as_mixed_value_error_with_retries(self): # Enable retries and run test_post_bulk_get_as_mixed_value_error. _service.enable_retries() self.test_post_bulk_get_as_mixed_value_error() # Disable retries and run test_post_bulk_get_as_mixed_value_error. _service.disable_retries() self.test_post_bulk_get_as_mixed_value_error() class TestPostBulkGetAsRelated(): """ Test Class for post_bulk_get_as_related """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_bulk_get_as_related_all_params(self): """ post_bulk_get_as_related() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = 'This is a mock binary response.' responses.add(responses.POST, url, body=mock_response, content_type='multipart/related', status=200) # Construct a dict representation of a BulkGetQueryDocument model bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'order00067' bulk_get_query_document_model['rev'] = '3-917fa2381192822767f010b95b45325b' # Set up parameter values db = 'testString' docs = [bulk_get_query_document_model] attachments = False att_encoding_info = False latest = False revs = False # Invoke method response = _service.post_bulk_get_as_related( db, docs, attachments=attachments, att_encoding_info=att_encoding_info, latest=latest, revs=revs, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'revs={}'.format('true' if revs else 'false') in query_string # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['docs'] == [bulk_get_query_document_model] def test_post_bulk_get_as_related_all_params_with_retries(self): # Enable retries and run test_post_bulk_get_as_related_all_params. _service.enable_retries() self.test_post_bulk_get_as_related_all_params() # Disable retries and run test_post_bulk_get_as_related_all_params. _service.disable_retries() self.test_post_bulk_get_as_related_all_params() @responses.activate def test_post_bulk_get_as_related_required_params(self): """ test_post_bulk_get_as_related_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = 'This is a mock binary response.' responses.add(responses.POST, url, body=mock_response, content_type='multipart/related', status=200) # Construct a dict representation of a BulkGetQueryDocument model bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'order00067' bulk_get_query_document_model['rev'] = '3-917fa2381192822767f010b95b45325b' # Set up parameter values db = 'testString' docs = [bulk_get_query_document_model] # Invoke method response = _service.post_bulk_get_as_related( db, docs, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['docs'] == [bulk_get_query_document_model] def test_post_bulk_get_as_related_required_params_with_retries(self): # Enable retries and run test_post_bulk_get_as_related_required_params. _service.enable_retries() self.test_post_bulk_get_as_related_required_params() # Disable retries and run test_post_bulk_get_as_related_required_params. _service.disable_retries() self.test_post_bulk_get_as_related_required_params() @responses.activate def test_post_bulk_get_as_related_value_error(self): """ test_post_bulk_get_as_related_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = 'This is a mock binary response.' responses.add(responses.POST, url, body=mock_response, content_type='multipart/related', status=200) # Construct a dict representation of a BulkGetQueryDocument model bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'order00067' bulk_get_query_document_model['rev'] = '3-917fa2381192822767f010b95b45325b' # Set up parameter values db = 'testString' docs = [bulk_get_query_document_model] # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "docs": docs, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_bulk_get_as_related(**req_copy) def test_post_bulk_get_as_related_value_error_with_retries(self): # Enable retries and run test_post_bulk_get_as_related_value_error. _service.enable_retries() self.test_post_bulk_get_as_related_value_error() # Disable retries and run test_post_bulk_get_as_related_value_error. _service.disable_retries() self.test_post_bulk_get_as_related_value_error() class TestPostBulkGetAsStream(): """ Test Class for post_bulk_get_as_stream """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_bulk_get_as_stream_all_params(self): """ post_bulk_get_as_stream() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a BulkGetQueryDocument model bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'order00067' bulk_get_query_document_model['rev'] = '3-917fa2381192822767f010b95b45325b' # Set up parameter values db = 'testString' docs = [bulk_get_query_document_model] attachments = False att_encoding_info = False latest = False revs = False # Invoke method response = _service.post_bulk_get_as_stream( db, docs, attachments=attachments, att_encoding_info=att_encoding_info, latest=latest, revs=revs, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'revs={}'.format('true' if revs else 'false') in query_string # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['docs'] == [bulk_get_query_document_model] # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_bulk_get_as_stream_all_params_with_retries(self): # Enable retries and run test_post_bulk_get_as_stream_all_params. _service.enable_retries() self.test_post_bulk_get_as_stream_all_params() # Disable retries and run test_post_bulk_get_as_stream_all_params. _service.disable_retries() self.test_post_bulk_get_as_stream_all_params() @responses.activate def test_post_bulk_get_as_stream_required_params(self): """ test_post_bulk_get_as_stream_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a BulkGetQueryDocument model bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'order00067' bulk_get_query_document_model['rev'] = '3-917fa2381192822767f010b95b45325b' # Set up parameter values db = 'testString' docs = [bulk_get_query_document_model] # Invoke method response = _service.post_bulk_get_as_stream( db, docs, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['docs'] == [bulk_get_query_document_model] # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_bulk_get_as_stream_required_params_with_retries(self): # Enable retries and run test_post_bulk_get_as_stream_required_params. _service.enable_retries() self.test_post_bulk_get_as_stream_required_params() # Disable retries and run test_post_bulk_get_as_stream_required_params. _service.disable_retries() self.test_post_bulk_get_as_stream_required_params() @responses.activate def test_post_bulk_get_as_stream_value_error(self): """ test_post_bulk_get_as_stream_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a BulkGetQueryDocument model bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'order00067' bulk_get_query_document_model['rev'] = '3-917fa2381192822767f010b95b45325b' # Set up parameter values db = 'testString' docs = [bulk_get_query_document_model] # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "docs": docs, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_bulk_get_as_stream(**req_copy) def test_post_bulk_get_as_stream_value_error_with_retries(self): # Enable retries and run test_post_bulk_get_as_stream_value_error. _service.enable_retries() self.test_post_bulk_get_as_stream_value_error() # Disable retries and run test_post_bulk_get_as_stream_value_error. _service.disable_retries() self.test_post_bulk_get_as_stream_value_error() class TestDeleteDocument(): """ Test Class for delete_document """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_delete_document_all_params(self): """ delete_document() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' if_match = 'testString' batch = 'ok' rev = 'testString' # Invoke method response = _service.delete_document( db, doc_id, if_match=if_match, batch=batch, rev=rev, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'batch={}'.format(batch) in query_string assert 'rev={}'.format(rev) in query_string def test_delete_document_all_params_with_retries(self): # Enable retries and run test_delete_document_all_params. _service.enable_retries() self.test_delete_document_all_params() # Disable retries and run test_delete_document_all_params. _service.disable_retries() self.test_delete_document_all_params() @responses.activate def test_delete_document_required_params(self): """ test_delete_document_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Invoke method response = _service.delete_document( db, doc_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_delete_document_required_params_with_retries(self): # Enable retries and run test_delete_document_required_params. _service.enable_retries() self.test_delete_document_required_params() # Disable retries and run test_delete_document_required_params. _service.disable_retries() self.test_delete_document_required_params() @responses.activate def test_delete_document_value_error(self): """ test_delete_document_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_document(**req_copy) def test_delete_document_value_error_with_retries(self): # Enable retries and run test_delete_document_value_error. _service.enable_retries() self.test_delete_document_value_error() # Disable retries and run test_delete_document_value_error. _service.disable_retries() self.test_delete_document_value_error() class TestGetDocument(): """ Test Class for get_document """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_document_all_params(self): """ get_document() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' if_none_match = 'testString' attachments = False att_encoding_info = False conflicts = False deleted_conflicts = False latest = False local_seq = False meta = False rev = 'testString' revs = False revs_info = False # Invoke method response = _service.get_document( db, doc_id, if_none_match=if_none_match, attachments=attachments, att_encoding_info=att_encoding_info, conflicts=conflicts, deleted_conflicts=deleted_conflicts, latest=latest, local_seq=local_seq, meta=meta, rev=rev, revs=revs, revs_info=revs_info, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'conflicts={}'.format('true' if conflicts else 'false') in query_string assert 'deleted_conflicts={}'.format('true' if deleted_conflicts else 'false') in query_string assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'local_seq={}'.format('true' if local_seq else 'false') in query_string assert 'meta={}'.format('true' if meta else 'false') in query_string assert 'rev={}'.format(rev) in query_string assert 'revs={}'.format('true' if revs else 'false') in query_string assert 'revs_info={}'.format('true' if revs_info else 'false') in query_string def test_get_document_all_params_with_retries(self): # Enable retries and run test_get_document_all_params. _service.enable_retries() self.test_get_document_all_params() # Disable retries and run test_get_document_all_params. _service.disable_retries() self.test_get_document_all_params() @responses.activate def test_get_document_required_params(self): """ test_get_document_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Invoke method response = _service.get_document( db, doc_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_document_required_params_with_retries(self): # Enable retries and run test_get_document_required_params. _service.enable_retries() self.test_get_document_required_params() # Disable retries and run test_get_document_required_params. _service.disable_retries() self.test_get_document_required_params() @responses.activate def test_get_document_value_error(self): """ test_get_document_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_document(**req_copy) def test_get_document_value_error_with_retries(self): # Enable retries and run test_get_document_value_error. _service.enable_retries() self.test_get_document_value_error() # Disable retries and run test_get_document_value_error. _service.disable_retries() self.test_get_document_value_error() class TestGetDocumentAsMixed(): """ Test Class for get_document_as_mixed """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_document_as_mixed_all_params(self): """ get_document_as_mixed() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, body=mock_response, content_type='multipart/mixed', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' if_none_match = 'testString' attachments = False att_encoding_info = False conflicts = False deleted_conflicts = False latest = False local_seq = False meta = False rev = 'testString' revs = False revs_info = False # Invoke method response = _service.get_document_as_mixed( db, doc_id, if_none_match=if_none_match, attachments=attachments, att_encoding_info=att_encoding_info, conflicts=conflicts, deleted_conflicts=deleted_conflicts, latest=latest, local_seq=local_seq, meta=meta, rev=rev, revs=revs, revs_info=revs_info, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'conflicts={}'.format('true' if conflicts else 'false') in query_string assert 'deleted_conflicts={}'.format('true' if deleted_conflicts else 'false') in query_string assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'local_seq={}'.format('true' if local_seq else 'false') in query_string assert 'meta={}'.format('true' if meta else 'false') in query_string assert 'rev={}'.format(rev) in query_string assert 'revs={}'.format('true' if revs else 'false') in query_string assert 'revs_info={}'.format('true' if revs_info else 'false') in query_string def test_get_document_as_mixed_all_params_with_retries(self): # Enable retries and run test_get_document_as_mixed_all_params. _service.enable_retries() self.test_get_document_as_mixed_all_params() # Disable retries and run test_get_document_as_mixed_all_params. _service.disable_retries() self.test_get_document_as_mixed_all_params() @responses.activate def test_get_document_as_mixed_required_params(self): """ test_get_document_as_mixed_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, body=mock_response, content_type='multipart/mixed', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Invoke method response = _service.get_document_as_mixed( db, doc_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_document_as_mixed_required_params_with_retries(self): # Enable retries and run test_get_document_as_mixed_required_params. _service.enable_retries() self.test_get_document_as_mixed_required_params() # Disable retries and run test_get_document_as_mixed_required_params. _service.disable_retries() self.test_get_document_as_mixed_required_params() @responses.activate def test_get_document_as_mixed_value_error(self): """ test_get_document_as_mixed_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, body=mock_response, content_type='multipart/mixed', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_document_as_mixed(**req_copy) def test_get_document_as_mixed_value_error_with_retries(self): # Enable retries and run test_get_document_as_mixed_value_error. _service.enable_retries() self.test_get_document_as_mixed_value_error() # Disable retries and run test_get_document_as_mixed_value_error. _service.disable_retries() self.test_get_document_as_mixed_value_error() class TestGetDocumentAsRelated(): """ Test Class for get_document_as_related """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_document_as_related_all_params(self): """ get_document_as_related() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, body=mock_response, content_type='multipart/related', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' if_none_match = 'testString' attachments = False att_encoding_info = False conflicts = False deleted_conflicts = False latest = False local_seq = False meta = False rev = 'testString' revs = False revs_info = False # Invoke method response = _service.get_document_as_related( db, doc_id, if_none_match=if_none_match, attachments=attachments, att_encoding_info=att_encoding_info, conflicts=conflicts, deleted_conflicts=deleted_conflicts, latest=latest, local_seq=local_seq, meta=meta, rev=rev, revs=revs, revs_info=revs_info, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'conflicts={}'.format('true' if conflicts else 'false') in query_string assert 'deleted_conflicts={}'.format('true' if deleted_conflicts else 'false') in query_string assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'local_seq={}'.format('true' if local_seq else 'false') in query_string assert 'meta={}'.format('true' if meta else 'false') in query_string assert 'rev={}'.format(rev) in query_string assert 'revs={}'.format('true' if revs else 'false') in query_string assert 'revs_info={}'.format('true' if revs_info else 'false') in query_string def test_get_document_as_related_all_params_with_retries(self): # Enable retries and run test_get_document_as_related_all_params. _service.enable_retries() self.test_get_document_as_related_all_params() # Disable retries and run test_get_document_as_related_all_params. _service.disable_retries() self.test_get_document_as_related_all_params() @responses.activate def test_get_document_as_related_required_params(self): """ test_get_document_as_related_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, body=mock_response, content_type='multipart/related', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Invoke method response = _service.get_document_as_related( db, doc_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_document_as_related_required_params_with_retries(self): # Enable retries and run test_get_document_as_related_required_params. _service.enable_retries() self.test_get_document_as_related_required_params() # Disable retries and run test_get_document_as_related_required_params. _service.disable_retries() self.test_get_document_as_related_required_params() @responses.activate def test_get_document_as_related_value_error(self): """ test_get_document_as_related_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, body=mock_response, content_type='multipart/related', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_document_as_related(**req_copy) def test_get_document_as_related_value_error_with_retries(self): # Enable retries and run test_get_document_as_related_value_error. _service.enable_retries() self.test_get_document_as_related_value_error() # Disable retries and run test_get_document_as_related_value_error. _service.disable_retries() self.test_get_document_as_related_value_error() class TestGetDocumentAsStream(): """ Test Class for get_document_as_stream """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_document_as_stream_all_params(self): """ get_document_as_stream() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' if_none_match = 'testString' attachments = False att_encoding_info = False conflicts = False deleted_conflicts = False latest = False local_seq = False meta = False rev = 'testString' revs = False revs_info = False # Invoke method response = _service.get_document_as_stream( db, doc_id, if_none_match=if_none_match, attachments=attachments, att_encoding_info=att_encoding_info, conflicts=conflicts, deleted_conflicts=deleted_conflicts, latest=latest, local_seq=local_seq, meta=meta, rev=rev, revs=revs, revs_info=revs_info, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'conflicts={}'.format('true' if conflicts else 'false') in query_string assert 'deleted_conflicts={}'.format('true' if deleted_conflicts else 'false') in query_string assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'local_seq={}'.format('true' if local_seq else 'false') in query_string assert 'meta={}'.format('true' if meta else 'false') in query_string assert 'rev={}'.format(rev) in query_string assert 'revs={}'.format('true' if revs else 'false') in query_string assert 'revs_info={}'.format('true' if revs_info else 'false') in query_string # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_get_document_as_stream_all_params_with_retries(self): # Enable retries and run test_get_document_as_stream_all_params. _service.enable_retries() self.test_get_document_as_stream_all_params() # Disable retries and run test_get_document_as_stream_all_params. _service.disable_retries() self.test_get_document_as_stream_all_params() @responses.activate def test_get_document_as_stream_required_params(self): """ test_get_document_as_stream_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Invoke method response = _service.get_document_as_stream( db, doc_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_get_document_as_stream_required_params_with_retries(self): # Enable retries and run test_get_document_as_stream_required_params. _service.enable_retries() self.test_get_document_as_stream_required_params() # Disable retries and run test_get_document_as_stream_required_params. _service.disable_retries() self.test_get_document_as_stream_required_params() @responses.activate def test_get_document_as_stream_value_error(self): """ test_get_document_as_stream_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_document_as_stream(**req_copy) def test_get_document_as_stream_value_error_with_retries(self): # Enable retries and run test_get_document_as_stream_value_error. _service.enable_retries() self.test_get_document_as_stream_value_error() # Disable retries and run test_get_document_as_stream_value_error. _service.disable_retries() self.test_get_document_as_stream_value_error() class TestPutDocument(): """ Test Class for put_document """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_put_document_all_params(self): """ put_document() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Document model document_model = {} document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'exampleid' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['brand'] = 'Foo' document_model['colours'] = '["red","green","black","blue"]' document_model['description'] = 'Slim Colourful Design Electronic Cooking Appliance for ...' document_model['image'] = 'assets/img/0gmsnghhew.jpg' document_model['keywords'] = '["Foo","Scales","Weight","Digital","Kitchen"]' document_model['name'] = 'Digital Kitchen Scales' document_model['price'] = '14.99' document_model['productid'] = '1000042' document_model['taxonomy'] = '["Home","Kitchen","Small Appliances"]' document_model['type'] = 'product' # Set up parameter values db = 'testString' doc_id = 'testString' document = document_model content_type = 'application/json' if_match = 'testString' batch = 'ok' new_edits = False rev = 'testString' # Invoke method response = _service.put_document( db, doc_id, document, content_type=content_type, if_match=if_match, batch=batch, new_edits=new_edits, rev=rev, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'batch={}'.format(batch) in query_string assert 'new_edits={}'.format('true' if new_edits else 'false') in query_string assert 'rev={}'.format(rev) in query_string # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params def test_put_document_all_params_with_retries(self): # Enable retries and run test_put_document_all_params. _service.enable_retries() self.test_put_document_all_params() # Disable retries and run test_put_document_all_params. _service.disable_retries() self.test_put_document_all_params() @responses.activate def test_put_document_required_params(self): """ test_put_document_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Document model document_model = {} document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'exampleid' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['brand'] = 'Foo' document_model['colours'] = '["red","green","black","blue"]' document_model['description'] = 'Slim Colourful Design Electronic Cooking Appliance for ...' document_model['image'] = 'assets/img/0gmsnghhew.jpg' document_model['keywords'] = '["Foo","Scales","Weight","Digital","Kitchen"]' document_model['name'] = 'Digital Kitchen Scales' document_model['price'] = '14.99' document_model['productid'] = '1000042' document_model['taxonomy'] = '["Home","Kitchen","Small Appliances"]' document_model['type'] = 'product' # Set up parameter values db = 'testString' doc_id = 'testString' document = document_model # Invoke method response = _service.put_document( db, doc_id, document, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params def test_put_document_required_params_with_retries(self): # Enable retries and run test_put_document_required_params. _service.enable_retries() self.test_put_document_required_params() # Disable retries and run test_put_document_required_params. _service.disable_retries() self.test_put_document_required_params() @responses.activate def test_put_document_value_error(self): """ test_put_document_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Document model document_model = {} document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'exampleid' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['brand'] = 'Foo' document_model['colours'] = '["red","green","black","blue"]' document_model['description'] = 'Slim Colourful Design Electronic Cooking Appliance for ...' document_model['image'] = 'assets/img/0gmsnghhew.jpg' document_model['keywords'] = '["Foo","Scales","Weight","Digital","Kitchen"]' document_model['name'] = 'Digital Kitchen Scales' document_model['price'] = '14.99' document_model['productid'] = '1000042' document_model['taxonomy'] = '["Home","Kitchen","Small Appliances"]' document_model['type'] = 'product' # Set up parameter values db = 'testString' doc_id = 'testString' document = document_model # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "doc_id": doc_id, "document": document, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.put_document(**req_copy) def test_put_document_value_error_with_retries(self): # Enable retries and run test_put_document_value_error. _service.enable_retries() self.test_put_document_value_error() # Disable retries and run test_put_document_value_error. _service.disable_retries() self.test_put_document_value_error() # endregion ############################################################################## # End of Service: Documents ############################################################################## ############################################################################## # Start of Service: DesignDocuments ############################################################################## # region class TestNewInstance(): """ Test Class for new_instance """ def test_new_instance(self): """ new_instance() """ os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): """ new_instance_without_authenticator() """ with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestHeadDesignDocument(): """ Test Class for head_design_document """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_head_design_document_all_params(self): """ head_design_document() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values db = 'testString' ddoc = 'testString' if_none_match = 'testString' # Invoke method response = _service.head_design_document( db, ddoc, if_none_match=if_none_match, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_head_design_document_all_params_with_retries(self): # Enable retries and run test_head_design_document_all_params. _service.enable_retries() self.test_head_design_document_all_params() # Disable retries and run test_head_design_document_all_params. _service.disable_retries() self.test_head_design_document_all_params() @responses.activate def test_head_design_document_required_params(self): """ test_head_design_document_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values db = 'testString' ddoc = 'testString' # Invoke method response = _service.head_design_document( db, ddoc, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_head_design_document_required_params_with_retries(self): # Enable retries and run test_head_design_document_required_params. _service.enable_retries() self.test_head_design_document_required_params() # Disable retries and run test_head_design_document_required_params. _service.disable_retries() self.test_head_design_document_required_params() @responses.activate def test_head_design_document_value_error(self): """ test_head_design_document_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values db = 'testString' ddoc = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.head_design_document(**req_copy) def test_head_design_document_value_error_with_retries(self): # Enable retries and run test_head_design_document_value_error. _service.enable_retries() self.test_head_design_document_value_error() # Disable retries and run test_head_design_document_value_error. _service.disable_retries() self.test_head_design_document_value_error() class TestDeleteDesignDocument(): """ Test Class for delete_design_document """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_delete_design_document_all_params(self): """ delete_design_document() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' if_match = 'testString' batch = 'ok' rev = 'testString' # Invoke method response = _service.delete_design_document( db, ddoc, if_match=if_match, batch=batch, rev=rev, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'batch={}'.format(batch) in query_string assert 'rev={}'.format(rev) in query_string def test_delete_design_document_all_params_with_retries(self): # Enable retries and run test_delete_design_document_all_params. _service.enable_retries() self.test_delete_design_document_all_params() # Disable retries and run test_delete_design_document_all_params. _service.disable_retries() self.test_delete_design_document_all_params() @responses.activate def test_delete_design_document_required_params(self): """ test_delete_design_document_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' # Invoke method response = _service.delete_design_document( db, ddoc, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_delete_design_document_required_params_with_retries(self): # Enable retries and run test_delete_design_document_required_params. _service.enable_retries() self.test_delete_design_document_required_params() # Disable retries and run test_delete_design_document_required_params. _service.disable_retries() self.test_delete_design_document_required_params() @responses.activate def test_delete_design_document_value_error(self): """ test_delete_design_document_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_design_document(**req_copy) def test_delete_design_document_value_error_with_retries(self): # Enable retries and run test_delete_design_document_value_error. _service.enable_retries() self.test_delete_design_document_value_error() # Disable retries and run test_delete_design_document_value_error. _service.disable_retries() self.test_delete_design_document_value_error() class TestGetDesignDocument(): """ Test Class for get_design_document """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_design_document_all_params(self): """ get_design_document() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}], "autoupdate": true, "filters": {"mapKey": "inner"}, "indexes": {"mapKey": {"analyzer": {"name": "classic", "stopwords": ["stopwords"], "fields": {"mapKey": {"name": "classic", "stopwords": ["stopwords"]}}}, "index": "index"}}, "language": "javascript", "options": {"partitioned": false}, "validate_doc_update": "validate_doc_update", "views": {"mapKey": {"map": "map", "reduce": "reduce"}}, "st_indexes": {"mapKey": {"index": "index"}}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' if_none_match = 'testString' attachments = False att_encoding_info = False conflicts = False deleted_conflicts = False latest = False local_seq = False meta = False rev = 'testString' revs = False revs_info = False # Invoke method response = _service.get_design_document( db, ddoc, if_none_match=if_none_match, attachments=attachments, att_encoding_info=att_encoding_info, conflicts=conflicts, deleted_conflicts=deleted_conflicts, latest=latest, local_seq=local_seq, meta=meta, rev=rev, revs=revs, revs_info=revs_info, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'conflicts={}'.format('true' if conflicts else 'false') in query_string assert 'deleted_conflicts={}'.format('true' if deleted_conflicts else 'false') in query_string assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'local_seq={}'.format('true' if local_seq else 'false') in query_string assert 'meta={}'.format('true' if meta else 'false') in query_string assert 'rev={}'.format(rev) in query_string assert 'revs={}'.format('true' if revs else 'false') in query_string assert 'revs_info={}'.format('true' if revs_info else 'false') in query_string def test_get_design_document_all_params_with_retries(self): # Enable retries and run test_get_design_document_all_params. _service.enable_retries() self.test_get_design_document_all_params() # Disable retries and run test_get_design_document_all_params. _service.disable_retries() self.test_get_design_document_all_params() @responses.activate def test_get_design_document_required_params(self): """ test_get_design_document_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}], "autoupdate": true, "filters": {"mapKey": "inner"}, "indexes": {"mapKey": {"analyzer": {"name": "classic", "stopwords": ["stopwords"], "fields": {"mapKey": {"name": "classic", "stopwords": ["stopwords"]}}}, "index": "index"}}, "language": "javascript", "options": {"partitioned": false}, "validate_doc_update": "validate_doc_update", "views": {"mapKey": {"map": "map", "reduce": "reduce"}}, "st_indexes": {"mapKey": {"index": "index"}}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' # Invoke method response = _service.get_design_document( db, ddoc, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_design_document_required_params_with_retries(self): # Enable retries and run test_get_design_document_required_params. _service.enable_retries() self.test_get_design_document_required_params() # Disable retries and run test_get_design_document_required_params. _service.disable_retries() self.test_get_design_document_required_params() @responses.activate def test_get_design_document_value_error(self): """ test_get_design_document_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}], "autoupdate": true, "filters": {"mapKey": "inner"}, "indexes": {"mapKey": {"analyzer": {"name": "classic", "stopwords": ["stopwords"], "fields": {"mapKey": {"name": "classic", "stopwords": ["stopwords"]}}}, "index": "index"}}, "language": "javascript", "options": {"partitioned": false}, "validate_doc_update": "validate_doc_update", "views": {"mapKey": {"map": "map", "reduce": "reduce"}}, "st_indexes": {"mapKey": {"index": "index"}}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_design_document(**req_copy) def test_get_design_document_value_error_with_retries(self): # Enable retries and run test_get_design_document_value_error. _service.enable_retries() self.test_get_design_document_value_error() # Disable retries and run test_get_design_document_value_error. _service.disable_retries() self.test_get_design_document_value_error() class TestPutDesignDocument(): """ Test Class for put_design_document """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_put_design_document_all_params(self): """ put_design_document() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Analyzer model analyzer_model = {} analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] # Construct a dict representation of a AnalyzerConfiguration model analyzer_configuration_model = {} analyzer_configuration_model['name'] = 'classic' analyzer_configuration_model['stopwords'] = ['testString'] analyzer_configuration_model['fields'] = {} # Construct a dict representation of a SearchIndexDefinition model search_index_definition_model = {} search_index_definition_model['analyzer'] = analyzer_configuration_model search_index_definition_model['index'] = 'testString' # Construct a dict representation of a DesignDocumentOptions model design_document_options_model = {} design_document_options_model['partitioned'] = True # Construct a dict representation of a DesignDocumentViewsMapReduce model design_document_views_map_reduce_model = {} design_document_views_map_reduce_model['map'] = 'testString' design_document_views_map_reduce_model['reduce'] = 'testString' # Construct a dict representation of a GeoIndexDefinition model geo_index_definition_model = {} geo_index_definition_model['index'] = 'testString' # Construct a dict representation of a DesignDocument model design_document_model = {} design_document_model['_attachments'] = {} design_document_model['_conflicts'] = ['testString'] design_document_model['_deleted'] = True design_document_model['_deleted_conflicts'] = ['testString'] design_document_model['_id'] = 'testString' design_document_model['_local_seq'] = 'testString' design_document_model['_rev'] = 'testString' design_document_model['_revisions'] = revisions_model design_document_model['_revs_info'] = [document_revision_status_model] design_document_model['autoupdate'] = True design_document_model['filters'] = {} design_document_model['indexes'] = {} design_document_model['language'] = 'javascript' design_document_model['options'] = design_document_options_model design_document_model['validate_doc_update'] = 'testString' design_document_model['views'] = {} design_document_model['st_indexes'] = {} design_document_model['foo'] = 'testString' # Set up parameter values db = 'testString' ddoc = 'testString' design_document = design_document_model if_match = 'testString' batch = 'ok' new_edits = False rev = 'testString' # Invoke method response = _service.put_design_document( db, ddoc, design_document, if_match=if_match, batch=batch, new_edits=new_edits, rev=rev, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'batch={}'.format(batch) in query_string assert 'new_edits={}'.format('true' if new_edits else 'false') in query_string assert 'rev={}'.format(rev) in query_string # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body == design_document def test_put_design_document_all_params_with_retries(self): # Enable retries and run test_put_design_document_all_params. _service.enable_retries() self.test_put_design_document_all_params() # Disable retries and run test_put_design_document_all_params. _service.disable_retries() self.test_put_design_document_all_params() @responses.activate def test_put_design_document_required_params(self): """ test_put_design_document_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Analyzer model analyzer_model = {} analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] # Construct a dict representation of a AnalyzerConfiguration model analyzer_configuration_model = {} analyzer_configuration_model['name'] = 'classic' analyzer_configuration_model['stopwords'] = ['testString'] analyzer_configuration_model['fields'] = {} # Construct a dict representation of a SearchIndexDefinition model search_index_definition_model = {} search_index_definition_model['analyzer'] = analyzer_configuration_model search_index_definition_model['index'] = 'testString' # Construct a dict representation of a DesignDocumentOptions model design_document_options_model = {} design_document_options_model['partitioned'] = True # Construct a dict representation of a DesignDocumentViewsMapReduce model design_document_views_map_reduce_model = {} design_document_views_map_reduce_model['map'] = 'testString' design_document_views_map_reduce_model['reduce'] = 'testString' # Construct a dict representation of a GeoIndexDefinition model geo_index_definition_model = {} geo_index_definition_model['index'] = 'testString' # Construct a dict representation of a DesignDocument model design_document_model = {} design_document_model['_attachments'] = {} design_document_model['_conflicts'] = ['testString'] design_document_model['_deleted'] = True design_document_model['_deleted_conflicts'] = ['testString'] design_document_model['_id'] = 'testString' design_document_model['_local_seq'] = 'testString' design_document_model['_rev'] = 'testString' design_document_model['_revisions'] = revisions_model design_document_model['_revs_info'] = [document_revision_status_model] design_document_model['autoupdate'] = True design_document_model['filters'] = {} design_document_model['indexes'] = {} design_document_model['language'] = 'javascript' design_document_model['options'] = design_document_options_model design_document_model['validate_doc_update'] = 'testString' design_document_model['views'] = {} design_document_model['st_indexes'] = {} design_document_model['foo'] = 'testString' # Set up parameter values db = 'testString' ddoc = 'testString' design_document = design_document_model # Invoke method response = _service.put_design_document( db, ddoc, design_document, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body == design_document def test_put_design_document_required_params_with_retries(self): # Enable retries and run test_put_design_document_required_params. _service.enable_retries() self.test_put_design_document_required_params() # Disable retries and run test_put_design_document_required_params. _service.disable_retries() self.test_put_design_document_required_params() @responses.activate def test_put_design_document_value_error(self): """ test_put_design_document_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Analyzer model analyzer_model = {} analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] # Construct a dict representation of a AnalyzerConfiguration model analyzer_configuration_model = {} analyzer_configuration_model['name'] = 'classic' analyzer_configuration_model['stopwords'] = ['testString'] analyzer_configuration_model['fields'] = {} # Construct a dict representation of a SearchIndexDefinition model search_index_definition_model = {} search_index_definition_model['analyzer'] = analyzer_configuration_model search_index_definition_model['index'] = 'testString' # Construct a dict representation of a DesignDocumentOptions model design_document_options_model = {} design_document_options_model['partitioned'] = True # Construct a dict representation of a DesignDocumentViewsMapReduce model design_document_views_map_reduce_model = {} design_document_views_map_reduce_model['map'] = 'testString' design_document_views_map_reduce_model['reduce'] = 'testString' # Construct a dict representation of a GeoIndexDefinition model geo_index_definition_model = {} geo_index_definition_model['index'] = 'testString' # Construct a dict representation of a DesignDocument model design_document_model = {} design_document_model['_attachments'] = {} design_document_model['_conflicts'] = ['testString'] design_document_model['_deleted'] = True design_document_model['_deleted_conflicts'] = ['testString'] design_document_model['_id'] = 'testString' design_document_model['_local_seq'] = 'testString' design_document_model['_rev'] = 'testString' design_document_model['_revisions'] = revisions_model design_document_model['_revs_info'] = [document_revision_status_model] design_document_model['autoupdate'] = True design_document_model['filters'] = {} design_document_model['indexes'] = {} design_document_model['language'] = 'javascript' design_document_model['options'] = design_document_options_model design_document_model['validate_doc_update'] = 'testString' design_document_model['views'] = {} design_document_model['st_indexes'] = {} design_document_model['foo'] = 'testString' # Set up parameter values db = 'testString' ddoc = 'testString' design_document = design_document_model # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, "design_document": design_document, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.put_design_document(**req_copy) def test_put_design_document_value_error_with_retries(self): # Enable retries and run test_put_design_document_value_error. _service.enable_retries() self.test_put_design_document_value_error() # Disable retries and run test_put_design_document_value_error. _service.disable_retries() self.test_put_design_document_value_error() class TestGetDesignDocumentInformation(): """ Test Class for get_design_document_information """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_design_document_information_all_params(self): """ get_design_document_information() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_info') mock_response = '{"name": "name", "view_index": {"compact_running": false, "language": "language", "signature": "signature", "sizes": {"active": 6, "external": 8, "file": 4}, "updater_running": false, "waiting_clients": 0, "waiting_commit": true}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' # Invoke method response = _service.get_design_document_information( db, ddoc, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_design_document_information_all_params_with_retries(self): # Enable retries and run test_get_design_document_information_all_params. _service.enable_retries() self.test_get_design_document_information_all_params() # Disable retries and run test_get_design_document_information_all_params. _service.disable_retries() self.test_get_design_document_information_all_params() @responses.activate def test_get_design_document_information_value_error(self): """ test_get_design_document_information_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_info') mock_response = '{"name": "name", "view_index": {"compact_running": false, "language": "language", "signature": "signature", "sizes": {"active": 6, "external": 8, "file": 4}, "updater_running": false, "waiting_clients": 0, "waiting_commit": true}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_design_document_information(**req_copy) def test_get_design_document_information_value_error_with_retries(self): # Enable retries and run test_get_design_document_information_value_error. _service.enable_retries() self.test_get_design_document_information_value_error() # Disable retries and run test_get_design_document_information_value_error. _service.disable_retries() self.test_get_design_document_information_value_error() class TestPostDesignDocs(): """ Test Class for post_design_docs """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_design_docs_all_params(self): """ post_design_docs() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design_docs') mock_response = '{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' key = 'testString' keys = ['testString'] startkey = '0007741142412418284' accept = 'application/json' # Invoke method response = _service.post_design_docs( db, att_encoding_info=att_encoding_info, attachments=attachments, conflicts=conflicts, descending=descending, include_docs=include_docs, inclusive_end=inclusive_end, limit=limit, skip=skip, update_seq=update_seq, endkey=endkey, key=key, keys=keys, startkey=startkey, accept=accept, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['att_encoding_info'] == False assert req_body['attachments'] == False assert req_body['conflicts'] == False assert req_body['descending'] == False assert req_body['include_docs'] == False assert req_body['inclusive_end'] == True assert req_body['limit'] == 10 assert req_body['skip'] == 0 assert req_body['update_seq'] == False assert req_body['endkey'] == 'testString' assert req_body['key'] == 'testString' assert req_body['keys'] == ['testString'] assert req_body['startkey'] == '0007741142412418284' def test_post_design_docs_all_params_with_retries(self): # Enable retries and run test_post_design_docs_all_params. _service.enable_retries() self.test_post_design_docs_all_params() # Disable retries and run test_post_design_docs_all_params. _service.disable_retries() self.test_post_design_docs_all_params() @responses.activate def test_post_design_docs_required_params(self): """ test_post_design_docs_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design_docs') mock_response = '{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' key = 'testString' keys = ['testString'] startkey = '0007741142412418284' # Invoke method response = _service.post_design_docs( db, att_encoding_info=att_encoding_info, attachments=attachments, conflicts=conflicts, descending=descending, include_docs=include_docs, inclusive_end=inclusive_end, limit=limit, skip=skip, update_seq=update_seq, endkey=endkey, key=key, keys=keys, startkey=startkey, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['att_encoding_info'] == False assert req_body['attachments'] == False assert req_body['conflicts'] == False assert req_body['descending'] == False assert req_body['include_docs'] == False assert req_body['inclusive_end'] == True assert req_body['limit'] == 10 assert req_body['skip'] == 0 assert req_body['update_seq'] == False assert req_body['endkey'] == 'testString' assert req_body['key'] == 'testString' assert req_body['keys'] == ['testString'] assert req_body['startkey'] == '0007741142412418284' def test_post_design_docs_required_params_with_retries(self): # Enable retries and run test_post_design_docs_required_params. _service.enable_retries() self.test_post_design_docs_required_params() # Disable retries and run test_post_design_docs_required_params. _service.disable_retries() self.test_post_design_docs_required_params() @responses.activate def test_post_design_docs_value_error(self): """ test_post_design_docs_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design_docs') mock_response = '{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' key = 'testString' keys = ['testString'] startkey = '0007741142412418284' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_design_docs(**req_copy) def test_post_design_docs_value_error_with_retries(self): # Enable retries and run test_post_design_docs_value_error. _service.enable_retries() self.test_post_design_docs_value_error() # Disable retries and run test_post_design_docs_value_error. _service.disable_retries() self.test_post_design_docs_value_error() class TestPostDesignDocsQueries(): """ Test Class for post_design_docs_queries """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_design_docs_queries_all_params(self): """ post_design_docs_queries() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design_docs/queries') mock_response = '{"results": [{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a AllDocsQuery model all_docs_query_model = {} all_docs_query_model['att_encoding_info'] = False all_docs_query_model['attachments'] = False all_docs_query_model['conflicts'] = False all_docs_query_model['descending'] = False all_docs_query_model['include_docs'] = False all_docs_query_model['inclusive_end'] = True all_docs_query_model['limit'] = 0 all_docs_query_model['skip'] = 0 all_docs_query_model['update_seq'] = False all_docs_query_model['endkey'] = 'testString' all_docs_query_model['key'] = 'testString' all_docs_query_model['keys'] = ['small-appliances:1000042', 'small-appliances:1000043'] all_docs_query_model['startkey'] = 'testString' # Set up parameter values db = 'testString' queries = [all_docs_query_model] accept = 'application/json' # Invoke method response = _service.post_design_docs_queries( db, queries, accept=accept, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['queries'] == [all_docs_query_model] def test_post_design_docs_queries_all_params_with_retries(self): # Enable retries and run test_post_design_docs_queries_all_params. _service.enable_retries() self.test_post_design_docs_queries_all_params() # Disable retries and run test_post_design_docs_queries_all_params. _service.disable_retries() self.test_post_design_docs_queries_all_params() @responses.activate def test_post_design_docs_queries_required_params(self): """ test_post_design_docs_queries_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design_docs/queries') mock_response = '{"results": [{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a AllDocsQuery model all_docs_query_model = {} all_docs_query_model['att_encoding_info'] = False all_docs_query_model['attachments'] = False all_docs_query_model['conflicts'] = False all_docs_query_model['descending'] = False all_docs_query_model['include_docs'] = False all_docs_query_model['inclusive_end'] = True all_docs_query_model['limit'] = 0 all_docs_query_model['skip'] = 0 all_docs_query_model['update_seq'] = False all_docs_query_model['endkey'] = 'testString' all_docs_query_model['key'] = 'testString' all_docs_query_model['keys'] = ['small-appliances:1000042', 'small-appliances:1000043'] all_docs_query_model['startkey'] = 'testString' # Set up parameter values db = 'testString' queries = [all_docs_query_model] # Invoke method response = _service.post_design_docs_queries( db, queries, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['queries'] == [all_docs_query_model] def test_post_design_docs_queries_required_params_with_retries(self): # Enable retries and run test_post_design_docs_queries_required_params. _service.enable_retries() self.test_post_design_docs_queries_required_params() # Disable retries and run test_post_design_docs_queries_required_params. _service.disable_retries() self.test_post_design_docs_queries_required_params() @responses.activate def test_post_design_docs_queries_value_error(self): """ test_post_design_docs_queries_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design_docs/queries') mock_response = '{"results": [{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a AllDocsQuery model all_docs_query_model = {} all_docs_query_model['att_encoding_info'] = False all_docs_query_model['attachments'] = False all_docs_query_model['conflicts'] = False all_docs_query_model['descending'] = False all_docs_query_model['include_docs'] = False all_docs_query_model['inclusive_end'] = True all_docs_query_model['limit'] = 0 all_docs_query_model['skip'] = 0 all_docs_query_model['update_seq'] = False all_docs_query_model['endkey'] = 'testString' all_docs_query_model['key'] = 'testString' all_docs_query_model['keys'] = ['small-appliances:1000042', 'small-appliances:1000043'] all_docs_query_model['startkey'] = 'testString' # Set up parameter values db = 'testString' queries = [all_docs_query_model] # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "queries": queries, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_design_docs_queries(**req_copy) def test_post_design_docs_queries_value_error_with_retries(self): # Enable retries and run test_post_design_docs_queries_value_error. _service.enable_retries() self.test_post_design_docs_queries_value_error() # Disable retries and run test_post_design_docs_queries_value_error. _service.disable_retries() self.test_post_design_docs_queries_value_error() # endregion ############################################################################## # End of Service: DesignDocuments ############################################################################## ############################################################################## # Start of Service: Views ############################################################################## # region class TestNewInstance(): """ Test Class for new_instance """ def test_new_instance(self): """ new_instance() """ os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): """ new_instance_without_authenticator() """ with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestPostView(): """ Test Class for post_view """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_view_all_params(self): """ post_view() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_view/testString') mock_response = '{"total_rows": 0, "update_seq": "update_seq", "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "anyValue", "value": "anyValue"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' view = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 0 skip = 0 update_seq = False endkey = 'testString' endkey_docid = 'testString' group = False group_level = 1 key = 'testString' keys = ['testString'] reduce = True stable = False startkey = 'testString' startkey_docid = 'testString' update = 'true' # Invoke method response = _service.post_view( db, ddoc, view, att_encoding_info=att_encoding_info, attachments=attachments, conflicts=conflicts, descending=descending, include_docs=include_docs, inclusive_end=inclusive_end, limit=limit, skip=skip, update_seq=update_seq, endkey=endkey, endkey_docid=endkey_docid, group=group, group_level=group_level, key=key, keys=keys, reduce=reduce, stable=stable, startkey=startkey, startkey_docid=startkey_docid, update=update, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['att_encoding_info'] == False assert req_body['attachments'] == False assert req_body['conflicts'] == False assert req_body['descending'] == False assert req_body['include_docs'] == False assert req_body['inclusive_end'] == True assert req_body['limit'] == 0 assert req_body['skip'] == 0 assert req_body['update_seq'] == False assert req_body['endkey'] == 'testString' assert req_body['endkey_docid'] == 'testString' assert req_body['group'] == False assert req_body['group_level'] == 1 assert req_body['key'] == 'testString' assert req_body['keys'] == ['testString'] assert req_body['reduce'] == True assert req_body['stable'] == False assert req_body['startkey'] == 'testString' assert req_body['startkey_docid'] == 'testString' assert req_body['update'] == 'true' def test_post_view_all_params_with_retries(self): # Enable retries and run test_post_view_all_params. _service.enable_retries() self.test_post_view_all_params() # Disable retries and run test_post_view_all_params. _service.disable_retries() self.test_post_view_all_params() @responses.activate def test_post_view_value_error(self): """ test_post_view_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_view/testString') mock_response = '{"total_rows": 0, "update_seq": "update_seq", "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "anyValue", "value": "anyValue"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' view = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 0 skip = 0 update_seq = False endkey = 'testString' endkey_docid = 'testString' group = False group_level = 1 key = 'testString' keys = ['testString'] reduce = True stable = False startkey = 'testString' startkey_docid = 'testString' update = 'true' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, "view": view, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_view(**req_copy) def test_post_view_value_error_with_retries(self): # Enable retries and run test_post_view_value_error. _service.enable_retries() self.test_post_view_value_error() # Disable retries and run test_post_view_value_error. _service.disable_retries() self.test_post_view_value_error() class TestPostViewAsStream(): """ Test Class for post_view_as_stream """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_view_as_stream_all_params(self): """ post_view_as_stream() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_view/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' view = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = True inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' endkey_docid = 'testString' group = False group_level = 1 key = 'testString' keys = ['examplekey'] reduce = True stable = False startkey = 'testString' startkey_docid = 'testString' update = 'true' # Invoke method response = _service.post_view_as_stream( db, ddoc, view, att_encoding_info=att_encoding_info, attachments=attachments, conflicts=conflicts, descending=descending, include_docs=include_docs, inclusive_end=inclusive_end, limit=limit, skip=skip, update_seq=update_seq, endkey=endkey, endkey_docid=endkey_docid, group=group, group_level=group_level, key=key, keys=keys, reduce=reduce, stable=stable, startkey=startkey, startkey_docid=startkey_docid, update=update, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['att_encoding_info'] == False assert req_body['attachments'] == False assert req_body['conflicts'] == False assert req_body['descending'] == False assert req_body['include_docs'] == True assert req_body['inclusive_end'] == True assert req_body['limit'] == 10 assert req_body['skip'] == 0 assert req_body['update_seq'] == False assert req_body['endkey'] == 'testString' assert req_body['endkey_docid'] == 'testString' assert req_body['group'] == False assert req_body['group_level'] == 1 assert req_body['key'] == 'testString' assert req_body['keys'] == ['examplekey'] assert req_body['reduce'] == True assert req_body['stable'] == False assert req_body['startkey'] == 'testString' assert req_body['startkey_docid'] == 'testString' assert req_body['update'] == 'true' # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_view_as_stream_all_params_with_retries(self): # Enable retries and run test_post_view_as_stream_all_params. _service.enable_retries() self.test_post_view_as_stream_all_params() # Disable retries and run test_post_view_as_stream_all_params. _service.disable_retries() self.test_post_view_as_stream_all_params() @responses.activate def test_post_view_as_stream_value_error(self): """ test_post_view_as_stream_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_view/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' view = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = True inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' endkey_docid = 'testString' group = False group_level = 1 key = 'testString' keys = ['examplekey'] reduce = True stable = False startkey = 'testString' startkey_docid = 'testString' update = 'true' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, "view": view, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_view_as_stream(**req_copy) def test_post_view_as_stream_value_error_with_retries(self): # Enable retries and run test_post_view_as_stream_value_error. _service.enable_retries() self.test_post_view_as_stream_value_error() # Disable retries and run test_post_view_as_stream_value_error. _service.disable_retries() self.test_post_view_as_stream_value_error() class TestPostViewQueries(): """ Test Class for post_view_queries """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_view_queries_all_params(self): """ post_view_queries() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_view/testString/queries') mock_response = '{"results": [{"total_rows": 0, "update_seq": "update_seq", "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "anyValue", "value": "anyValue"}]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a ViewQuery model view_query_model = {} view_query_model['att_encoding_info'] = False view_query_model['attachments'] = False view_query_model['conflicts'] = False view_query_model['descending'] = False view_query_model['include_docs'] = False view_query_model['inclusive_end'] = True view_query_model['limit'] = 0 view_query_model['skip'] = 0 view_query_model['update_seq'] = False view_query_model['endkey'] = 'testString' view_query_model['endkey_docid'] = 'testString' view_query_model['group'] = False view_query_model['group_level'] = 1 view_query_model['key'] = 'testString' view_query_model['keys'] = ['testString'] view_query_model['reduce'] = True view_query_model['stable'] = False view_query_model['startkey'] = 'testString' view_query_model['startkey_docid'] = 'testString' view_query_model['update'] = 'true' # Set up parameter values db = 'testString' ddoc = 'testString' view = 'testString' queries = [view_query_model] # Invoke method response = _service.post_view_queries( db, ddoc, view, queries, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['queries'] == [view_query_model] def test_post_view_queries_all_params_with_retries(self): # Enable retries and run test_post_view_queries_all_params. _service.enable_retries() self.test_post_view_queries_all_params() # Disable retries and run test_post_view_queries_all_params. _service.disable_retries() self.test_post_view_queries_all_params() @responses.activate def test_post_view_queries_value_error(self): """ test_post_view_queries_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_view/testString/queries') mock_response = '{"results": [{"total_rows": 0, "update_seq": "update_seq", "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "anyValue", "value": "anyValue"}]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a ViewQuery model view_query_model = {} view_query_model['att_encoding_info'] = False view_query_model['attachments'] = False view_query_model['conflicts'] = False view_query_model['descending'] = False view_query_model['include_docs'] = False view_query_model['inclusive_end'] = True view_query_model['limit'] = 0 view_query_model['skip'] = 0 view_query_model['update_seq'] = False view_query_model['endkey'] = 'testString' view_query_model['endkey_docid'] = 'testString' view_query_model['group'] = False view_query_model['group_level'] = 1 view_query_model['key'] = 'testString' view_query_model['keys'] = ['testString'] view_query_model['reduce'] = True view_query_model['stable'] = False view_query_model['startkey'] = 'testString' view_query_model['startkey_docid'] = 'testString' view_query_model['update'] = 'true' # Set up parameter values db = 'testString' ddoc = 'testString' view = 'testString' queries = [view_query_model] # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, "view": view, "queries": queries, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_view_queries(**req_copy) def test_post_view_queries_value_error_with_retries(self): # Enable retries and run test_post_view_queries_value_error. _service.enable_retries() self.test_post_view_queries_value_error() # Disable retries and run test_post_view_queries_value_error. _service.disable_retries() self.test_post_view_queries_value_error() class TestPostViewQueriesAsStream(): """ Test Class for post_view_queries_as_stream """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_view_queries_as_stream_all_params(self): """ post_view_queries_as_stream() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_view/testString/queries') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a ViewQuery model view_query_model = {} view_query_model['att_encoding_info'] = False view_query_model['attachments'] = False view_query_model['conflicts'] = False view_query_model['descending'] = False view_query_model['include_docs'] = True view_query_model['inclusive_end'] = True view_query_model['limit'] = 5 view_query_model['skip'] = 0 view_query_model['update_seq'] = False view_query_model['endkey'] = 'testString' view_query_model['endkey_docid'] = 'testString' view_query_model['group'] = False view_query_model['group_level'] = 1 view_query_model['key'] = 'testString' view_query_model['keys'] = ['testString'] view_query_model['reduce'] = True view_query_model['stable'] = False view_query_model['startkey'] = 'testString' view_query_model['startkey_docid'] = 'testString' view_query_model['update'] = 'true' # Set up parameter values db = 'testString' ddoc = 'testString' view = 'testString' queries = [view_query_model] # Invoke method response = _service.post_view_queries_as_stream( db, ddoc, view, queries, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['queries'] == [view_query_model] # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_view_queries_as_stream_all_params_with_retries(self): # Enable retries and run test_post_view_queries_as_stream_all_params. _service.enable_retries() self.test_post_view_queries_as_stream_all_params() # Disable retries and run test_post_view_queries_as_stream_all_params. _service.disable_retries() self.test_post_view_queries_as_stream_all_params() @responses.activate def test_post_view_queries_as_stream_value_error(self): """ test_post_view_queries_as_stream_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_view/testString/queries') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a ViewQuery model view_query_model = {} view_query_model['att_encoding_info'] = False view_query_model['attachments'] = False view_query_model['conflicts'] = False view_query_model['descending'] = False view_query_model['include_docs'] = True view_query_model['inclusive_end'] = True view_query_model['limit'] = 5 view_query_model['skip'] = 0 view_query_model['update_seq'] = False view_query_model['endkey'] = 'testString' view_query_model['endkey_docid'] = 'testString' view_query_model['group'] = False view_query_model['group_level'] = 1 view_query_model['key'] = 'testString' view_query_model['keys'] = ['testString'] view_query_model['reduce'] = True view_query_model['stable'] = False view_query_model['startkey'] = 'testString' view_query_model['startkey_docid'] = 'testString' view_query_model['update'] = 'true' # Set up parameter values db = 'testString' ddoc = 'testString' view = 'testString' queries = [view_query_model] # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, "view": view, "queries": queries, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_view_queries_as_stream(**req_copy) def test_post_view_queries_as_stream_value_error_with_retries(self): # Enable retries and run test_post_view_queries_as_stream_value_error. _service.enable_retries() self.test_post_view_queries_as_stream_value_error() # Disable retries and run test_post_view_queries_as_stream_value_error. _service.disable_retries() self.test_post_view_queries_as_stream_value_error() # endregion ############################################################################## # End of Service: Views ############################################################################## ############################################################################## # Start of Service: PartitionedDatabases ############################################################################## # region class TestNewInstance(): """ Test Class for new_instance """ def test_new_instance(self): """ new_instance() """ os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): """ new_instance_without_authenticator() """ with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestGetPartitionInformation(): """ Test Class for get_partition_information """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_partition_information_all_params(self): """ get_partition_information() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString') mock_response = '{"db_name": "db_name", "doc_count": 0, "doc_del_count": 0, "partition": "partition", "partitioned_indexes": {"count": 0, "indexes": {"search": 0, "view": 0}, "limit": 0}, "sizes": {"active": 0, "external": 0}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' # Invoke method response = _service.get_partition_information( db, partition_key, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_partition_information_all_params_with_retries(self): # Enable retries and run test_get_partition_information_all_params. _service.enable_retries() self.test_get_partition_information_all_params() # Disable retries and run test_get_partition_information_all_params. _service.disable_retries() self.test_get_partition_information_all_params() @responses.activate def test_get_partition_information_value_error(self): """ test_get_partition_information_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString') mock_response = '{"db_name": "db_name", "doc_count": 0, "doc_del_count": 0, "partition": "partition", "partitioned_indexes": {"count": 0, "indexes": {"search": 0, "view": 0}, "limit": 0}, "sizes": {"active": 0, "external": 0}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "partition_key": partition_key, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_partition_information(**req_copy) def test_get_partition_information_value_error_with_retries(self): # Enable retries and run test_get_partition_information_value_error. _service.enable_retries() self.test_get_partition_information_value_error() # Disable retries and run test_get_partition_information_value_error. _service.disable_retries() self.test_get_partition_information_value_error() class TestPostPartitionAllDocs(): """ Test Class for post_partition_all_docs """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_partition_all_docs_all_params(self): """ post_partition_all_docs() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_all_docs') mock_response = '{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' key = 'testString' keys = ['testString'] startkey = '0007741142412418284' # Invoke method response = _service.post_partition_all_docs( db, partition_key, att_encoding_info=att_encoding_info, attachments=attachments, conflicts=conflicts, descending=descending, include_docs=include_docs, inclusive_end=inclusive_end, limit=limit, skip=skip, update_seq=update_seq, endkey=endkey, key=key, keys=keys, startkey=startkey, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['att_encoding_info'] == False assert req_body['attachments'] == False assert req_body['conflicts'] == False assert req_body['descending'] == False assert req_body['include_docs'] == False assert req_body['inclusive_end'] == True assert req_body['limit'] == 10 assert req_body['skip'] == 0 assert req_body['update_seq'] == False assert req_body['endkey'] == 'testString' assert req_body['key'] == 'testString' assert req_body['keys'] == ['testString'] assert req_body['startkey'] == '0007741142412418284' def test_post_partition_all_docs_all_params_with_retries(self): # Enable retries and run test_post_partition_all_docs_all_params. _service.enable_retries() self.test_post_partition_all_docs_all_params() # Disable retries and run test_post_partition_all_docs_all_params. _service.disable_retries() self.test_post_partition_all_docs_all_params() @responses.activate def test_post_partition_all_docs_value_error(self): """ test_post_partition_all_docs_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_all_docs') mock_response = '{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' key = 'testString' keys = ['testString'] startkey = '0007741142412418284' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "partition_key": partition_key, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_partition_all_docs(**req_copy) def test_post_partition_all_docs_value_error_with_retries(self): # Enable retries and run test_post_partition_all_docs_value_error. _service.enable_retries() self.test_post_partition_all_docs_value_error() # Disable retries and run test_post_partition_all_docs_value_error. _service.disable_retries() self.test_post_partition_all_docs_value_error() class TestPostPartitionAllDocsAsStream(): """ Test Class for post_partition_all_docs_as_stream """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_partition_all_docs_as_stream_all_params(self): """ post_partition_all_docs_as_stream() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_all_docs') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' key = 'testString' keys = ['testString'] startkey = '0007741142412418284' # Invoke method response = _service.post_partition_all_docs_as_stream( db, partition_key, att_encoding_info=att_encoding_info, attachments=attachments, conflicts=conflicts, descending=descending, include_docs=include_docs, inclusive_end=inclusive_end, limit=limit, skip=skip, update_seq=update_seq, endkey=endkey, key=key, keys=keys, startkey=startkey, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['att_encoding_info'] == False assert req_body['attachments'] == False assert req_body['conflicts'] == False assert req_body['descending'] == False assert req_body['include_docs'] == False assert req_body['inclusive_end'] == True assert req_body['limit'] == 10 assert req_body['skip'] == 0 assert req_body['update_seq'] == False assert req_body['endkey'] == 'testString' assert req_body['key'] == 'testString' assert req_body['keys'] == ['testString'] assert req_body['startkey'] == '0007741142412418284' # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_partition_all_docs_as_stream_all_params_with_retries(self): # Enable retries and run test_post_partition_all_docs_as_stream_all_params. _service.enable_retries() self.test_post_partition_all_docs_as_stream_all_params() # Disable retries and run test_post_partition_all_docs_as_stream_all_params. _service.disable_retries() self.test_post_partition_all_docs_as_stream_all_params() @responses.activate def test_post_partition_all_docs_as_stream_value_error(self): """ test_post_partition_all_docs_as_stream_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_all_docs') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' key = 'testString' keys = ['testString'] startkey = '0007741142412418284' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "partition_key": partition_key, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_partition_all_docs_as_stream(**req_copy) def test_post_partition_all_docs_as_stream_value_error_with_retries(self): # Enable retries and run test_post_partition_all_docs_as_stream_value_error. _service.enable_retries() self.test_post_partition_all_docs_as_stream_value_error() # Disable retries and run test_post_partition_all_docs_as_stream_value_error. _service.disable_retries() self.test_post_partition_all_docs_as_stream_value_error() class TestPostPartitionSearch(): """ Test Class for post_partition_search """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_partition_search_all_params(self): """ post_partition_search() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_design/testString/_search/testString') mock_response = '{"total_rows": 0, "bookmark": "bookmark", "by": "by", "counts": {"mapKey": {"mapKey": 0}}, "ranges": {"mapKey": {"mapKey": 0}}, "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "fields": {"mapKey": "anyValue"}, "highlights": {"mapKey": ["inner"]}, "id": "id"}], "groups": [{"total_rows": 0, "bookmark": "bookmark", "by": "by", "counts": {"mapKey": {"mapKey": 0}}, "ranges": {"mapKey": {"mapKey": 0}}, "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "fields": {"mapKey": "anyValue"}, "highlights": {"mapKey": ["inner"]}, "id": "id"}]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' ddoc = 'testString' index = 'testString' query = 'testString' bookmark = 'testString' highlight_fields = ['testString'] highlight_number = 1 highlight_post_tag = '</em>' highlight_pre_tag = '<em>' highlight_size = 1 include_docs = False include_fields = ['testString'] limit = 0 sort = ['testString'] stale = 'ok' # Invoke method response = _service.post_partition_search( db, partition_key, ddoc, index, query, bookmark=bookmark, highlight_fields=highlight_fields, highlight_number=highlight_number, highlight_post_tag=highlight_post_tag, highlight_pre_tag=highlight_pre_tag, highlight_size=highlight_size, include_docs=include_docs, include_fields=include_fields, limit=limit, sort=sort, stale=stale, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['query'] == 'testString' assert req_body['bookmark'] == 'testString' assert req_body['highlight_fields'] == ['testString'] assert req_body['highlight_number'] == 1 assert req_body['highlight_post_tag'] == '</em>' assert req_body['highlight_pre_tag'] == '<em>' assert req_body['highlight_size'] == 1 assert req_body['include_docs'] == False assert req_body['include_fields'] == ['testString'] assert req_body['limit'] == 0 assert req_body['sort'] == ['testString'] assert req_body['stale'] == 'ok' def test_post_partition_search_all_params_with_retries(self): # Enable retries and run test_post_partition_search_all_params. _service.enable_retries() self.test_post_partition_search_all_params() # Disable retries and run test_post_partition_search_all_params. _service.disable_retries() self.test_post_partition_search_all_params() @responses.activate def test_post_partition_search_value_error(self): """ test_post_partition_search_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_design/testString/_search/testString') mock_response = '{"total_rows": 0, "bookmark": "bookmark", "by": "by", "counts": {"mapKey": {"mapKey": 0}}, "ranges": {"mapKey": {"mapKey": 0}}, "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "fields": {"mapKey": "anyValue"}, "highlights": {"mapKey": ["inner"]}, "id": "id"}], "groups": [{"total_rows": 0, "bookmark": "bookmark", "by": "by", "counts": {"mapKey": {"mapKey": 0}}, "ranges": {"mapKey": {"mapKey": 0}}, "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "fields": {"mapKey": "anyValue"}, "highlights": {"mapKey": ["inner"]}, "id": "id"}]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' ddoc = 'testString' index = 'testString' query = 'testString' bookmark = 'testString' highlight_fields = ['testString'] highlight_number = 1 highlight_post_tag = '</em>' highlight_pre_tag = '<em>' highlight_size = 1 include_docs = False include_fields = ['testString'] limit = 0 sort = ['testString'] stale = 'ok' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "partition_key": partition_key, "ddoc": ddoc, "index": index, "query": query, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_partition_search(**req_copy) def test_post_partition_search_value_error_with_retries(self): # Enable retries and run test_post_partition_search_value_error. _service.enable_retries() self.test_post_partition_search_value_error() # Disable retries and run test_post_partition_search_value_error. _service.disable_retries() self.test_post_partition_search_value_error() class TestPostPartitionSearchAsStream(): """ Test Class for post_partition_search_as_stream """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_partition_search_as_stream_all_params(self): """ post_partition_search_as_stream() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_design/testString/_search/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' ddoc = 'testString' index = 'testString' query = 'testString' bookmark = 'testString' highlight_fields = ['testString'] highlight_number = 1 highlight_post_tag = '</em>' highlight_pre_tag = '<em>' highlight_size = 1 include_docs = False include_fields = ['testString'] limit = 3 sort = ['testString'] stale = 'ok' # Invoke method response = _service.post_partition_search_as_stream( db, partition_key, ddoc, index, query, bookmark=bookmark, highlight_fields=highlight_fields, highlight_number=highlight_number, highlight_post_tag=highlight_post_tag, highlight_pre_tag=highlight_pre_tag, highlight_size=highlight_size, include_docs=include_docs, include_fields=include_fields, limit=limit, sort=sort, stale=stale, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['query'] == 'testString' assert req_body['bookmark'] == 'testString' assert req_body['highlight_fields'] == ['testString'] assert req_body['highlight_number'] == 1 assert req_body['highlight_post_tag'] == '</em>' assert req_body['highlight_pre_tag'] == '<em>' assert req_body['highlight_size'] == 1 assert req_body['include_docs'] == False assert req_body['include_fields'] == ['testString'] assert req_body['limit'] == 3 assert req_body['sort'] == ['testString'] assert req_body['stale'] == 'ok' # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_partition_search_as_stream_all_params_with_retries(self): # Enable retries and run test_post_partition_search_as_stream_all_params. _service.enable_retries() self.test_post_partition_search_as_stream_all_params() # Disable retries and run test_post_partition_search_as_stream_all_params. _service.disable_retries() self.test_post_partition_search_as_stream_all_params() @responses.activate def test_post_partition_search_as_stream_value_error(self): """ test_post_partition_search_as_stream_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_design/testString/_search/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' ddoc = 'testString' index = 'testString' query = 'testString' bookmark = 'testString' highlight_fields = ['testString'] highlight_number = 1 highlight_post_tag = '</em>' highlight_pre_tag = '<em>' highlight_size = 1 include_docs = False include_fields = ['testString'] limit = 3 sort = ['testString'] stale = 'ok' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "partition_key": partition_key, "ddoc": ddoc, "index": index, "query": query, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_partition_search_as_stream(**req_copy) def test_post_partition_search_as_stream_value_error_with_retries(self): # Enable retries and run test_post_partition_search_as_stream_value_error. _service.enable_retries() self.test_post_partition_search_as_stream_value_error() # Disable retries and run test_post_partition_search_as_stream_value_error. _service.disable_retries() self.test_post_partition_search_as_stream_value_error() class TestPostPartitionView(): """ Test Class for post_partition_view """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_partition_view_all_params(self): """ post_partition_view() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_design/testString/_view/testString') mock_response = '{"total_rows": 0, "update_seq": "update_seq", "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "anyValue", "value": "anyValue"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' ddoc = 'testString' view = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = True inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' endkey_docid = 'testString' group = False group_level = 1 key = 'testString' keys = ['examplekey'] reduce = True stable = False startkey = 'testString' startkey_docid = 'testString' update = 'true' # Invoke method response = _service.post_partition_view( db, partition_key, ddoc, view, att_encoding_info=att_encoding_info, attachments=attachments, conflicts=conflicts, descending=descending, include_docs=include_docs, inclusive_end=inclusive_end, limit=limit, skip=skip, update_seq=update_seq, endkey=endkey, endkey_docid=endkey_docid, group=group, group_level=group_level, key=key, keys=keys, reduce=reduce, stable=stable, startkey=startkey, startkey_docid=startkey_docid, update=update, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['att_encoding_info'] == False assert req_body['attachments'] == False assert req_body['conflicts'] == False assert req_body['descending'] == False assert req_body['include_docs'] == True assert req_body['inclusive_end'] == True assert req_body['limit'] == 10 assert req_body['skip'] == 0 assert req_body['update_seq'] == False assert req_body['endkey'] == 'testString' assert req_body['endkey_docid'] == 'testString' assert req_body['group'] == False assert req_body['group_level'] == 1 assert req_body['key'] == 'testString' assert req_body['keys'] == ['examplekey'] assert req_body['reduce'] == True assert req_body['stable'] == False assert req_body['startkey'] == 'testString' assert req_body['startkey_docid'] == 'testString' assert req_body['update'] == 'true' def test_post_partition_view_all_params_with_retries(self): # Enable retries and run test_post_partition_view_all_params. _service.enable_retries() self.test_post_partition_view_all_params() # Disable retries and run test_post_partition_view_all_params. _service.disable_retries() self.test_post_partition_view_all_params() @responses.activate def test_post_partition_view_value_error(self): """ test_post_partition_view_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_design/testString/_view/testString') mock_response = '{"total_rows": 0, "update_seq": "update_seq", "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "anyValue", "value": "anyValue"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' ddoc = 'testString' view = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = True inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' endkey_docid = 'testString' group = False group_level = 1 key = 'testString' keys = ['examplekey'] reduce = True stable = False startkey = 'testString' startkey_docid = 'testString' update = 'true' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "partition_key": partition_key, "ddoc": ddoc, "view": view, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_partition_view(**req_copy) def test_post_partition_view_value_error_with_retries(self): # Enable retries and run test_post_partition_view_value_error. _service.enable_retries() self.test_post_partition_view_value_error() # Disable retries and run test_post_partition_view_value_error. _service.disable_retries() self.test_post_partition_view_value_error() class TestPostPartitionViewAsStream(): """ Test Class for post_partition_view_as_stream """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_partition_view_as_stream_all_params(self): """ post_partition_view_as_stream() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_design/testString/_view/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' ddoc = 'testString' view = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = True inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' endkey_docid = 'testString' group = False group_level = 1 key = 'testString' keys = ['examplekey'] reduce = True stable = False startkey = 'testString' startkey_docid = 'testString' update = 'true' # Invoke method response = _service.post_partition_view_as_stream( db, partition_key, ddoc, view, att_encoding_info=att_encoding_info, attachments=attachments, conflicts=conflicts, descending=descending, include_docs=include_docs, inclusive_end=inclusive_end, limit=limit, skip=skip, update_seq=update_seq, endkey=endkey, endkey_docid=endkey_docid, group=group, group_level=group_level, key=key, keys=keys, reduce=reduce, stable=stable, startkey=startkey, startkey_docid=startkey_docid, update=update, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['att_encoding_info'] == False assert req_body['attachments'] == False assert req_body['conflicts'] == False assert req_body['descending'] == False assert req_body['include_docs'] == True assert req_body['inclusive_end'] == True assert req_body['limit'] == 10 assert req_body['skip'] == 0 assert req_body['update_seq'] == False assert req_body['endkey'] == 'testString' assert req_body['endkey_docid'] == 'testString' assert req_body['group'] == False assert req_body['group_level'] == 1 assert req_body['key'] == 'testString' assert req_body['keys'] == ['examplekey'] assert req_body['reduce'] == True assert req_body['stable'] == False assert req_body['startkey'] == 'testString' assert req_body['startkey_docid'] == 'testString' assert req_body['update'] == 'true' # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_partition_view_as_stream_all_params_with_retries(self): # Enable retries and run test_post_partition_view_as_stream_all_params. _service.enable_retries() self.test_post_partition_view_as_stream_all_params() # Disable retries and run test_post_partition_view_as_stream_all_params. _service.disable_retries() self.test_post_partition_view_as_stream_all_params() @responses.activate def test_post_partition_view_as_stream_value_error(self): """ test_post_partition_view_as_stream_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_design/testString/_view/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' ddoc = 'testString' view = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = True inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' endkey_docid = 'testString' group = False group_level = 1 key = 'testString' keys = ['examplekey'] reduce = True stable = False startkey = 'testString' startkey_docid = 'testString' update = 'true' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "partition_key": partition_key, "ddoc": ddoc, "view": view, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_partition_view_as_stream(**req_copy) def test_post_partition_view_as_stream_value_error_with_retries(self): # Enable retries and run test_post_partition_view_as_stream_value_error. _service.enable_retries() self.test_post_partition_view_as_stream_value_error() # Disable retries and run test_post_partition_view_as_stream_value_error. _service.disable_retries() self.test_post_partition_view_as_stream_value_error() class TestPostPartitionFind(): """ Test Class for post_partition_find """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_partition_find_all_params(self): """ post_partition_find() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_find') mock_response = '{"bookmark": "bookmark", "docs": [{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}], "execution_stats": {"execution_time_ms": 17, "results_returned": 0, "total_docs_examined": 0, "total_keys_examined": 0, "total_quorum_docs_examined": 0}, "warning": "warning"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' selector = {} bookmark = 'testString' conflicts = True execution_stats = True fields = ['testString'] limit = 0 skip = 0 sort = [{}] stable = True update = 'true' use_index = ['testString'] # Invoke method response = _service.post_partition_find( db, partition_key, selector, bookmark=bookmark, conflicts=conflicts, execution_stats=execution_stats, fields=fields, limit=limit, skip=skip, sort=sort, stable=stable, update=update, use_index=use_index, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['selector'] == {} assert req_body['bookmark'] == 'testString' assert req_body['conflicts'] == True assert req_body['execution_stats'] == True assert req_body['fields'] == ['testString'] assert req_body['limit'] == 0 assert req_body['skip'] == 0 assert req_body['sort'] == [{}] assert req_body['stable'] == True assert req_body['update'] == 'true' assert req_body['use_index'] == ['testString'] def test_post_partition_find_all_params_with_retries(self): # Enable retries and run test_post_partition_find_all_params. _service.enable_retries() self.test_post_partition_find_all_params() # Disable retries and run test_post_partition_find_all_params. _service.disable_retries() self.test_post_partition_find_all_params() @responses.activate def test_post_partition_find_value_error(self): """ test_post_partition_find_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_find') mock_response = '{"bookmark": "bookmark", "docs": [{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}], "execution_stats": {"execution_time_ms": 17, "results_returned": 0, "total_docs_examined": 0, "total_keys_examined": 0, "total_quorum_docs_examined": 0}, "warning": "warning"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' selector = {} bookmark = 'testString' conflicts = True execution_stats = True fields = ['testString'] limit = 0 skip = 0 sort = [{}] stable = True update = 'true' use_index = ['testString'] # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "partition_key": partition_key, "selector": selector, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_partition_find(**req_copy) def test_post_partition_find_value_error_with_retries(self): # Enable retries and run test_post_partition_find_value_error. _service.enable_retries() self.test_post_partition_find_value_error() # Disable retries and run test_post_partition_find_value_error. _service.disable_retries() self.test_post_partition_find_value_error() class TestPostPartitionFindAsStream(): """ Test Class for post_partition_find_as_stream """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_partition_find_as_stream_all_params(self): """ post_partition_find_as_stream() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_find') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' selector = {} bookmark = 'testString' conflicts = True execution_stats = True fields = ['productid', 'name', 'description'] limit = 0 skip = 0 sort = [{}] stable = True update = 'true' use_index = ['testString'] # Invoke method response = _service.post_partition_find_as_stream( db, partition_key, selector, bookmark=bookmark, conflicts=conflicts, execution_stats=execution_stats, fields=fields, limit=limit, skip=skip, sort=sort, stable=stable, update=update, use_index=use_index, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['selector'] == {} assert req_body['bookmark'] == 'testString' assert req_body['conflicts'] == True assert req_body['execution_stats'] == True assert req_body['fields'] == ['productid', 'name', 'description'] assert req_body['limit'] == 0 assert req_body['skip'] == 0 assert req_body['sort'] == [{}] assert req_body['stable'] == True assert req_body['update'] == 'true' assert req_body['use_index'] == ['testString'] # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_partition_find_as_stream_all_params_with_retries(self): # Enable retries and run test_post_partition_find_as_stream_all_params. _service.enable_retries() self.test_post_partition_find_as_stream_all_params() # Disable retries and run test_post_partition_find_as_stream_all_params. _service.disable_retries() self.test_post_partition_find_as_stream_all_params() @responses.activate def test_post_partition_find_as_stream_value_error(self): """ test_post_partition_find_as_stream_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_find') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' selector = {} bookmark = 'testString' conflicts = True execution_stats = True fields = ['productid', 'name', 'description'] limit = 0 skip = 0 sort = [{}] stable = True update = 'true' use_index = ['testString'] # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "partition_key": partition_key, "selector": selector, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_partition_find_as_stream(**req_copy) def test_post_partition_find_as_stream_value_error_with_retries(self): # Enable retries and run test_post_partition_find_as_stream_value_error. _service.enable_retries() self.test_post_partition_find_as_stream_value_error() # Disable retries and run test_post_partition_find_as_stream_value_error. _service.disable_retries() self.test_post_partition_find_as_stream_value_error() # endregion ############################################################################## # End of Service: PartitionedDatabases ############################################################################## ############################################################################## # Start of Service: Queries ############################################################################## # region class TestNewInstance(): """ Test Class for new_instance """ def test_new_instance(self): """ new_instance() """ os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): """ new_instance_without_authenticator() """ with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestPostExplain(): """ Test Class for post_explain """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_explain_all_params(self): """ post_explain() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_explain') mock_response = '{"dbname": "dbname", "fields": ["fields"], "index": {"ddoc": "ddoc", "def": {"default_analyzer": {"name": "classic", "stopwords": ["stopwords"]}, "default_field": {"analyzer": {"name": "classic", "stopwords": ["stopwords"]}, "enabled": true}, "fields": [{"name": "name", "type": "boolean"}], "index_array_lengths": true, "partial_filter_selector": {"mapKey": "anyValue"}}, "name": "name", "type": "json"}, "limit": 0, "opts": {"mapKey": "anyValue"}, "range": {"end_key": ["anyValue"], "start_key": ["anyValue"]}, "selector": {"mapKey": "anyValue"}, "skip": 0}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' selector = {} bookmark = 'testString' conflicts = True execution_stats = True fields = ['testString'] limit = 0 skip = 0 sort = [{}] stable = True update = 'true' use_index = ['testString'] r = 1 # Invoke method response = _service.post_explain( db, selector, bookmark=bookmark, conflicts=conflicts, execution_stats=execution_stats, fields=fields, limit=limit, skip=skip, sort=sort, stable=stable, update=update, use_index=use_index, r=r, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['selector'] == {} assert req_body['bookmark'] == 'testString' assert req_body['conflicts'] == True assert req_body['execution_stats'] == True assert req_body['fields'] == ['testString'] assert req_body['limit'] == 0 assert req_body['skip'] == 0 assert req_body['sort'] == [{}] assert req_body['stable'] == True assert req_body['update'] == 'true' assert req_body['use_index'] == ['testString'] assert req_body['r'] == 1 def test_post_explain_all_params_with_retries(self): # Enable retries and run test_post_explain_all_params. _service.enable_retries() self.test_post_explain_all_params() # Disable retries and run test_post_explain_all_params. _service.disable_retries() self.test_post_explain_all_params() @responses.activate def test_post_explain_value_error(self): """ test_post_explain_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_explain') mock_response = '{"dbname": "dbname", "fields": ["fields"], "index": {"ddoc": "ddoc", "def": {"default_analyzer": {"name": "classic", "stopwords": ["stopwords"]}, "default_field": {"analyzer": {"name": "classic", "stopwords": ["stopwords"]}, "enabled": true}, "fields": [{"name": "name", "type": "boolean"}], "index_array_lengths": true, "partial_filter_selector": {"mapKey": "anyValue"}}, "name": "name", "type": "json"}, "limit": 0, "opts": {"mapKey": "anyValue"}, "range": {"end_key": ["anyValue"], "start_key": ["anyValue"]}, "selector": {"mapKey": "anyValue"}, "skip": 0}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' selector = {} bookmark = 'testString' conflicts = True execution_stats = True fields = ['testString'] limit = 0 skip = 0 sort = [{}] stable = True update = 'true' use_index = ['testString'] r = 1 # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "selector": selector, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_explain(**req_copy) def test_post_explain_value_error_with_retries(self): # Enable retries and run test_post_explain_value_error. _service.enable_retries() self.test_post_explain_value_error() # Disable retries and run test_post_explain_value_error. _service.disable_retries() self.test_post_explain_value_error() class TestPostFind(): """ Test Class for post_find """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_find_all_params(self): """ post_find() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_find') mock_response = '{"bookmark": "bookmark", "docs": [{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}], "execution_stats": {"execution_time_ms": 17, "results_returned": 0, "total_docs_examined": 0, "total_keys_examined": 0, "total_quorum_docs_examined": 0}, "warning": "warning"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' selector = {} bookmark = 'testString' conflicts = True execution_stats = True fields = ['_id', 'type', 'name', 'email'] limit = 3 skip = 0 sort = [{}] stable = True update = 'true' use_index = ['testString'] r = 1 # Invoke method response = _service.post_find( db, selector, bookmark=bookmark, conflicts=conflicts, execution_stats=execution_stats, fields=fields, limit=limit, skip=skip, sort=sort, stable=stable, update=update, use_index=use_index, r=r, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['selector'] == {} assert req_body['bookmark'] == 'testString' assert req_body['conflicts'] == True assert req_body['execution_stats'] == True assert req_body['fields'] == ['_id', 'type', 'name', 'email'] assert req_body['limit'] == 3 assert req_body['skip'] == 0 assert req_body['sort'] == [{}] assert req_body['stable'] == True assert req_body['update'] == 'true' assert req_body['use_index'] == ['testString'] assert req_body['r'] == 1 def test_post_find_all_params_with_retries(self): # Enable retries and run test_post_find_all_params. _service.enable_retries() self.test_post_find_all_params() # Disable retries and run test_post_find_all_params. _service.disable_retries() self.test_post_find_all_params() @responses.activate def test_post_find_value_error(self): """ test_post_find_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_find') mock_response = '{"bookmark": "bookmark", "docs": [{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}], "execution_stats": {"execution_time_ms": 17, "results_returned": 0, "total_docs_examined": 0, "total_keys_examined": 0, "total_quorum_docs_examined": 0}, "warning": "warning"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' selector = {} bookmark = 'testString' conflicts = True execution_stats = True fields = ['_id', 'type', 'name', 'email'] limit = 3 skip = 0 sort = [{}] stable = True update = 'true' use_index = ['testString'] r = 1 # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "selector": selector, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_find(**req_copy) def test_post_find_value_error_with_retries(self): # Enable retries and run test_post_find_value_error. _service.enable_retries() self.test_post_find_value_error() # Disable retries and run test_post_find_value_error. _service.disable_retries() self.test_post_find_value_error() class TestPostFindAsStream(): """ Test Class for post_find_as_stream """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_find_as_stream_all_params(self): """ post_find_as_stream() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_find') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' selector = {} bookmark = 'testString' conflicts = True execution_stats = True fields = ['_id', 'type', 'name', 'email'] limit = 3 skip = 0 sort = [{}] stable = True update = 'true' use_index = ['testString'] r = 1 # Invoke method response = _service.post_find_as_stream( db, selector, bookmark=bookmark, conflicts=conflicts, execution_stats=execution_stats, fields=fields, limit=limit, skip=skip, sort=sort, stable=stable, update=update, use_index=use_index, r=r, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['selector'] == {} assert req_body['bookmark'] == 'testString' assert req_body['conflicts'] == True assert req_body['execution_stats'] == True assert req_body['fields'] == ['_id', 'type', 'name', 'email'] assert req_body['limit'] == 3 assert req_body['skip'] == 0 assert req_body['sort'] == [{}] assert req_body['stable'] == True assert req_body['update'] == 'true' assert req_body['use_index'] == ['testString'] assert req_body['r'] == 1 # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_find_as_stream_all_params_with_retries(self): # Enable retries and run test_post_find_as_stream_all_params. _service.enable_retries() self.test_post_find_as_stream_all_params() # Disable retries and run test_post_find_as_stream_all_params. _service.disable_retries() self.test_post_find_as_stream_all_params() @responses.activate def test_post_find_as_stream_value_error(self): """ test_post_find_as_stream_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_find') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' selector = {} bookmark = 'testString' conflicts = True execution_stats = True fields = ['_id', 'type', 'name', 'email'] limit = 3 skip = 0 sort = [{}] stable = True update = 'true' use_index = ['testString'] r = 1 # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "selector": selector, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_find_as_stream(**req_copy) def test_post_find_as_stream_value_error_with_retries(self): # Enable retries and run test_post_find_as_stream_value_error. _service.enable_retries() self.test_post_find_as_stream_value_error() # Disable retries and run test_post_find_as_stream_value_error. _service.disable_retries() self.test_post_find_as_stream_value_error() class TestGetIndexesInformation(): """ Test Class for get_indexes_information """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_indexes_information_all_params(self): """ get_indexes_information() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_index') mock_response = '{"total_rows": 0, "indexes": [{"ddoc": "ddoc", "def": {"default_analyzer": {"name": "classic", "stopwords": ["stopwords"]}, "default_field": {"analyzer": {"name": "classic", "stopwords": ["stopwords"]}, "enabled": true}, "fields": [{"name": "name", "type": "boolean"}], "index_array_lengths": true, "partial_filter_selector": {"mapKey": "anyValue"}}, "name": "name", "type": "json"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' # Invoke method response = _service.get_indexes_information( db, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_indexes_information_all_params_with_retries(self): # Enable retries and run test_get_indexes_information_all_params. _service.enable_retries() self.test_get_indexes_information_all_params() # Disable retries and run test_get_indexes_information_all_params. _service.disable_retries() self.test_get_indexes_information_all_params() @responses.activate def test_get_indexes_information_value_error(self): """ test_get_indexes_information_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_index') mock_response = '{"total_rows": 0, "indexes": [{"ddoc": "ddoc", "def": {"default_analyzer": {"name": "classic", "stopwords": ["stopwords"]}, "default_field": {"analyzer": {"name": "classic", "stopwords": ["stopwords"]}, "enabled": true}, "fields": [{"name": "name", "type": "boolean"}], "index_array_lengths": true, "partial_filter_selector": {"mapKey": "anyValue"}}, "name": "name", "type": "json"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_indexes_information(**req_copy) def test_get_indexes_information_value_error_with_retries(self): # Enable retries and run test_get_indexes_information_value_error. _service.enable_retries() self.test_get_indexes_information_value_error() # Disable retries and run test_get_indexes_information_value_error. _service.disable_retries() self.test_get_indexes_information_value_error() class TestPostIndex(): """ Test Class for post_index """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_index_all_params(self): """ post_index() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_index') mock_response = '{"id": "id", "name": "name", "result": "created"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a Analyzer model analyzer_model = {} analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] # Construct a dict representation of a IndexTextOperatorDefaultField model index_text_operator_default_field_model = {} index_text_operator_default_field_model['analyzer'] = analyzer_model index_text_operator_default_field_model['enabled'] = True # Construct a dict representation of a IndexField model index_field_model = {} index_field_model['name'] = 'testString' index_field_model['type'] = 'boolean' index_field_model['foo'] = 'asc' # Construct a dict representation of a IndexDefinition model index_definition_model = {} index_definition_model['default_analyzer'] = analyzer_model index_definition_model['default_field'] = index_text_operator_default_field_model index_definition_model['fields'] = [index_field_model] index_definition_model['index_array_lengths'] = True index_definition_model['partial_filter_selector'] = {} # Set up parameter values db = 'testString' index = index_definition_model ddoc = 'testString' def_ = index_definition_model name = 'testString' partitioned = True type = 'json' # Invoke method response = _service.post_index( db, index, ddoc=ddoc, def_=def_, name=name, partitioned=partitioned, type=type, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['index'] == index_definition_model assert req_body['ddoc'] == 'testString' assert req_body['def'] == index_definition_model assert req_body['name'] == 'testString' assert req_body['partitioned'] == True assert req_body['type'] == 'json' def test_post_index_all_params_with_retries(self): # Enable retries and run test_post_index_all_params. _service.enable_retries() self.test_post_index_all_params() # Disable retries and run test_post_index_all_params. _service.disable_retries() self.test_post_index_all_params() @responses.activate def test_post_index_value_error(self): """ test_post_index_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_index') mock_response = '{"id": "id", "name": "name", "result": "created"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a Analyzer model analyzer_model = {} analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] # Construct a dict representation of a IndexTextOperatorDefaultField model index_text_operator_default_field_model = {} index_text_operator_default_field_model['analyzer'] = analyzer_model index_text_operator_default_field_model['enabled'] = True # Construct a dict representation of a IndexField model index_field_model = {} index_field_model['name'] = 'testString' index_field_model['type'] = 'boolean' index_field_model['foo'] = 'asc' # Construct a dict representation of a IndexDefinition model index_definition_model = {} index_definition_model['default_analyzer'] = analyzer_model index_definition_model['default_field'] = index_text_operator_default_field_model index_definition_model['fields'] = [index_field_model] index_definition_model['index_array_lengths'] = True index_definition_model['partial_filter_selector'] = {} # Set up parameter values db = 'testString' index = index_definition_model ddoc = 'testString' def_ = index_definition_model name = 'testString' partitioned = True type = 'json' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "index": index, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_index(**req_copy) def test_post_index_value_error_with_retries(self): # Enable retries and run test_post_index_value_error. _service.enable_retries() self.test_post_index_value_error() # Disable retries and run test_post_index_value_error. _service.disable_retries() self.test_post_index_value_error() class TestDeleteIndex(): """ Test Class for delete_index """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_delete_index_all_params(self): """ delete_index() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_index/_design/testString/json/testString') mock_response = '{"ok": true}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' type = 'json' index = 'testString' # Invoke method response = _service.delete_index( db, ddoc, type, index, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_delete_index_all_params_with_retries(self): # Enable retries and run test_delete_index_all_params. _service.enable_retries() self.test_delete_index_all_params() # Disable retries and run test_delete_index_all_params. _service.disable_retries() self.test_delete_index_all_params() @responses.activate def test_delete_index_value_error(self): """ test_delete_index_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_index/_design/testString/json/testString') mock_response = '{"ok": true}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' type = 'json' index = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, "type": type, "index": index, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_index(**req_copy) def test_delete_index_value_error_with_retries(self): # Enable retries and run test_delete_index_value_error. _service.enable_retries() self.test_delete_index_value_error() # Disable retries and run test_delete_index_value_error. _service.disable_retries() self.test_delete_index_value_error() # endregion ############################################################################## # End of Service: Queries ############################################################################## ############################################################################## # Start of Service: Searches ############################################################################## # region class TestNewInstance(): """ Test Class for new_instance """ def test_new_instance(self): """ new_instance() """ os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): """ new_instance_without_authenticator() """ with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestPostSearchAnalyze(): """ Test Class for post_search_analyze """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_search_analyze_all_params(self): """ post_search_analyze() """ # Set up mock url = self.preprocess_url(_base_url + '/_search_analyze') mock_response = '{"tokens": ["tokens"]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values analyzer = 'arabic' text = 'testString' # Invoke method response = _service.post_search_analyze( analyzer, text, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['analyzer'] == 'arabic' assert req_body['text'] == 'testString' def test_post_search_analyze_all_params_with_retries(self): # Enable retries and run test_post_search_analyze_all_params. _service.enable_retries() self.test_post_search_analyze_all_params() # Disable retries and run test_post_search_analyze_all_params. _service.disable_retries() self.test_post_search_analyze_all_params() @responses.activate def test_post_search_analyze_value_error(self): """ test_post_search_analyze_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/_search_analyze') mock_response = '{"tokens": ["tokens"]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values analyzer = 'arabic' text = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "analyzer": analyzer, "text": text, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_search_analyze(**req_copy) def test_post_search_analyze_value_error_with_retries(self): # Enable retries and run test_post_search_analyze_value_error. _service.enable_retries() self.test_post_search_analyze_value_error() # Disable retries and run test_post_search_analyze_value_error. _service.disable_retries() self.test_post_search_analyze_value_error() class TestPostSearch(): """ Test Class for post_search """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_search_all_params(self): """ post_search() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_search/testString') mock_response = '{"total_rows": 0, "bookmark": "bookmark", "by": "by", "counts": {"mapKey": {"mapKey": 0}}, "ranges": {"mapKey": {"mapKey": 0}}, "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "fields": {"mapKey": "anyValue"}, "highlights": {"mapKey": ["inner"]}, "id": "id"}], "groups": [{"total_rows": 0, "bookmark": "bookmark", "by": "by", "counts": {"mapKey": {"mapKey": 0}}, "ranges": {"mapKey": {"mapKey": 0}}, "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "fields": {"mapKey": "anyValue"}, "highlights": {"mapKey": ["inner"]}, "id": "id"}]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' query = 'testString' bookmark = 'testString' highlight_fields = ['testString'] highlight_number = 1 highlight_post_tag = '</em>' highlight_pre_tag = '<em>' highlight_size = 1 include_docs = False include_fields = ['testString'] limit = 0 sort = ['testString'] stale = 'ok' counts = ['testString'] drilldown = [['testString']] group_field = 'testString' group_limit = 1 group_sort = ['testString'] ranges = {} # Invoke method response = _service.post_search( db, ddoc, index, query, bookmark=bookmark, highlight_fields=highlight_fields, highlight_number=highlight_number, highlight_post_tag=highlight_post_tag, highlight_pre_tag=highlight_pre_tag, highlight_size=highlight_size, include_docs=include_docs, include_fields=include_fields, limit=limit, sort=sort, stale=stale, counts=counts, drilldown=drilldown, group_field=group_field, group_limit=group_limit, group_sort=group_sort, ranges=ranges, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['query'] == 'testString' assert req_body['bookmark'] == 'testString' assert req_body['highlight_fields'] == ['testString'] assert req_body['highlight_number'] == 1 assert req_body['highlight_post_tag'] == '</em>' assert req_body['highlight_pre_tag'] == '<em>' assert req_body['highlight_size'] == 1 assert req_body['include_docs'] == False assert req_body['include_fields'] == ['testString'] assert req_body['limit'] == 0 assert req_body['sort'] == ['testString'] assert req_body['stale'] == 'ok' assert req_body['counts'] == ['testString'] assert req_body['drilldown'] == [['testString']] assert req_body['group_field'] == 'testString' assert req_body['group_limit'] == 1 assert req_body['group_sort'] == ['testString'] assert req_body['ranges'] == {} def test_post_search_all_params_with_retries(self): # Enable retries and run test_post_search_all_params. _service.enable_retries() self.test_post_search_all_params() # Disable retries and run test_post_search_all_params. _service.disable_retries() self.test_post_search_all_params() @responses.activate def test_post_search_value_error(self): """ test_post_search_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_search/testString') mock_response = '{"total_rows": 0, "bookmark": "bookmark", "by": "by", "counts": {"mapKey": {"mapKey": 0}}, "ranges": {"mapKey": {"mapKey": 0}}, "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "fields": {"mapKey": "anyValue"}, "highlights": {"mapKey": ["inner"]}, "id": "id"}], "groups": [{"total_rows": 0, "bookmark": "bookmark", "by": "by", "counts": {"mapKey": {"mapKey": 0}}, "ranges": {"mapKey": {"mapKey": 0}}, "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "fields": {"mapKey": "anyValue"}, "highlights": {"mapKey": ["inner"]}, "id": "id"}]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' query = 'testString' bookmark = 'testString' highlight_fields = ['testString'] highlight_number = 1 highlight_post_tag = '</em>' highlight_pre_tag = '<em>' highlight_size = 1 include_docs = False include_fields = ['testString'] limit = 0 sort = ['testString'] stale = 'ok' counts = ['testString'] drilldown = [['testString']] group_field = 'testString' group_limit = 1 group_sort = ['testString'] ranges = {} # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, "index": index, "query": query, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_search(**req_copy) def test_post_search_value_error_with_retries(self): # Enable retries and run test_post_search_value_error. _service.enable_retries() self.test_post_search_value_error() # Disable retries and run test_post_search_value_error. _service.disable_retries() self.test_post_search_value_error() class TestPostSearchAsStream(): """ Test Class for post_search_as_stream """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_search_as_stream_all_params(self): """ post_search_as_stream() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_search/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' query = 'testString' bookmark = 'testString' highlight_fields = ['testString'] highlight_number = 1 highlight_post_tag = '</em>' highlight_pre_tag = '<em>' highlight_size = 1 include_docs = False include_fields = ['testString'] limit = 3 sort = ['testString'] stale = 'ok' counts = ['testString'] drilldown = [['testString']] group_field = 'testString' group_limit = 1 group_sort = ['testString'] ranges = {} # Invoke method response = _service.post_search_as_stream( db, ddoc, index, query, bookmark=bookmark, highlight_fields=highlight_fields, highlight_number=highlight_number, highlight_post_tag=highlight_post_tag, highlight_pre_tag=highlight_pre_tag, highlight_size=highlight_size, include_docs=include_docs, include_fields=include_fields, limit=limit, sort=sort, stale=stale, counts=counts, drilldown=drilldown, group_field=group_field, group_limit=group_limit, group_sort=group_sort, ranges=ranges, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['query'] == 'testString' assert req_body['bookmark'] == 'testString' assert req_body['highlight_fields'] == ['testString'] assert req_body['highlight_number'] == 1 assert req_body['highlight_post_tag'] == '</em>' assert req_body['highlight_pre_tag'] == '<em>' assert req_body['highlight_size'] == 1 assert req_body['include_docs'] == False assert req_body['include_fields'] == ['testString'] assert req_body['limit'] == 3 assert req_body['sort'] == ['testString'] assert req_body['stale'] == 'ok' assert req_body['counts'] == ['testString'] assert req_body['drilldown'] == [['testString']] assert req_body['group_field'] == 'testString' assert req_body['group_limit'] == 1 assert req_body['group_sort'] == ['testString'] assert req_body['ranges'] == {} # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_search_as_stream_all_params_with_retries(self): # Enable retries and run test_post_search_as_stream_all_params. _service.enable_retries() self.test_post_search_as_stream_all_params() # Disable retries and run test_post_search_as_stream_all_params. _service.disable_retries() self.test_post_search_as_stream_all_params() @responses.activate def test_post_search_as_stream_value_error(self): """ test_post_search_as_stream_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_search/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' query = 'testString' bookmark = 'testString' highlight_fields = ['testString'] highlight_number = 1 highlight_post_tag = '</em>' highlight_pre_tag = '<em>' highlight_size = 1 include_docs = False include_fields = ['testString'] limit = 3 sort = ['testString'] stale = 'ok' counts = ['testString'] drilldown = [['testString']] group_field = 'testString' group_limit = 1 group_sort = ['testString'] ranges = {} # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, "index": index, "query": query, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_search_as_stream(**req_copy) def test_post_search_as_stream_value_error_with_retries(self): # Enable retries and run test_post_search_as_stream_value_error. _service.enable_retries() self.test_post_search_as_stream_value_error() # Disable retries and run test_post_search_as_stream_value_error. _service.disable_retries() self.test_post_search_as_stream_value_error() class TestGetSearchInfo(): """ Test Class for get_search_info """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_search_info_all_params(self): """ get_search_info() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_search_info/testString') mock_response = '{"name": "name", "search_index": {"committed_seq": 13, "disk_size": 0, "doc_count": 0, "doc_del_count": 0, "pending_seq": 11}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' # Invoke method response = _service.get_search_info( db, ddoc, index, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_search_info_all_params_with_retries(self): # Enable retries and run test_get_search_info_all_params. _service.enable_retries() self.test_get_search_info_all_params() # Disable retries and run test_get_search_info_all_params. _service.disable_retries() self.test_get_search_info_all_params() @responses.activate def test_get_search_info_value_error(self): """ test_get_search_info_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_search_info/testString') mock_response = '{"name": "name", "search_index": {"committed_seq": 13, "disk_size": 0, "doc_count": 0, "doc_del_count": 0, "pending_seq": 11}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, "index": index, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_search_info(**req_copy) def test_get_search_info_value_error_with_retries(self): # Enable retries and run test_get_search_info_value_error. _service.enable_retries() self.test_get_search_info_value_error() # Disable retries and run test_get_search_info_value_error. _service.disable_retries() self.test_get_search_info_value_error() # endregion ############################################################################## # End of Service: Searches ############################################################################## ############################################################################## # Start of Service: Geospatial ############################################################################## # region class TestNewInstance(): """ Test Class for new_instance """ def test_new_instance(self): """ new_instance() """ os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): """ new_instance_without_authenticator() """ with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestGetGeo(): """ Test Class for get_geo """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_geo_all_params(self): """ get_geo() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_geo/testString') mock_response = '{"bookmark": "bookmark", "features": [{"_id": "id", "_rev": "rev", "bbox": [4], "geometry": {"type": "Point", "coordinates": ["anyValue"]}, "properties": {"mapKey": "anyValue"}, "type": "Feature"}], "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "geometry": {"type": "Point", "coordinates": ["anyValue"]}, "id": "id", "rev": "rev"}], "type": "FeatureCollection"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' bbox = 'testString' bookmark = 'testString' format = 'view' g = 'testString' include_docs = False lat = -90 limit = 0 lon = -180 nearest = False radius = 0 rangex = 0 rangey = 0 relation = 'intersects' skip = 0 stale = 'ok' # Invoke method response = _service.get_geo( db, ddoc, index, bbox=bbox, bookmark=bookmark, format=format, g=g, include_docs=include_docs, lat=lat, limit=limit, lon=lon, nearest=nearest, radius=radius, rangex=rangex, rangey=rangey, relation=relation, skip=skip, stale=stale, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'bbox={}'.format(bbox) in query_string assert 'bookmark={}'.format(bookmark) in query_string assert 'format={}'.format(format) in query_string assert 'g={}'.format(g) in query_string assert 'include_docs={}'.format('true' if include_docs else 'false') in query_string assert 'lat={}'.format(lat) in query_string assert 'limit={}'.format(limit) in query_string assert 'lon={}'.format(lon) in query_string assert 'nearest={}'.format('true' if nearest else 'false') in query_string assert 'radius={}'.format(radius) in query_string assert 'rangex={}'.format(rangex) in query_string assert 'rangey={}'.format(rangey) in query_string assert 'relation={}'.format(relation) in query_string assert 'skip={}'.format(skip) in query_string assert 'stale={}'.format(stale) in query_string def test_get_geo_all_params_with_retries(self): # Enable retries and run test_get_geo_all_params. _service.enable_retries() self.test_get_geo_all_params() # Disable retries and run test_get_geo_all_params. _service.disable_retries() self.test_get_geo_all_params() @responses.activate def test_get_geo_required_params(self): """ test_get_geo_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_geo/testString') mock_response = '{"bookmark": "bookmark", "features": [{"_id": "id", "_rev": "rev", "bbox": [4], "geometry": {"type": "Point", "coordinates": ["anyValue"]}, "properties": {"mapKey": "anyValue"}, "type": "Feature"}], "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "geometry": {"type": "Point", "coordinates": ["anyValue"]}, "id": "id", "rev": "rev"}], "type": "FeatureCollection"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' # Invoke method response = _service.get_geo( db, ddoc, index, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_geo_required_params_with_retries(self): # Enable retries and run test_get_geo_required_params. _service.enable_retries() self.test_get_geo_required_params() # Disable retries and run test_get_geo_required_params. _service.disable_retries() self.test_get_geo_required_params() @responses.activate def test_get_geo_value_error(self): """ test_get_geo_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_geo/testString') mock_response = '{"bookmark": "bookmark", "features": [{"_id": "id", "_rev": "rev", "bbox": [4], "geometry": {"type": "Point", "coordinates": ["anyValue"]}, "properties": {"mapKey": "anyValue"}, "type": "Feature"}], "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "geometry": {"type": "Point", "coordinates": ["anyValue"]}, "id": "id", "rev": "rev"}], "type": "FeatureCollection"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, "index": index, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_geo(**req_copy) def test_get_geo_value_error_with_retries(self): # Enable retries and run test_get_geo_value_error. _service.enable_retries() self.test_get_geo_value_error() # Disable retries and run test_get_geo_value_error. _service.disable_retries() self.test_get_geo_value_error() class TestGetGeoAsStream(): """ Test Class for get_geo_as_stream """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_geo_as_stream_all_params(self): """ get_geo_as_stream() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_geo/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' bbox = 'testString' bookmark = 'testString' format = 'view' g = 'testString' include_docs = False lat = -90 limit = 0 lon = -180 nearest = False radius = 0 rangex = 0 rangey = 0 relation = 'intersects' skip = 0 stale = 'ok' # Invoke method response = _service.get_geo_as_stream( db, ddoc, index, bbox=bbox, bookmark=bookmark, format=format, g=g, include_docs=include_docs, lat=lat, limit=limit, lon=lon, nearest=nearest, radius=radius, rangex=rangex, rangey=rangey, relation=relation, skip=skip, stale=stale, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'bbox={}'.format(bbox) in query_string assert 'bookmark={}'.format(bookmark) in query_string assert 'format={}'.format(format) in query_string assert 'g={}'.format(g) in query_string assert 'include_docs={}'.format('true' if include_docs else 'false') in query_string assert 'lat={}'.format(lat) in query_string assert 'limit={}'.format(limit) in query_string assert 'lon={}'.format(lon) in query_string assert 'nearest={}'.format('true' if nearest else 'false') in query_string assert 'radius={}'.format(radius) in query_string assert 'rangex={}'.format(rangex) in query_string assert 'rangey={}'.format(rangey) in query_string assert 'relation={}'.format(relation) in query_string assert 'skip={}'.format(skip) in query_string assert 'stale={}'.format(stale) in query_string # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_get_geo_as_stream_all_params_with_retries(self): # Enable retries and run test_get_geo_as_stream_all_params. _service.enable_retries() self.test_get_geo_as_stream_all_params() # Disable retries and run test_get_geo_as_stream_all_params. _service.disable_retries() self.test_get_geo_as_stream_all_params() @responses.activate def test_get_geo_as_stream_required_params(self): """ test_get_geo_as_stream_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_geo/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' # Invoke method response = _service.get_geo_as_stream( db, ddoc, index, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_get_geo_as_stream_required_params_with_retries(self): # Enable retries and run test_get_geo_as_stream_required_params. _service.enable_retries() self.test_get_geo_as_stream_required_params() # Disable retries and run test_get_geo_as_stream_required_params. _service.disable_retries() self.test_get_geo_as_stream_required_params() @responses.activate def test_get_geo_as_stream_value_error(self): """ test_get_geo_as_stream_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_geo/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, "index": index, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_geo_as_stream(**req_copy) def test_get_geo_as_stream_value_error_with_retries(self): # Enable retries and run test_get_geo_as_stream_value_error. _service.enable_retries() self.test_get_geo_as_stream_value_error() # Disable retries and run test_get_geo_as_stream_value_error. _service.disable_retries() self.test_get_geo_as_stream_value_error() class TestPostGeoCleanup(): """ Test Class for post_geo_cleanup """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_geo_cleanup_all_params(self): """ post_geo_cleanup() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_geo_cleanup') mock_response = '{"ok": true}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=202) # Set up parameter values db = 'testString' # Invoke method response = _service.post_geo_cleanup( db, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 202 def test_post_geo_cleanup_all_params_with_retries(self): # Enable retries and run test_post_geo_cleanup_all_params. _service.enable_retries() self.test_post_geo_cleanup_all_params() # Disable retries and run test_post_geo_cleanup_all_params. _service.disable_retries() self.test_post_geo_cleanup_all_params() @responses.activate def test_post_geo_cleanup_value_error(self): """ test_post_geo_cleanup_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_geo_cleanup') mock_response = '{"ok": true}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=202) # Set up parameter values db = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_geo_cleanup(**req_copy) def test_post_geo_cleanup_value_error_with_retries(self): # Enable retries and run test_post_geo_cleanup_value_error. _service.enable_retries() self.test_post_geo_cleanup_value_error() # Disable retries and run test_post_geo_cleanup_value_error. _service.disable_retries() self.test_post_geo_cleanup_value_error() class TestGetGeoIndexInformation(): """ Test Class for get_geo_index_information """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_geo_index_information_all_params(self): """ get_geo_index_information() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_geo_info/testString') mock_response = '{"geo_index": {"data_size": 0, "disk_size": 0, "doc_count": 0}, "name": "name"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' # Invoke method response = _service.get_geo_index_information( db, ddoc, index, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_geo_index_information_all_params_with_retries(self): # Enable retries and run test_get_geo_index_information_all_params. _service.enable_retries() self.test_get_geo_index_information_all_params() # Disable retries and run test_get_geo_index_information_all_params. _service.disable_retries() self.test_get_geo_index_information_all_params() @responses.activate def test_get_geo_index_information_value_error(self): """ test_get_geo_index_information_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_geo_info/testString') mock_response = '{"geo_index": {"data_size": 0, "disk_size": 0, "doc_count": 0}, "name": "name"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, "index": index, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_geo_index_information(**req_copy) def test_get_geo_index_information_value_error_with_retries(self): # Enable retries and run test_get_geo_index_information_value_error. _service.enable_retries() self.test_get_geo_index_information_value_error() # Disable retries and run test_get_geo_index_information_value_error. _service.disable_retries() self.test_get_geo_index_information_value_error() # endregion ############################################################################## # End of Service: Geospatial ############################################################################## ############################################################################## # Start of Service: Replication ############################################################################## # region class TestNewInstance(): """ Test Class for new_instance """ def test_new_instance(self): """ new_instance() """ os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): """ new_instance_without_authenticator() """ with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestHeadReplicationDocument(): """ Test Class for head_replication_document """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_head_replication_document_all_params(self): """ head_replication_document() """ # Set up mock url = self.preprocess_url(_base_url + '/_replicator/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values doc_id = 'testString' if_none_match = 'testString' # Invoke method response = _service.head_replication_document( doc_id, if_none_match=if_none_match, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_head_replication_document_all_params_with_retries(self): # Enable retries and run test_head_replication_document_all_params. _service.enable_retries() self.test_head_replication_document_all_params() # Disable retries and run test_head_replication_document_all_params. _service.disable_retries() self.test_head_replication_document_all_params() @responses.activate def test_head_replication_document_required_params(self): """ test_head_replication_document_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/_replicator/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values doc_id = 'testString' # Invoke method response = _service.head_replication_document( doc_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_head_replication_document_required_params_with_retries(self): # Enable retries and run test_head_replication_document_required_params. _service.enable_retries() self.test_head_replication_document_required_params() # Disable retries and run test_head_replication_document_required_params. _service.disable_retries() self.test_head_replication_document_required_params() @responses.activate def test_head_replication_document_value_error(self): """ test_head_replication_document_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/_replicator/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.head_replication_document(**req_copy) def test_head_replication_document_value_error_with_retries(self): # Enable retries and run test_head_replication_document_value_error. _service.enable_retries() self.test_head_replication_document_value_error() # Disable retries and run test_head_replication_document_value_error. _service.disable_retries() self.test_head_replication_document_value_error() class TestHeadSchedulerDocument(): """ Test Class for head_scheduler_document """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_head_scheduler_document_all_params(self): """ head_scheduler_document() """ # Set up mock url = self.preprocess_url(_base_url + '/_scheduler/docs/_replicator/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values doc_id = 'testString' # Invoke method response = _service.head_scheduler_document( doc_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_head_scheduler_document_all_params_with_retries(self): # Enable retries and run test_head_scheduler_document_all_params. _service.enable_retries() self.test_head_scheduler_document_all_params() # Disable retries and run test_head_scheduler_document_all_params. _service.disable_retries() self.test_head_scheduler_document_all_params() @responses.activate def test_head_scheduler_document_value_error(self): """ test_head_scheduler_document_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/_scheduler/docs/_replicator/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.head_scheduler_document(**req_copy) def test_head_scheduler_document_value_error_with_retries(self): # Enable retries and run test_head_scheduler_document_value_error. _service.enable_retries() self.test_head_scheduler_document_value_error() # Disable retries and run test_head_scheduler_document_value_error. _service.disable_retries() self.test_head_scheduler_document_value_error() class TestHeadSchedulerJob(): """ Test Class for head_scheduler_job """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_head_scheduler_job_all_params(self): """ head_scheduler_job() """ # Set up mock url = self.preprocess_url(_base_url + '/_scheduler/jobs/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values job_id = 'testString' # Invoke method response = _service.head_scheduler_job( job_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_head_scheduler_job_all_params_with_retries(self): # Enable retries and run test_head_scheduler_job_all_params. _service.enable_retries() self.test_head_scheduler_job_all_params() # Disable retries and run test_head_scheduler_job_all_params. _service.disable_retries() self.test_head_scheduler_job_all_params() @responses.activate def test_head_scheduler_job_value_error(self): """ test_head_scheduler_job_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/_scheduler/jobs/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values job_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "job_id": job_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.head_scheduler_job(**req_copy) def test_head_scheduler_job_value_error_with_retries(self): # Enable retries and run test_head_scheduler_job_value_error. _service.enable_retries() self.test_head_scheduler_job_value_error() # Disable retries and run test_head_scheduler_job_value_error. _service.disable_retries() self.test_head_scheduler_job_value_error() class TestDeleteReplicationDocument(): """ Test Class for delete_replication_document """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_delete_replication_document_all_params(self): """ delete_replication_document() """ # Set up mock url = self.preprocess_url(_base_url + '/_replicator/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=201) # Set up parameter values doc_id = 'testString' if_match = 'testString' batch = 'ok' rev = 'testString' # Invoke method response = _service.delete_replication_document( doc_id, if_match=if_match, batch=batch, rev=rev, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'batch={}'.format(batch) in query_string assert 'rev={}'.format(rev) in query_string def test_delete_replication_document_all_params_with_retries(self): # Enable retries and run test_delete_replication_document_all_params. _service.enable_retries() self.test_delete_replication_document_all_params() # Disable retries and run test_delete_replication_document_all_params. _service.disable_retries() self.test_delete_replication_document_all_params() @responses.activate def test_delete_replication_document_required_params(self): """ test_delete_replication_document_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/_replicator/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=201) # Set up parameter values doc_id = 'testString' # Invoke method response = _service.delete_replication_document( doc_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 def test_delete_replication_document_required_params_with_retries(self): # Enable retries and run test_delete_replication_document_required_params. _service.enable_retries() self.test_delete_replication_document_required_params() # Disable retries and run test_delete_replication_document_required_params. _service.disable_retries() self.test_delete_replication_document_required_params() @responses.activate def test_delete_replication_document_value_error(self): """ test_delete_replication_document_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/_replicator/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=201) # Set up parameter values doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_replication_document(**req_copy) def test_delete_replication_document_value_error_with_retries(self): # Enable retries and run test_delete_replication_document_value_error. _service.enable_retries() self.test_delete_replication_document_value_error() # Disable retries and run test_delete_replication_document_value_error. _service.disable_retries() self.test_delete_replication_document_value_error() class TestGetReplicationDocument(): """ Test Class for get_replication_document """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_replication_document_all_params(self): """ get_replication_document() """ # Set up mock url = self.preprocess_url(_base_url + '/_replicator/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}], "cancel": true, "checkpoint_interval": 0, "connection_timeout": 0, "continuous": false, "create_target": false, "create_target_params": {"n": 1, "partitioned": false, "q": 1}, "doc_ids": ["doc_ids"], "filter": "filter", "http_connections": 1, "query_params": {"mapKey": "inner"}, "retries_per_request": 0, "selector": {"mapKey": "anyValue"}, "since_seq": "since_seq", "socket_options": "socket_options", "source": {"auth": {"basic": {"password": "password", "username": "username"}, "iam": {"api_key": "api_key"}}, "headers": {"mapKey": "inner"}, "url": "url"}, "source_proxy": "source_proxy", "target": {"auth": {"basic": {"password": "password", "username": "username"}, "iam": {"api_key": "api_key"}}, "headers": {"mapKey": "inner"}, "url": "url"}, "target_proxy": "target_proxy", "use_checkpoints": true, "user_ctx": {"db": "db", "name": "name", "roles": ["_reader"]}, "worker_batch_size": 1, "worker_processes": 1}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values doc_id = 'testString' if_none_match = 'testString' attachments = False att_encoding_info = False conflicts = False deleted_conflicts = False latest = False local_seq = False meta = False rev = 'testString' revs = False revs_info = False # Invoke method response = _service.get_replication_document( doc_id, if_none_match=if_none_match, attachments=attachments, att_encoding_info=att_encoding_info, conflicts=conflicts, deleted_conflicts=deleted_conflicts, latest=latest, local_seq=local_seq, meta=meta, rev=rev, revs=revs, revs_info=revs_info, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'conflicts={}'.format('true' if conflicts else 'false') in query_string assert 'deleted_conflicts={}'.format('true' if deleted_conflicts else 'false') in query_string assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'local_seq={}'.format('true' if local_seq else 'false') in query_string assert 'meta={}'.format('true' if meta else 'false') in query_string assert 'rev={}'.format(rev) in query_string assert 'revs={}'.format('true' if revs else 'false') in query_string assert 'revs_info={}'.format('true' if revs_info else 'false') in query_string def test_get_replication_document_all_params_with_retries(self): # Enable retries and run test_get_replication_document_all_params. _service.enable_retries() self.test_get_replication_document_all_params() # Disable retries and run test_get_replication_document_all_params. _service.disable_retries() self.test_get_replication_document_all_params() @responses.activate def test_get_replication_document_required_params(self): """ test_get_replication_document_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/_replicator/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}], "cancel": true, "checkpoint_interval": 0, "connection_timeout": 0, "continuous": false, "create_target": false, "create_target_params": {"n": 1, "partitioned": false, "q": 1}, "doc_ids": ["doc_ids"], "filter": "filter", "http_connections": 1, "query_params": {"mapKey": "inner"}, "retries_per_request": 0, "selector": {"mapKey": "anyValue"}, "since_seq": "since_seq", "socket_options": "socket_options", "source": {"auth": {"basic": {"password": "password", "username": "username"}, "iam": {"api_key": "api_key"}}, "headers": {"mapKey": "inner"}, "url": "url"}, "source_proxy": "source_proxy", "target": {"auth": {"basic": {"password": "password", "username": "username"}, "iam": {"api_key": "api_key"}}, "headers": {"mapKey": "inner"}, "url": "url"}, "target_proxy": "target_proxy", "use_checkpoints": true, "user_ctx": {"db": "db", "name": "name", "roles": ["_reader"]}, "worker_batch_size": 1, "worker_processes": 1}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values doc_id = 'testString' # Invoke method response = _service.get_replication_document( doc_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_replication_document_required_params_with_retries(self): # Enable retries and run test_get_replication_document_required_params. _service.enable_retries() self.test_get_replication_document_required_params() # Disable retries and run test_get_replication_document_required_params. _service.disable_retries() self.test_get_replication_document_required_params() @responses.activate def test_get_replication_document_value_error(self): """ test_get_replication_document_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/_replicator/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}], "cancel": true, "checkpoint_interval": 0, "connection_timeout": 0, "continuous": false, "create_target": false, "create_target_params": {"n": 1, "partitioned": false, "q": 1}, "doc_ids": ["doc_ids"], "filter": "filter", "http_connections": 1, "query_params": {"mapKey": "inner"}, "retries_per_request": 0, "selector": {"mapKey": "anyValue"}, "since_seq": "since_seq", "socket_options": "socket_options", "source": {"auth": {"basic": {"password": "password", "username": "username"}, "iam": {"api_key": "api_key"}}, "headers": {"mapKey": "inner"}, "url": "url"}, "source_proxy": "source_proxy", "target": {"auth": {"basic": {"password": "password", "username": "username"}, "iam": {"api_key": "api_key"}}, "headers": {"mapKey": "inner"}, "url": "url"}, "target_proxy": "target_proxy", "use_checkpoints": true, "user_ctx": {"db": "db", "name": "name", "roles": ["_reader"]}, "worker_batch_size": 1, "worker_processes": 1}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_replication_document(**req_copy) def test_get_replication_document_value_error_with_retries(self): # Enable retries and run test_get_replication_document_value_error. _service.enable_retries() self.test_get_replication_document_value_error() # Disable retries and run test_get_replication_document_value_error. _service.disable_retries() self.test_get_replication_document_value_error() class TestPutReplicationDocument(): """ Test Class for put_replication_document """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_put_replication_document_all_params(self): """ put_replication_document() """ # Set up mock url = self.preprocess_url(_base_url + '/_replicator/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a ReplicationCreateTargetParameters model replication_create_target_parameters_model = {} replication_create_target_parameters_model['n'] = 1 replication_create_target_parameters_model['partitioned'] = False replication_create_target_parameters_model['q'] = 1 # Construct a dict representation of a ReplicationDatabaseAuthBasic model replication_database_auth_basic_model = {} replication_database_auth_basic_model['password'] = 'testString' replication_database_auth_basic_model['username'] = 'testString' # Construct a dict representation of a ReplicationDatabaseAuthIam model replication_database_auth_iam_model = {} replication_database_auth_iam_model['api_key'] = 'testString' # Construct a dict representation of a ReplicationDatabaseAuth model replication_database_auth_model = {} replication_database_auth_model['basic'] = replication_database_auth_basic_model replication_database_auth_model['iam'] = replication_database_auth_iam_model # Construct a dict representation of a ReplicationDatabase model replication_database_model = {} replication_database_model['auth'] = replication_database_auth_model replication_database_model['headers'] = {} replication_database_model['url'] = 'testString' # Construct a dict representation of a UserContext model user_context_model = {} user_context_model['db'] = 'testString' user_context_model['name'] = 'testString' user_context_model['roles'] = ['_reader'] # Construct a dict representation of a ReplicationDocument model replication_document_model = {} replication_document_model['_attachments'] = {} replication_document_model['_conflicts'] = ['testString'] replication_document_model['_deleted'] = True replication_document_model['_deleted_conflicts'] = ['testString'] replication_document_model['_id'] = 'testString' replication_document_model['_local_seq'] = 'testString' replication_document_model['_rev'] = 'testString' replication_document_model['_revisions'] = revisions_model replication_document_model['_revs_info'] = [document_revision_status_model] replication_document_model['cancel'] = True replication_document_model['checkpoint_interval'] = 0 replication_document_model['connection_timeout'] = 0 replication_document_model['continuous'] = False replication_document_model['create_target'] = False replication_document_model['create_target_params'] = replication_create_target_parameters_model replication_document_model['doc_ids'] = ['testString'] replication_document_model['filter'] = 'testString' replication_document_model['http_connections'] = 1 replication_document_model['query_params'] = {} replication_document_model['retries_per_request'] = 0 replication_document_model['selector'] = {} replication_document_model['since_seq'] = 'testString' replication_document_model['socket_options'] = 'testString' replication_document_model['source'] = replication_database_model replication_document_model['source_proxy'] = 'testString' replication_document_model['target'] = replication_database_model replication_document_model['target_proxy'] = 'testString' replication_document_model['use_checkpoints'] = True replication_document_model['user_ctx'] = user_context_model replication_document_model['worker_batch_size'] = 1 replication_document_model['worker_processes'] = 1 replication_document_model['foo'] = 'testString' # Set up parameter values doc_id = 'testString' replication_document = replication_document_model if_match = 'testString' batch = 'ok' new_edits = False rev = 'testString' # Invoke method response = _service.put_replication_document( doc_id, replication_document, if_match=if_match, batch=batch, new_edits=new_edits, rev=rev, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'batch={}'.format(batch) in query_string assert 'new_edits={}'.format('true' if new_edits else 'false') in query_string assert 'rev={}'.format(rev) in query_string # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body == replication_document def test_put_replication_document_all_params_with_retries(self): # Enable retries and run test_put_replication_document_all_params. _service.enable_retries() self.test_put_replication_document_all_params() # Disable retries and run test_put_replication_document_all_params. _service.disable_retries() self.test_put_replication_document_all_params() @responses.activate def test_put_replication_document_required_params(self): """ test_put_replication_document_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/_replicator/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a ReplicationCreateTargetParameters model replication_create_target_parameters_model = {} replication_create_target_parameters_model['n'] = 1 replication_create_target_parameters_model['partitioned'] = False replication_create_target_parameters_model['q'] = 1 # Construct a dict representation of a ReplicationDatabaseAuthBasic model replication_database_auth_basic_model = {} replication_database_auth_basic_model['password'] = 'testString' replication_database_auth_basic_model['username'] = 'testString' # Construct a dict representation of a ReplicationDatabaseAuthIam model replication_database_auth_iam_model = {} replication_database_auth_iam_model['api_key'] = 'testString' # Construct a dict representation of a ReplicationDatabaseAuth model replication_database_auth_model = {} replication_database_auth_model['basic'] = replication_database_auth_basic_model replication_database_auth_model['iam'] = replication_database_auth_iam_model # Construct a dict representation of a ReplicationDatabase model replication_database_model = {} replication_database_model['auth'] = replication_database_auth_model replication_database_model['headers'] = {} replication_database_model['url'] = 'testString' # Construct a dict representation of a UserContext model user_context_model = {} user_context_model['db'] = 'testString' user_context_model['name'] = 'testString' user_context_model['roles'] = ['_reader'] # Construct a dict representation of a ReplicationDocument model replication_document_model = {} replication_document_model['_attachments'] = {} replication_document_model['_conflicts'] = ['testString'] replication_document_model['_deleted'] = True replication_document_model['_deleted_conflicts'] = ['testString'] replication_document_model['_id'] = 'testString' replication_document_model['_local_seq'] = 'testString' replication_document_model['_rev'] = 'testString' replication_document_model['_revisions'] = revisions_model replication_document_model['_revs_info'] = [document_revision_status_model] replication_document_model['cancel'] = True replication_document_model['checkpoint_interval'] = 0 replication_document_model['connection_timeout'] = 0 replication_document_model['continuous'] = False replication_document_model['create_target'] = False replication_document_model['create_target_params'] = replication_create_target_parameters_model replication_document_model['doc_ids'] = ['testString'] replication_document_model['filter'] = 'testString' replication_document_model['http_connections'] = 1 replication_document_model['query_params'] = {} replication_document_model['retries_per_request'] = 0 replication_document_model['selector'] = {} replication_document_model['since_seq'] = 'testString' replication_document_model['socket_options'] = 'testString' replication_document_model['source'] = replication_database_model replication_document_model['source_proxy'] = 'testString' replication_document_model['target'] = replication_database_model replication_document_model['target_proxy'] = 'testString' replication_document_model['use_checkpoints'] = True replication_document_model['user_ctx'] = user_context_model replication_document_model['worker_batch_size'] = 1 replication_document_model['worker_processes'] = 1 replication_document_model['foo'] = 'testString' # Set up parameter values doc_id = 'testString' replication_document = replication_document_model # Invoke method response = _service.put_replication_document( doc_id, replication_document, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body == replication_document def test_put_replication_document_required_params_with_retries(self): # Enable retries and run test_put_replication_document_required_params. _service.enable_retries() self.test_put_replication_document_required_params() # Disable retries and run test_put_replication_document_required_params. _service.disable_retries() self.test_put_replication_document_required_params() @responses.activate def test_put_replication_document_value_error(self): """ test_put_replication_document_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/_replicator/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a ReplicationCreateTargetParameters model replication_create_target_parameters_model = {} replication_create_target_parameters_model['n'] = 1 replication_create_target_parameters_model['partitioned'] = False replication_create_target_parameters_model['q'] = 1 # Construct a dict representation of a ReplicationDatabaseAuthBasic model replication_database_auth_basic_model = {} replication_database_auth_basic_model['password'] = 'testString' replication_database_auth_basic_model['username'] = 'testString' # Construct a dict representation of a ReplicationDatabaseAuthIam model replication_database_auth_iam_model = {} replication_database_auth_iam_model['api_key'] = 'testString' # Construct a dict representation of a ReplicationDatabaseAuth model replication_database_auth_model = {} replication_database_auth_model['basic'] = replication_database_auth_basic_model replication_database_auth_model['iam'] = replication_database_auth_iam_model # Construct a dict representation of a ReplicationDatabase model replication_database_model = {} replication_database_model['auth'] = replication_database_auth_model replication_database_model['headers'] = {} replication_database_model['url'] = 'testString' # Construct a dict representation of a UserContext model user_context_model = {} user_context_model['db'] = 'testString' user_context_model['name'] = 'testString' user_context_model['roles'] = ['_reader'] # Construct a dict representation of a ReplicationDocument model replication_document_model = {} replication_document_model['_attachments'] = {} replication_document_model['_conflicts'] = ['testString'] replication_document_model['_deleted'] = True replication_document_model['_deleted_conflicts'] = ['testString'] replication_document_model['_id'] = 'testString' replication_document_model['_local_seq'] = 'testString' replication_document_model['_rev'] = 'testString' replication_document_model['_revisions'] = revisions_model replication_document_model['_revs_info'] = [document_revision_status_model] replication_document_model['cancel'] = True replication_document_model['checkpoint_interval'] = 0 replication_document_model['connection_timeout'] = 0 replication_document_model['continuous'] = False replication_document_model['create_target'] = False replication_document_model['create_target_params'] = replication_create_target_parameters_model replication_document_model['doc_ids'] = ['testString'] replication_document_model['filter'] = 'testString' replication_document_model['http_connections'] = 1 replication_document_model['query_params'] = {} replication_document_model['retries_per_request'] = 0 replication_document_model['selector'] = {} replication_document_model['since_seq'] = 'testString' replication_document_model['socket_options'] = 'testString' replication_document_model['source'] = replication_database_model replication_document_model['source_proxy'] = 'testString' replication_document_model['target'] = replication_database_model replication_document_model['target_proxy'] = 'testString' replication_document_model['use_checkpoints'] = True replication_document_model['user_ctx'] = user_context_model replication_document_model['worker_batch_size'] = 1 replication_document_model['worker_processes'] = 1 replication_document_model['foo'] = 'testString' # Set up parameter values doc_id = 'testString' replication_document = replication_document_model # Pass in all but one required param and check for a ValueError req_param_dict = { "doc_id": doc_id, "replication_document": replication_document, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.put_replication_document(**req_copy) def test_put_replication_document_value_error_with_retries(self): # Enable retries and run test_put_replication_document_value_error. _service.enable_retries() self.test_put_replication_document_value_error() # Disable retries and run test_put_replication_document_value_error. _service.disable_retries() self.test_put_replication_document_value_error() class TestGetSchedulerDocs(): """ Test Class for get_scheduler_docs """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_scheduler_docs_all_params(self): """ get_scheduler_docs() """ # Set up mock url = self.preprocess_url(_base_url + '/_scheduler/docs') mock_response = '{"total_rows": 0, "docs": [{"database": "database", "doc_id": "doc_id", "error_count": 0, "id": "id", "info": {"changes_pending": 0, "checkpointed_source_seq": "checkpointed_source_seq", "doc_write_failures": 0, "docs_read": 0, "docs_written": 0, "error": "error", "missing_revisions_found": 0, "revisions_checked": 0, "source_seq": "source_seq", "through_seq": "through_seq"}, "last_updated": "2019-01-01T12:00:00.000Z", "node": "node", "source": "source", "source_proxy": "source_proxy", "start_time": "2019-01-01T12:00:00.000Z", "state": "initializing", "target": "target", "target_proxy": "target_proxy"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values limit = 0 skip = 0 states = ['initializing'] # Invoke method response = _service.get_scheduler_docs( limit=limit, skip=skip, states=states, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'limit={}'.format(limit) in query_string assert 'skip={}'.format(skip) in query_string assert 'states={}'.format(','.join(states)) in query_string def test_get_scheduler_docs_all_params_with_retries(self): # Enable retries and run test_get_scheduler_docs_all_params. _service.enable_retries() self.test_get_scheduler_docs_all_params() # Disable retries and run test_get_scheduler_docs_all_params. _service.disable_retries() self.test_get_scheduler_docs_all_params() @responses.activate def test_get_scheduler_docs_required_params(self): """ test_get_scheduler_docs_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/_scheduler/docs') mock_response = '{"total_rows": 0, "docs": [{"database": "database", "doc_id": "doc_id", "error_count": 0, "id": "id", "info": {"changes_pending": 0, "checkpointed_source_seq": "checkpointed_source_seq", "doc_write_failures": 0, "docs_read": 0, "docs_written": 0, "error": "error", "missing_revisions_found": 0, "revisions_checked": 0, "source_seq": "source_seq", "through_seq": "through_seq"}, "last_updated": "2019-01-01T12:00:00.000Z", "node": "node", "source": "source", "source_proxy": "source_proxy", "start_time": "2019-01-01T12:00:00.000Z", "state": "initializing", "target": "target", "target_proxy": "target_proxy"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Invoke method response = _service.get_scheduler_docs() # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_scheduler_docs_required_params_with_retries(self): # Enable retries and run test_get_scheduler_docs_required_params. _service.enable_retries() self.test_get_scheduler_docs_required_params() # Disable retries and run test_get_scheduler_docs_required_params. _service.disable_retries() self.test_get_scheduler_docs_required_params() class TestGetSchedulerDocument(): """ Test Class for get_scheduler_document """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_scheduler_document_all_params(self): """ get_scheduler_document() """ # Set up mock url = self.preprocess_url(_base_url + '/_scheduler/docs/_replicator/testString') mock_response = '{"database": "database", "doc_id": "doc_id", "error_count": 0, "id": "id", "info": {"changes_pending": 0, "checkpointed_source_seq": "checkpointed_source_seq", "doc_write_failures": 0, "docs_read": 0, "docs_written": 0, "error": "error", "missing_revisions_found": 0, "revisions_checked": 0, "source_seq": "source_seq", "through_seq": "through_seq"}, "last_updated": "2019-01-01T12:00:00.000Z", "node": "node", "source": "source", "source_proxy": "source_proxy", "start_time": "2019-01-01T12:00:00.000Z", "state": "initializing", "target": "target", "target_proxy": "target_proxy"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values doc_id = 'testString' # Invoke method response = _service.get_scheduler_document( doc_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_scheduler_document_all_params_with_retries(self): # Enable retries and run test_get_scheduler_document_all_params. _service.enable_retries() self.test_get_scheduler_document_all_params() # Disable retries and run test_get_scheduler_document_all_params. _service.disable_retries() self.test_get_scheduler_document_all_params() @responses.activate def test_get_scheduler_document_value_error(self): """ test_get_scheduler_document_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/_scheduler/docs/_replicator/testString') mock_response = '{"database": "database", "doc_id": "doc_id", "error_count": 0, "id": "id", "info": {"changes_pending": 0, "checkpointed_source_seq": "checkpointed_source_seq", "doc_write_failures": 0, "docs_read": 0, "docs_written": 0, "error": "error", "missing_revisions_found": 0, "revisions_checked": 0, "source_seq": "source_seq", "through_seq": "through_seq"}, "last_updated": "2019-01-01T12:00:00.000Z", "node": "node", "source": "source", "source_proxy": "source_proxy", "start_time": "2019-01-01T12:00:00.000Z", "state": "initializing", "target": "target", "target_proxy": "target_proxy"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_scheduler_document(**req_copy) def test_get_scheduler_document_value_error_with_retries(self): # Enable retries and run test_get_scheduler_document_value_error. _service.enable_retries() self.test_get_scheduler_document_value_error() # Disable retries and run test_get_scheduler_document_value_error. _service.disable_retries() self.test_get_scheduler_document_value_error() class TestGetSchedulerJobs(): """ Test Class for get_scheduler_jobs """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_scheduler_jobs_all_params(self): """ get_scheduler_jobs() """ # Set up mock url = self.preprocess_url(_base_url + '/_scheduler/jobs') mock_response = '{"total_rows": 0, "jobs": [{"database": "database", "doc_id": "doc_id", "history": [{"reason": "reason", "timestamp": "2019-01-01T12:00:00.000Z", "type": "type"}], "id": "id", "info": {"changes_pending": 0, "checkpointed_source_seq": "checkpointed_source_seq", "doc_write_failures": 0, "docs_read": 0, "docs_written": 0, "error": "error", "missing_revisions_found": 0, "revisions_checked": 0, "source_seq": "source_seq", "through_seq": "through_seq"}, "node": "node", "pid": "pid", "source": "source", "start_time": "2019-01-01T12:00:00.000Z", "target": "target", "user": "user"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values limit = 0 skip = 0 # Invoke method response = _service.get_scheduler_jobs( limit=limit, skip=skip, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'limit={}'.format(limit) in query_string assert 'skip={}'.format(skip) in query_string def test_get_scheduler_jobs_all_params_with_retries(self): # Enable retries and run test_get_scheduler_jobs_all_params. _service.enable_retries() self.test_get_scheduler_jobs_all_params() # Disable retries and run test_get_scheduler_jobs_all_params. _service.disable_retries() self.test_get_scheduler_jobs_all_params() @responses.activate def test_get_scheduler_jobs_required_params(self): """ test_get_scheduler_jobs_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/_scheduler/jobs') mock_response = '{"total_rows": 0, "jobs": [{"database": "database", "doc_id": "doc_id", "history": [{"reason": "reason", "timestamp": "2019-01-01T12:00:00.000Z", "type": "type"}], "id": "id", "info": {"changes_pending": 0, "checkpointed_source_seq": "checkpointed_source_seq", "doc_write_failures": 0, "docs_read": 0, "docs_written": 0, "error": "error", "missing_revisions_found": 0, "revisions_checked": 0, "source_seq": "source_seq", "through_seq": "through_seq"}, "node": "node", "pid": "pid", "source": "source", "start_time": "2019-01-01T12:00:00.000Z", "target": "target", "user": "user"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Invoke method response = _service.get_scheduler_jobs() # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_scheduler_jobs_required_params_with_retries(self): # Enable retries and run test_get_scheduler_jobs_required_params. _service.enable_retries() self.test_get_scheduler_jobs_required_params() # Disable retries and run test_get_scheduler_jobs_required_params. _service.disable_retries() self.test_get_scheduler_jobs_required_params() class TestGetSchedulerJob(): """ Test Class for get_scheduler_job """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_scheduler_job_all_params(self): """ get_scheduler_job() """ # Set up mock url = self.preprocess_url(_base_url + '/_scheduler/jobs/testString') mock_response = '{"database": "database", "doc_id": "doc_id", "history": [{"reason": "reason", "timestamp": "2019-01-01T12:00:00.000Z", "type": "type"}], "id": "id", "info": {"changes_pending": 0, "checkpointed_source_seq": "checkpointed_source_seq", "doc_write_failures": 0, "docs_read": 0, "docs_written": 0, "error": "error", "missing_revisions_found": 0, "revisions_checked": 0, "source_seq": "source_seq", "through_seq": "through_seq"}, "node": "node", "pid": "pid", "source": "source", "start_time": "2019-01-01T12:00:00.000Z", "target": "target", "user": "user"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values job_id = 'testString' # Invoke method response = _service.get_scheduler_job( job_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_scheduler_job_all_params_with_retries(self): # Enable retries and run test_get_scheduler_job_all_params. _service.enable_retries() self.test_get_scheduler_job_all_params() # Disable retries and run test_get_scheduler_job_all_params. _service.disable_retries() self.test_get_scheduler_job_all_params() @responses.activate def test_get_scheduler_job_value_error(self): """ test_get_scheduler_job_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/_scheduler/jobs/testString') mock_response = '{"database": "database", "doc_id": "doc_id", "history": [{"reason": "reason", "timestamp": "2019-01-01T12:00:00.000Z", "type": "type"}], "id": "id", "info": {"changes_pending": 0, "checkpointed_source_seq": "checkpointed_source_seq", "doc_write_failures": 0, "docs_read": 0, "docs_written": 0, "error": "error", "missing_revisions_found": 0, "revisions_checked": 0, "source_seq": "source_seq", "through_seq": "through_seq"}, "node": "node", "pid": "pid", "source": "source", "start_time": "2019-01-01T12:00:00.000Z", "target": "target", "user": "user"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values job_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "job_id": job_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_scheduler_job(**req_copy) def test_get_scheduler_job_value_error_with_retries(self): # Enable retries and run test_get_scheduler_job_value_error. _service.enable_retries() self.test_get_scheduler_job_value_error() # Disable retries and run test_get_scheduler_job_value_error. _service.disable_retries() self.test_get_scheduler_job_value_error() # endregion ############################################################################## # End of Service: Replication ############################################################################## ############################################################################## # Start of Service: Authentication ############################################################################## # region class TestNewInstance(): """ Test Class for new_instance """ def test_new_instance(self): """ new_instance() """ os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): """ new_instance_without_authenticator() """ with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestGetSessionInformation(): """ Test Class for get_session_information """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_session_information_all_params(self): """ get_session_information() """ # Set up mock url = self.preprocess_url(_base_url + '/_session') mock_response = '{"ok": true, "info": {"authenticated": "authenticated", "authentication_db": "authentication_db", "authentication_handlers": ["authentication_handlers"]}, "userCtx": {"db": "db", "name": "name", "roles": ["_reader"]}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Invoke method response = _service.get_session_information() # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_session_information_all_params_with_retries(self): # Enable retries and run test_get_session_information_all_params. _service.enable_retries() self.test_get_session_information_all_params() # Disable retries and run test_get_session_information_all_params. _service.disable_retries() self.test_get_session_information_all_params() # endregion ############################################################################## # End of Service: Authentication ############################################################################## ############################################################################## # Start of Service: Authorization ############################################################################## # region class TestNewInstance(): """ Test Class for new_instance """ def test_new_instance(self): """ new_instance() """ os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): """ new_instance_without_authenticator() """ with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestGetSecurity(): """ Test Class for get_security """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_security_all_params(self): """ get_security() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_security') mock_response = '{"admins": {"names": ["names"], "roles": ["roles"]}, "members": {"names": ["names"], "roles": ["roles"]}, "cloudant": {"mapKey": ["_reader"]}, "couchdb_auth_only": false}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' # Invoke method response = _service.get_security( db, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_security_all_params_with_retries(self): # Enable retries and run test_get_security_all_params. _service.enable_retries() self.test_get_security_all_params() # Disable retries and run test_get_security_all_params. _service.disable_retries() self.test_get_security_all_params() @responses.activate def test_get_security_value_error(self): """ test_get_security_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_security') mock_response = '{"admins": {"names": ["names"], "roles": ["roles"]}, "members": {"names": ["names"], "roles": ["roles"]}, "cloudant": {"mapKey": ["_reader"]}, "couchdb_auth_only": false}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_security(**req_copy) def test_get_security_value_error_with_retries(self): # Enable retries and run test_get_security_value_error. _service.enable_retries() self.test_get_security_value_error() # Disable retries and run test_get_security_value_error. _service.disable_retries() self.test_get_security_value_error() class TestPutSecurity(): """ Test Class for put_security """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_put_security_all_params(self): """ put_security() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_security') mock_response = '{"ok": true}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a SecurityObject model security_object_model = {} security_object_model['names'] = ['testString'] security_object_model['roles'] = ['testString'] # Set up parameter values db = 'testString' admins = security_object_model members = security_object_model cloudant = {} couchdb_auth_only = True # Invoke method response = _service.put_security( db, admins=admins, members=members, cloudant=cloudant, couchdb_auth_only=couchdb_auth_only, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['admins'] == security_object_model assert req_body['members'] == security_object_model assert req_body['cloudant'] == {} assert req_body['couchdb_auth_only'] == True def test_put_security_all_params_with_retries(self): # Enable retries and run test_put_security_all_params. _service.enable_retries() self.test_put_security_all_params() # Disable retries and run test_put_security_all_params. _service.disable_retries() self.test_put_security_all_params() @responses.activate def test_put_security_value_error(self): """ test_put_security_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_security') mock_response = '{"ok": true}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a SecurityObject model security_object_model = {} security_object_model['names'] = ['testString'] security_object_model['roles'] = ['testString'] # Set up parameter values db = 'testString' admins = security_object_model members = security_object_model cloudant = {} couchdb_auth_only = True # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.put_security(**req_copy) def test_put_security_value_error_with_retries(self): # Enable retries and run test_put_security_value_error. _service.enable_retries() self.test_put_security_value_error() # Disable retries and run test_put_security_value_error. _service.disable_retries() self.test_put_security_value_error() class TestPostApiKeys(): """ Test Class for post_api_keys """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_api_keys_all_params(self): """ post_api_keys() """ # Set up mock url = self.preprocess_url(_base_url + '/_api/v2/api_keys') mock_response = '{"ok": true, "key": "key", "password": "password"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) # Invoke method response = _service.post_api_keys() # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 def test_post_api_keys_all_params_with_retries(self): # Enable retries and run test_post_api_keys_all_params. _service.enable_retries() self.test_post_api_keys_all_params() # Disable retries and run test_post_api_keys_all_params. _service.disable_retries() self.test_post_api_keys_all_params() class TestPutCloudantSecurityConfiguration(): """ Test Class for put_cloudant_security_configuration """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_put_cloudant_security_configuration_all_params(self): """ put_cloudant_security_configuration() """ # Set up mock url = self.preprocess_url(_base_url + '/_api/v2/db/testString/_security') mock_response = '{"ok": true}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a SecurityObject model security_object_model = {} security_object_model['names'] = ['testString'] security_object_model['roles'] = ['testString'] # Set up parameter values db = 'testString' cloudant = {} admins = security_object_model members = security_object_model couchdb_auth_only = True # Invoke method response = _service.put_cloudant_security_configuration( db, cloudant, admins=admins, members=members, couchdb_auth_only=couchdb_auth_only, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['cloudant'] == {} assert req_body['admins'] == security_object_model assert req_body['members'] == security_object_model assert req_body['couchdb_auth_only'] == True def test_put_cloudant_security_configuration_all_params_with_retries(self): # Enable retries and run test_put_cloudant_security_configuration_all_params. _service.enable_retries() self.test_put_cloudant_security_configuration_all_params() # Disable retries and run test_put_cloudant_security_configuration_all_params. _service.disable_retries() self.test_put_cloudant_security_configuration_all_params() @responses.activate def test_put_cloudant_security_configuration_value_error(self): """ test_put_cloudant_security_configuration_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/_api/v2/db/testString/_security') mock_response = '{"ok": true}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a SecurityObject model security_object_model = {} security_object_model['names'] = ['testString'] security_object_model['roles'] = ['testString'] # Set up parameter values db = 'testString' cloudant = {} admins = security_object_model members = security_object_model couchdb_auth_only = True # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "cloudant": cloudant, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.put_cloudant_security_configuration(**req_copy) def test_put_cloudant_security_configuration_value_error_with_retries(self): # Enable retries and run test_put_cloudant_security_configuration_value_error. _service.enable_retries() self.test_put_cloudant_security_configuration_value_error() # Disable retries and run test_put_cloudant_security_configuration_value_error. _service.disable_retries() self.test_put_cloudant_security_configuration_value_error() # endregion ############################################################################## # End of Service: Authorization ############################################################################## ############################################################################## # Start of Service: CORS ############################################################################## # region class TestNewInstance(): """ Test Class for new_instance """ def test_new_instance(self): """ new_instance() """ os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): """ new_instance_without_authenticator() """ with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestGetCorsInformation(): """ Test Class for get_cors_information """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_cors_information_all_params(self): """ get_cors_information() """ # Set up mock url = self.preprocess_url(_base_url + '/_api/v2/user/config/cors') mock_response = '{"allow_credentials": true, "enable_cors": true, "origins": ["origins"]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Invoke method response = _service.get_cors_information() # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_cors_information_all_params_with_retries(self): # Enable retries and run test_get_cors_information_all_params. _service.enable_retries() self.test_get_cors_information_all_params() # Disable retries and run test_get_cors_information_all_params. _service.disable_retries() self.test_get_cors_information_all_params() class TestPutCorsConfiguration(): """ Test Class for put_cors_configuration """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_put_cors_configuration_all_params(self): """ put_cors_configuration() """ # Set up mock url = self.preprocess_url(_base_url + '/_api/v2/user/config/cors') mock_response = '{"ok": true}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values origins = ['testString'] allow_credentials = True enable_cors = True # Invoke method response = _service.put_cors_configuration( origins, allow_credentials=allow_credentials, enable_cors=enable_cors, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['origins'] == ['testString'] assert req_body['allow_credentials'] == True assert req_body['enable_cors'] == True def test_put_cors_configuration_all_params_with_retries(self): # Enable retries and run test_put_cors_configuration_all_params. _service.enable_retries() self.test_put_cors_configuration_all_params() # Disable retries and run test_put_cors_configuration_all_params. _service.disable_retries() self.test_put_cors_configuration_all_params() @responses.activate def test_put_cors_configuration_value_error(self): """ test_put_cors_configuration_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/_api/v2/user/config/cors') mock_response = '{"ok": true}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values origins = ['testString'] allow_credentials = True enable_cors = True # Pass in all but one required param and check for a ValueError req_param_dict = { "origins": origins, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.put_cors_configuration(**req_copy) def test_put_cors_configuration_value_error_with_retries(self): # Enable retries and run test_put_cors_configuration_value_error. _service.enable_retries() self.test_put_cors_configuration_value_error() # Disable retries and run test_put_cors_configuration_value_error. _service.disable_retries() self.test_put_cors_configuration_value_error() # endregion ############################################################################## # End of Service: CORS ############################################################################## ############################################################################## # Start of Service: Attachments ############################################################################## # region class TestNewInstance(): """ Test Class for new_instance """ def test_new_instance(self): """ new_instance() """ os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): """ new_instance_without_authenticator() """ with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestHeadAttachment(): """ Test Class for head_attachment """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_head_attachment_all_params(self): """ head_attachment() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values db = 'testString' doc_id = 'testString' attachment_name = 'testString' if_match = 'testString' if_none_match = 'testString' rev = 'testString' # Invoke method response = _service.head_attachment( db, doc_id, attachment_name, if_match=if_match, if_none_match=if_none_match, rev=rev, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'rev={}'.format(rev) in query_string def test_head_attachment_all_params_with_retries(self): # Enable retries and run test_head_attachment_all_params. _service.enable_retries() self.test_head_attachment_all_params() # Disable retries and run test_head_attachment_all_params. _service.disable_retries() self.test_head_attachment_all_params() @responses.activate def test_head_attachment_required_params(self): """ test_head_attachment_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values db = 'testString' doc_id = 'testString' attachment_name = 'testString' # Invoke method response = _service.head_attachment( db, doc_id, attachment_name, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_head_attachment_required_params_with_retries(self): # Enable retries and run test_head_attachment_required_params. _service.enable_retries() self.test_head_attachment_required_params() # Disable retries and run test_head_attachment_required_params. _service.disable_retries() self.test_head_attachment_required_params() @responses.activate def test_head_attachment_value_error(self): """ test_head_attachment_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values db = 'testString' doc_id = 'testString' attachment_name = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "doc_id": doc_id, "attachment_name": attachment_name, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.head_attachment(**req_copy) def test_head_attachment_value_error_with_retries(self): # Enable retries and run test_head_attachment_value_error. _service.enable_retries() self.test_head_attachment_value_error() # Disable retries and run test_head_attachment_value_error. _service.disable_retries() self.test_head_attachment_value_error() class TestDeleteAttachment(): """ Test Class for delete_attachment """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_delete_attachment_all_params(self): """ delete_attachment() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=201) # Set up parameter values db = 'testString' doc_id = 'testString' attachment_name = 'testString' if_match = 'testString' rev = 'testString' batch = 'ok' # Invoke method response = _service.delete_attachment( db, doc_id, attachment_name, if_match=if_match, rev=rev, batch=batch, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'rev={}'.format(rev) in query_string assert 'batch={}'.format(batch) in query_string def test_delete_attachment_all_params_with_retries(self): # Enable retries and run test_delete_attachment_all_params. _service.enable_retries() self.test_delete_attachment_all_params() # Disable retries and run test_delete_attachment_all_params. _service.disable_retries() self.test_delete_attachment_all_params() @responses.activate def test_delete_attachment_required_params(self): """ test_delete_attachment_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=201) # Set up parameter values db = 'testString' doc_id = 'testString' attachment_name = 'testString' # Invoke method response = _service.delete_attachment( db, doc_id, attachment_name, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 def test_delete_attachment_required_params_with_retries(self): # Enable retries and run test_delete_attachment_required_params. _service.enable_retries() self.test_delete_attachment_required_params() # Disable retries and run test_delete_attachment_required_params. _service.disable_retries() self.test_delete_attachment_required_params() @responses.activate def test_delete_attachment_value_error(self): """ test_delete_attachment_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=201) # Set up parameter values db = 'testString' doc_id = 'testString' attachment_name = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "doc_id": doc_id, "attachment_name": attachment_name, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_attachment(**req_copy) def test_delete_attachment_value_error_with_retries(self): # Enable retries and run test_delete_attachment_value_error. _service.enable_retries() self.test_delete_attachment_value_error() # Disable retries and run test_delete_attachment_value_error. _service.disable_retries() self.test_delete_attachment_value_error() class TestGetAttachment(): """ Test Class for get_attachment """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_attachment_all_params(self): """ get_attachment() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString/testString') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, body=mock_response, content_type='*/*', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' attachment_name = 'testString' if_match = 'testString' if_none_match = 'testString' range = 'testString' rev = 'testString' # Invoke method response = _service.get_attachment( db, doc_id, attachment_name, if_match=if_match, if_none_match=if_none_match, range=range, rev=rev, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'rev={}'.format(rev) in query_string def test_get_attachment_all_params_with_retries(self): # Enable retries and run test_get_attachment_all_params. _service.enable_retries() self.test_get_attachment_all_params() # Disable retries and run test_get_attachment_all_params. _service.disable_retries() self.test_get_attachment_all_params() @responses.activate def test_get_attachment_required_params(self): """ test_get_attachment_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString/testString') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, body=mock_response, content_type='*/*', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' attachment_name = 'testString' # Invoke method response = _service.get_attachment( db, doc_id, attachment_name, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_attachment_required_params_with_retries(self): # Enable retries and run test_get_attachment_required_params. _service.enable_retries() self.test_get_attachment_required_params() # Disable retries and run test_get_attachment_required_params. _service.disable_retries() self.test_get_attachment_required_params() @responses.activate def test_get_attachment_value_error(self): """ test_get_attachment_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString/testString') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, body=mock_response, content_type='*/*', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' attachment_name = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "doc_id": doc_id, "attachment_name": attachment_name, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_attachment(**req_copy) def test_get_attachment_value_error_with_retries(self): # Enable retries and run test_get_attachment_value_error. _service.enable_retries() self.test_get_attachment_value_error() # Disable retries and run test_get_attachment_value_error. _service.disable_retries() self.test_get_attachment_value_error() class TestPutAttachment(): """ Test Class for put_attachment """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_put_attachment_all_params(self): """ put_attachment() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Set up parameter values db = 'testString' doc_id = 'testString' attachment_name = 'testString' attachment = io.BytesIO(b'This is a mock file.').getvalue() content_type = 'application/octet-stream' if_match = 'testString' rev = 'testString' # Invoke method response = _service.put_attachment( db, doc_id, attachment_name, attachment, content_type, if_match=if_match, rev=rev, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'rev={}'.format(rev) in query_string # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params def test_put_attachment_all_params_with_retries(self): # Enable retries and run test_put_attachment_all_params. _service.enable_retries() self.test_put_attachment_all_params() # Disable retries and run test_put_attachment_all_params. _service.disable_retries() self.test_put_attachment_all_params() @responses.activate def test_put_attachment_required_params(self): """ test_put_attachment_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Set up parameter values db = 'testString' doc_id = 'testString' attachment_name = 'testString' attachment = io.BytesIO(b'This is a mock file.').getvalue() content_type = 'application/octet-stream' # Invoke method response = _service.put_attachment( db, doc_id, attachment_name, attachment, content_type, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params def test_put_attachment_required_params_with_retries(self): # Enable retries and run test_put_attachment_required_params. _service.enable_retries() self.test_put_attachment_required_params() # Disable retries and run test_put_attachment_required_params. _service.disable_retries() self.test_put_attachment_required_params() @responses.activate def test_put_attachment_value_error(self): """ test_put_attachment_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/testString/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Set up parameter values db = 'testString' doc_id = 'testString' attachment_name = 'testString' attachment = io.BytesIO(b'This is a mock file.').getvalue() content_type = 'application/octet-stream' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "doc_id": doc_id, "attachment_name": attachment_name, "attachment": attachment, "content_type": content_type, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.put_attachment(**req_copy) def test_put_attachment_value_error_with_retries(self): # Enable retries and run test_put_attachment_value_error. _service.enable_retries() self.test_put_attachment_value_error() # Disable retries and run test_put_attachment_value_error. _service.disable_retries() self.test_put_attachment_value_error() # endregion ############################################################################## # End of Service: Attachments ############################################################################## ############################################################################## # Start of Service: LocalDocuments ############################################################################## # region class TestNewInstance(): """ Test Class for new_instance """ def test_new_instance(self): """ new_instance() """ os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): """ new_instance_without_authenticator() """ with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestHeadLocalDocument(): """ Test Class for head_local_document """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_head_local_document_all_params(self): """ head_local_document() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_local/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values db = 'testString' doc_id = 'testString' if_none_match = 'testString' # Invoke method response = _service.head_local_document( db, doc_id, if_none_match=if_none_match, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_head_local_document_all_params_with_retries(self): # Enable retries and run test_head_local_document_all_params. _service.enable_retries() self.test_head_local_document_all_params() # Disable retries and run test_head_local_document_all_params. _service.disable_retries() self.test_head_local_document_all_params() @responses.activate def test_head_local_document_required_params(self): """ test_head_local_document_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_local/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Invoke method response = _service.head_local_document( db, doc_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_head_local_document_required_params_with_retries(self): # Enable retries and run test_head_local_document_required_params. _service.enable_retries() self.test_head_local_document_required_params() # Disable retries and run test_head_local_document_required_params. _service.disable_retries() self.test_head_local_document_required_params() @responses.activate def test_head_local_document_value_error(self): """ test_head_local_document_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_local/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.head_local_document(**req_copy) def test_head_local_document_value_error_with_retries(self): # Enable retries and run test_head_local_document_value_error. _service.enable_retries() self.test_head_local_document_value_error() # Disable retries and run test_head_local_document_value_error. _service.disable_retries() self.test_head_local_document_value_error() class TestDeleteLocalDocument(): """ Test Class for delete_local_document """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_delete_local_document_all_params(self): """ delete_local_document() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_local/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' batch = 'ok' # Invoke method response = _service.delete_local_document( db, doc_id, batch=batch, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'batch={}'.format(batch) in query_string def test_delete_local_document_all_params_with_retries(self): # Enable retries and run test_delete_local_document_all_params. _service.enable_retries() self.test_delete_local_document_all_params() # Disable retries and run test_delete_local_document_all_params. _service.disable_retries() self.test_delete_local_document_all_params() @responses.activate def test_delete_local_document_required_params(self): """ test_delete_local_document_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_local/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Invoke method response = _service.delete_local_document( db, doc_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_delete_local_document_required_params_with_retries(self): # Enable retries and run test_delete_local_document_required_params. _service.enable_retries() self.test_delete_local_document_required_params() # Disable retries and run test_delete_local_document_required_params. _service.disable_retries() self.test_delete_local_document_required_params() @responses.activate def test_delete_local_document_value_error(self): """ test_delete_local_document_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_local/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_local_document(**req_copy) def test_delete_local_document_value_error_with_retries(self): # Enable retries and run test_delete_local_document_value_error. _service.enable_retries() self.test_delete_local_document_value_error() # Disable retries and run test_delete_local_document_value_error. _service.disable_retries() self.test_delete_local_document_value_error() class TestGetLocalDocument(): """ Test Class for get_local_document """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_local_document_all_params(self): """ get_local_document() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_local/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' accept = 'application/json' if_none_match = 'testString' attachments = False att_encoding_info = False local_seq = False # Invoke method response = _service.get_local_document( db, doc_id, accept=accept, if_none_match=if_none_match, attachments=attachments, att_encoding_info=att_encoding_info, local_seq=local_seq, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'local_seq={}'.format('true' if local_seq else 'false') in query_string def test_get_local_document_all_params_with_retries(self): # Enable retries and run test_get_local_document_all_params. _service.enable_retries() self.test_get_local_document_all_params() # Disable retries and run test_get_local_document_all_params. _service.disable_retries() self.test_get_local_document_all_params() @responses.activate def test_get_local_document_required_params(self): """ test_get_local_document_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_local/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Invoke method response = _service.get_local_document( db, doc_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_local_document_required_params_with_retries(self): # Enable retries and run test_get_local_document_required_params. _service.enable_retries() self.test_get_local_document_required_params() # Disable retries and run test_get_local_document_required_params. _service.disable_retries() self.test_get_local_document_required_params() @responses.activate def test_get_local_document_value_error(self): """ test_get_local_document_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_local/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_local_document(**req_copy) def test_get_local_document_value_error_with_retries(self): # Enable retries and run test_get_local_document_value_error. _service.enable_retries() self.test_get_local_document_value_error() # Disable retries and run test_get_local_document_value_error. _service.disable_retries() self.test_get_local_document_value_error() class TestPutLocalDocument(): """ Test Class for put_local_document """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_put_local_document_all_params(self): """ put_local_document() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_local/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Document model document_model = {} document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'exampleid' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['brand'] = 'Foo' document_model['colours'] = '["red","green","black","blue"]' document_model['description'] = 'Slim Colourful Design Electronic Cooking Appliance for ...' document_model['image'] = 'assets/img/0gmsnghhew.jpg' document_model['keywords'] = '["Foo","Scales","Weight","Digital","Kitchen"]' document_model['name'] = 'Digital Kitchen Scales' document_model['price'] = '14.99' document_model['productid'] = '1000042' document_model['taxonomy'] = '["Home","Kitchen","Small Appliances"]' document_model['type'] = 'product' # Set up parameter values db = 'testString' doc_id = 'testString' document = document_model content_type = 'application/json' batch = 'ok' # Invoke method response = _service.put_local_document( db, doc_id, document, content_type=content_type, batch=batch, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'batch={}'.format(batch) in query_string # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params def test_put_local_document_all_params_with_retries(self): # Enable retries and run test_put_local_document_all_params. _service.enable_retries() self.test_put_local_document_all_params() # Disable retries and run test_put_local_document_all_params. _service.disable_retries() self.test_put_local_document_all_params() @responses.activate def test_put_local_document_required_params(self): """ test_put_local_document_required_params() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_local/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Document model document_model = {} document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'exampleid' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['brand'] = 'Foo' document_model['colours'] = '["red","green","black","blue"]' document_model['description'] = 'Slim Colourful Design Electronic Cooking Appliance for ...' document_model['image'] = 'assets/img/0gmsnghhew.jpg' document_model['keywords'] = '["Foo","Scales","Weight","Digital","Kitchen"]' document_model['name'] = 'Digital Kitchen Scales' document_model['price'] = '14.99' document_model['productid'] = '1000042' document_model['taxonomy'] = '["Home","Kitchen","Small Appliances"]' document_model['type'] = 'product' # Set up parameter values db = 'testString' doc_id = 'testString' document = document_model # Invoke method response = _service.put_local_document( db, doc_id, document, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params def test_put_local_document_required_params_with_retries(self): # Enable retries and run test_put_local_document_required_params. _service.enable_retries() self.test_put_local_document_required_params() # Disable retries and run test_put_local_document_required_params. _service.disable_retries() self.test_put_local_document_required_params() @responses.activate def test_put_local_document_value_error(self): """ test_put_local_document_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_local/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Document model document_model = {} document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'exampleid' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['brand'] = 'Foo' document_model['colours'] = '["red","green","black","blue"]' document_model['description'] = 'Slim Colourful Design Electronic Cooking Appliance for ...' document_model['image'] = 'assets/img/0gmsnghhew.jpg' document_model['keywords'] = '["Foo","Scales","Weight","Digital","Kitchen"]' document_model['name'] = 'Digital Kitchen Scales' document_model['price'] = '14.99' document_model['productid'] = '1000042' document_model['taxonomy'] = '["Home","Kitchen","Small Appliances"]' document_model['type'] = 'product' # Set up parameter values db = 'testString' doc_id = 'testString' document = document_model # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "doc_id": doc_id, "document": document, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.put_local_document(**req_copy) def test_put_local_document_value_error_with_retries(self): # Enable retries and run test_put_local_document_value_error. _service.enable_retries() self.test_put_local_document_value_error() # Disable retries and run test_put_local_document_value_error. _service.disable_retries() self.test_put_local_document_value_error() # endregion ############################################################################## # End of Service: LocalDocuments ############################################################################## ############################################################################## # Start of Service: DatabaseDetails ############################################################################## # region class TestNewInstance(): """ Test Class for new_instance """ def test_new_instance(self): """ new_instance() """ os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): """ new_instance_without_authenticator() """ with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestPostRevsDiff(): """ Test Class for post_revs_diff """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_revs_diff_all_params(self): """ post_revs_diff() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_revs_diff') mock_response = '{"mapKey": {"missing": ["missing"], "possible_ancestors": ["possible_ancestors"]}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' document_revisions = {} # Invoke method response = _service.post_revs_diff( db, document_revisions, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body == document_revisions def test_post_revs_diff_all_params_with_retries(self): # Enable retries and run test_post_revs_diff_all_params. _service.enable_retries() self.test_post_revs_diff_all_params() # Disable retries and run test_post_revs_diff_all_params. _service.disable_retries() self.test_post_revs_diff_all_params() @responses.activate def test_post_revs_diff_value_error(self): """ test_post_revs_diff_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_revs_diff') mock_response = '{"mapKey": {"missing": ["missing"], "possible_ancestors": ["possible_ancestors"]}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' document_revisions = {} # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "document_revisions": document_revisions, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_revs_diff(**req_copy) def test_post_revs_diff_value_error_with_retries(self): # Enable retries and run test_post_revs_diff_value_error. _service.enable_retries() self.test_post_revs_diff_value_error() # Disable retries and run test_post_revs_diff_value_error. _service.disable_retries() self.test_post_revs_diff_value_error() class TestGetShardsInformation(): """ Test Class for get_shards_information """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_shards_information_all_params(self): """ get_shards_information() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_shards') mock_response = '{"shards": {"mapKey": ["inner"]}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' # Invoke method response = _service.get_shards_information( db, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_shards_information_all_params_with_retries(self): # Enable retries and run test_get_shards_information_all_params. _service.enable_retries() self.test_get_shards_information_all_params() # Disable retries and run test_get_shards_information_all_params. _service.disable_retries() self.test_get_shards_information_all_params() @responses.activate def test_get_shards_information_value_error(self): """ test_get_shards_information_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_shards') mock_response = '{"shards": {"mapKey": ["inner"]}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_shards_information(**req_copy) def test_get_shards_information_value_error_with_retries(self): # Enable retries and run test_get_shards_information_value_error. _service.enable_retries() self.test_get_shards_information_value_error() # Disable retries and run test_get_shards_information_value_error. _service.disable_retries() self.test_get_shards_information_value_error() class TestGetDocumentShardsInfo(): """ Test Class for get_document_shards_info """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_document_shards_info_all_params(self): """ get_document_shards_info() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_shards/testString') mock_response = '{"nodes": ["nodes"], "range": "range"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Invoke method response = _service.get_document_shards_info( db, doc_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_document_shards_info_all_params_with_retries(self): # Enable retries and run test_get_document_shards_info_all_params. _service.enable_retries() self.test_get_document_shards_info_all_params() # Disable retries and run test_get_document_shards_info_all_params. _service.disable_retries() self.test_get_document_shards_info_all_params() @responses.activate def test_get_document_shards_info_value_error(self): """ test_get_document_shards_info_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/testString/_shards/testString') mock_response = '{"nodes": ["nodes"], "range": "range"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_document_shards_info(**req_copy) def test_get_document_shards_info_value_error_with_retries(self): # Enable retries and run test_get_document_shards_info_value_error. _service.enable_retries() self.test_get_document_shards_info_value_error() # Disable retries and run test_get_document_shards_info_value_error. _service.disable_retries() self.test_get_document_shards_info_value_error() # endregion ############################################################################## # End of Service: DatabaseDetails ############################################################################## ############################################################################## # Start of Service: Monitoring ############################################################################## # region class TestNewInstance(): """ Test Class for new_instance """ def test_new_instance(self): """ new_instance() """ os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): """ new_instance_without_authenticator() """ with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestHeadUpInformation(): """ Test Class for head_up_information """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_head_up_information_all_params(self): """ head_up_information() """ # Set up mock url = self.preprocess_url(_base_url + '/_up') responses.add(responses.HEAD, url, status=200) # Invoke method response = _service.head_up_information() # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_head_up_information_all_params_with_retries(self): # Enable retries and run test_head_up_information_all_params. _service.enable_retries() self.test_head_up_information_all_params() # Disable retries and run test_head_up_information_all_params. _service.disable_retries() self.test_head_up_information_all_params() class TestGetActiveTasks(): """ Test Class for get_active_tasks """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_active_tasks_all_params(self): """ get_active_tasks() """ # Set up mock url = self.preprocess_url(_base_url + '/_active_tasks') mock_response = '[{"changes_done": 0, "database": "database", "node": "node", "pid": "pid", "progress": 0, "started_on": 0, "status": "status", "task": "task", "total_changes": 0, "type": "type", "updated_on": 0}]' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Invoke method response = _service.get_active_tasks() # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_active_tasks_all_params_with_retries(self): # Enable retries and run test_get_active_tasks_all_params. _service.enable_retries() self.test_get_active_tasks_all_params() # Disable retries and run test_get_active_tasks_all_params. _service.disable_retries() self.test_get_active_tasks_all_params() class TestGetUpInformation(): """ Test Class for get_up_information """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_up_information_all_params(self): """ get_up_information() """ # Set up mock url = self.preprocess_url(_base_url + '/_up') mock_response = '{"seeds": {"anyKey": "anyValue"}, "status": "maintenance_mode"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Invoke method response = _service.get_up_information() # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_up_information_all_params_with_retries(self): # Enable retries and run test_get_up_information_all_params. _service.enable_retries() self.test_get_up_information_all_params() # Disable retries and run test_get_up_information_all_params. _service.disable_retries() self.test_get_up_information_all_params() class TestGetActivityTrackerEvents(): """ Test Class for get_activity_tracker_events """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_activity_tracker_events_all_params(self): """ get_activity_tracker_events() """ # Set up mock url = self.preprocess_url(_base_url + '/_api/v2/user/activity_tracker/events') mock_response = '{"types": ["management"]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Invoke method response = _service.get_activity_tracker_events() # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_activity_tracker_events_all_params_with_retries(self): # Enable retries and run test_get_activity_tracker_events_all_params. _service.enable_retries() self.test_get_activity_tracker_events_all_params() # Disable retries and run test_get_activity_tracker_events_all_params. _service.disable_retries() self.test_get_activity_tracker_events_all_params() class TestPostActivityTrackerEvents(): """ Test Class for post_activity_tracker_events """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_activity_tracker_events_all_params(self): """ post_activity_tracker_events() """ # Set up mock url = self.preprocess_url(_base_url + '/_api/v2/user/activity_tracker/events') mock_response = '{"ok": true}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values types = ['management'] # Invoke method response = _service.post_activity_tracker_events( types, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['types'] == ['management'] def test_post_activity_tracker_events_all_params_with_retries(self): # Enable retries and run test_post_activity_tracker_events_all_params. _service.enable_retries() self.test_post_activity_tracker_events_all_params() # Disable retries and run test_post_activity_tracker_events_all_params. _service.disable_retries() self.test_post_activity_tracker_events_all_params() @responses.activate def test_post_activity_tracker_events_value_error(self): """ test_post_activity_tracker_events_value_error() """ # Set up mock url = self.preprocess_url(_base_url + '/_api/v2/user/activity_tracker/events') mock_response = '{"ok": true}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values types = ['management'] # Pass in all but one required param and check for a ValueError req_param_dict = { "types": types, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_activity_tracker_events(**req_copy) def test_post_activity_tracker_events_value_error_with_retries(self): # Enable retries and run test_post_activity_tracker_events_value_error. _service.enable_retries() self.test_post_activity_tracker_events_value_error() # Disable retries and run test_post_activity_tracker_events_value_error. _service.disable_retries() self.test_post_activity_tracker_events_value_error() class TestGetCurrentThroughputInformation(): """ Test Class for get_current_throughput_information """ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_current_throughput_information_all_params(self): """ get_current_throughput_information() """ # Set up mock url = self.preprocess_url(_base_url + '/_api/v2/user/current/throughput') mock_response = '{"throughput": {"query": 0, "read": 0, "write": 0}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Invoke method response = _service.get_current_throughput_information() # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_current_throughput_information_all_params_with_retries(self): # Enable retries and run test_get_current_throughput_information_all_params. _service.enable_retries() self.test_get_current_throughput_information_all_params() # Disable retries and run test_get_current_throughput_information_all_params. _service.disable_retries() self.test_get_current_throughput_information_all_params() # endregion ############################################################################## # End of Service: Monitoring ############################################################################## ############################################################################## # Start of Model Tests ############################################################################## # region class TestModel_ActiveTask(): """ Test Class for ActiveTask """ def test_active_task_serialization(self): """ Test serialization/deserialization for ActiveTask """ # Construct a json representation of a ActiveTask model active_task_model_json = {} active_task_model_json['changes_done'] = 0 active_task_model_json['database'] = 'testString' active_task_model_json['node'] = 'testString' active_task_model_json['pid'] = 'testString' active_task_model_json['progress'] = 0 active_task_model_json['started_on'] = 0 active_task_model_json['status'] = 'testString' active_task_model_json['task'] = 'testString' active_task_model_json['total_changes'] = 0 active_task_model_json['type'] = 'testString' active_task_model_json['updated_on'] = 0 # Construct a model instance of ActiveTask by calling from_dict on the json representation active_task_model = ActiveTask.from_dict(active_task_model_json) assert active_task_model != False # Construct a model instance of ActiveTask by calling from_dict on the json representation active_task_model_dict = ActiveTask.from_dict(active_task_model_json).__dict__ active_task_model2 = ActiveTask(**active_task_model_dict) # Verify the model instances are equivalent assert active_task_model == active_task_model2 # Convert model instance back to dict and verify no loss of data active_task_model_json2 = active_task_model.to_dict() assert active_task_model_json2 == active_task_model_json class TestModel_ActivityTrackerEvents(): """ Test Class for ActivityTrackerEvents """ def test_activity_tracker_events_serialization(self): """ Test serialization/deserialization for ActivityTrackerEvents """ # Construct a json representation of a ActivityTrackerEvents model activity_tracker_events_model_json = {} activity_tracker_events_model_json['types'] = ['management'] # Construct a model instance of ActivityTrackerEvents by calling from_dict on the json representation activity_tracker_events_model = ActivityTrackerEvents.from_dict(activity_tracker_events_model_json) assert activity_tracker_events_model != False # Construct a model instance of ActivityTrackerEvents by calling from_dict on the json representation activity_tracker_events_model_dict = ActivityTrackerEvents.from_dict(activity_tracker_events_model_json).__dict__ activity_tracker_events_model2 = ActivityTrackerEvents(**activity_tracker_events_model_dict) # Verify the model instances are equivalent assert activity_tracker_events_model == activity_tracker_events_model2 # Convert model instance back to dict and verify no loss of data activity_tracker_events_model_json2 = activity_tracker_events_model.to_dict() assert activity_tracker_events_model_json2 == activity_tracker_events_model_json class TestModel_AllDocsQueriesResult(): """ Test Class for AllDocsQueriesResult """ def test_all_docs_queries_result_serialization(self): """ Test serialization/deserialization for AllDocsQueriesResult """ # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' docs_result_row_value_model = {} # DocsResultRowValue docs_result_row_value_model['rev'] = 'testString' docs_result_row_model = {} # DocsResultRow docs_result_row_model['caused_by'] = 'testString' docs_result_row_model['error'] = 'testString' docs_result_row_model['reason'] = 'testString' docs_result_row_model['doc'] = document_model docs_result_row_model['id'] = 'testString' docs_result_row_model['key'] = 'testString' docs_result_row_model['value'] = docs_result_row_value_model all_docs_result_model = {} # AllDocsResult all_docs_result_model['total_rows'] = 0 all_docs_result_model['rows'] = [docs_result_row_model] all_docs_result_model['update_seq'] = 'testString' # Construct a json representation of a AllDocsQueriesResult model all_docs_queries_result_model_json = {} all_docs_queries_result_model_json['results'] = [all_docs_result_model] # Construct a model instance of AllDocsQueriesResult by calling from_dict on the json representation all_docs_queries_result_model = AllDocsQueriesResult.from_dict(all_docs_queries_result_model_json) assert all_docs_queries_result_model != False # Construct a model instance of AllDocsQueriesResult by calling from_dict on the json representation all_docs_queries_result_model_dict = AllDocsQueriesResult.from_dict(all_docs_queries_result_model_json).__dict__ all_docs_queries_result_model2 = AllDocsQueriesResult(**all_docs_queries_result_model_dict) # Verify the model instances are equivalent assert all_docs_queries_result_model == all_docs_queries_result_model2 # Convert model instance back to dict and verify no loss of data all_docs_queries_result_model_json2 = all_docs_queries_result_model.to_dict() assert all_docs_queries_result_model_json2 == all_docs_queries_result_model_json class TestModel_AllDocsQuery(): """ Test Class for AllDocsQuery """ def test_all_docs_query_serialization(self): """ Test serialization/deserialization for AllDocsQuery """ # Construct a json representation of a AllDocsQuery model all_docs_query_model_json = {} all_docs_query_model_json['att_encoding_info'] = False all_docs_query_model_json['attachments'] = False all_docs_query_model_json['conflicts'] = False all_docs_query_model_json['descending'] = False all_docs_query_model_json['include_docs'] = False all_docs_query_model_json['inclusive_end'] = True all_docs_query_model_json['limit'] = 0 all_docs_query_model_json['skip'] = 0 all_docs_query_model_json['update_seq'] = False all_docs_query_model_json['endkey'] = 'testString' all_docs_query_model_json['key'] = 'testString' all_docs_query_model_json['keys'] = ['testString'] all_docs_query_model_json['startkey'] = 'testString' # Construct a model instance of AllDocsQuery by calling from_dict on the json representation all_docs_query_model = AllDocsQuery.from_dict(all_docs_query_model_json) assert all_docs_query_model != False # Construct a model instance of AllDocsQuery by calling from_dict on the json representation all_docs_query_model_dict = AllDocsQuery.from_dict(all_docs_query_model_json).__dict__ all_docs_query_model2 = AllDocsQuery(**all_docs_query_model_dict) # Verify the model instances are equivalent assert all_docs_query_model == all_docs_query_model2 # Convert model instance back to dict and verify no loss of data all_docs_query_model_json2 = all_docs_query_model.to_dict() assert all_docs_query_model_json2 == all_docs_query_model_json class TestModel_AllDocsResult(): """ Test Class for AllDocsResult """ def test_all_docs_result_serialization(self): """ Test serialization/deserialization for AllDocsResult """ # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' docs_result_row_value_model = {} # DocsResultRowValue docs_result_row_value_model['rev'] = 'testString' docs_result_row_model = {} # DocsResultRow docs_result_row_model['caused_by'] = 'testString' docs_result_row_model['error'] = 'testString' docs_result_row_model['reason'] = 'testString' docs_result_row_model['doc'] = document_model docs_result_row_model['id'] = 'testString' docs_result_row_model['key'] = 'testString' docs_result_row_model['value'] = docs_result_row_value_model # Construct a json representation of a AllDocsResult model all_docs_result_model_json = {} all_docs_result_model_json['total_rows'] = 0 all_docs_result_model_json['rows'] = [docs_result_row_model] all_docs_result_model_json['update_seq'] = 'testString' # Construct a model instance of AllDocsResult by calling from_dict on the json representation all_docs_result_model = AllDocsResult.from_dict(all_docs_result_model_json) assert all_docs_result_model != False # Construct a model instance of AllDocsResult by calling from_dict on the json representation all_docs_result_model_dict = AllDocsResult.from_dict(all_docs_result_model_json).__dict__ all_docs_result_model2 = AllDocsResult(**all_docs_result_model_dict) # Verify the model instances are equivalent assert all_docs_result_model == all_docs_result_model2 # Convert model instance back to dict and verify no loss of data all_docs_result_model_json2 = all_docs_result_model.to_dict() assert all_docs_result_model_json2 == all_docs_result_model_json class TestModel_Analyzer(): """ Test Class for Analyzer """ def test_analyzer_serialization(self): """ Test serialization/deserialization for Analyzer """ # Construct a json representation of a Analyzer model analyzer_model_json = {} analyzer_model_json['name'] = 'classic' analyzer_model_json['stopwords'] = ['testString'] # Construct a model instance of Analyzer by calling from_dict on the json representation analyzer_model = Analyzer.from_dict(analyzer_model_json) assert analyzer_model != False # Construct a model instance of Analyzer by calling from_dict on the json representation analyzer_model_dict = Analyzer.from_dict(analyzer_model_json).__dict__ analyzer_model2 = Analyzer(**analyzer_model_dict) # Verify the model instances are equivalent assert analyzer_model == analyzer_model2 # Convert model instance back to dict and verify no loss of data analyzer_model_json2 = analyzer_model.to_dict() assert analyzer_model_json2 == analyzer_model_json class TestModel_AnalyzerConfiguration(): """ Test Class for AnalyzerConfiguration """ def test_analyzer_configuration_serialization(self): """ Test serialization/deserialization for AnalyzerConfiguration """ # Construct dict forms of any model objects needed in order to build this model. analyzer_model = {} # Analyzer analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] # Construct a json representation of a AnalyzerConfiguration model analyzer_configuration_model_json = {} analyzer_configuration_model_json['name'] = 'classic' analyzer_configuration_model_json['stopwords'] = ['testString'] analyzer_configuration_model_json['fields'] = {} # Construct a model instance of AnalyzerConfiguration by calling from_dict on the json representation analyzer_configuration_model = AnalyzerConfiguration.from_dict(analyzer_configuration_model_json) assert analyzer_configuration_model != False # Construct a model instance of AnalyzerConfiguration by calling from_dict on the json representation analyzer_configuration_model_dict = AnalyzerConfiguration.from_dict(analyzer_configuration_model_json).__dict__ analyzer_configuration_model2 = AnalyzerConfiguration(**analyzer_configuration_model_dict) # Verify the model instances are equivalent assert analyzer_configuration_model == analyzer_configuration_model2 # Convert model instance back to dict and verify no loss of data analyzer_configuration_model_json2 = analyzer_configuration_model.to_dict() assert analyzer_configuration_model_json2 == analyzer_configuration_model_json class TestModel_ApiKeysResult(): """ Test Class for ApiKeysResult """ def test_api_keys_result_serialization(self): """ Test serialization/deserialization for ApiKeysResult """ # Construct a json representation of a ApiKeysResult model api_keys_result_model_json = {} api_keys_result_model_json['ok'] = True api_keys_result_model_json['key'] = 'testString' api_keys_result_model_json['password'] = 'testString' # Construct a model instance of ApiKeysResult by calling from_dict on the json representation api_keys_result_model = ApiKeysResult.from_dict(api_keys_result_model_json) assert api_keys_result_model != False # Construct a model instance of ApiKeysResult by calling from_dict on the json representation api_keys_result_model_dict = ApiKeysResult.from_dict(api_keys_result_model_json).__dict__ api_keys_result_model2 = ApiKeysResult(**api_keys_result_model_dict) # Verify the model instances are equivalent assert api_keys_result_model == api_keys_result_model2 # Convert model instance back to dict and verify no loss of data api_keys_result_model_json2 = api_keys_result_model.to_dict() assert api_keys_result_model_json2 == api_keys_result_model_json class TestModel_Attachment(): """ Test Class for Attachment """ def test_attachment_serialization(self): """ Test serialization/deserialization for Attachment """ # Construct a json representation of a Attachment model attachment_model_json = {} attachment_model_json['content_type'] = 'testString' attachment_model_json['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model_json['digest'] = 'testString' attachment_model_json['encoded_length'] = 0 attachment_model_json['encoding'] = 'testString' attachment_model_json['follows'] = True attachment_model_json['length'] = 0 attachment_model_json['revpos'] = 1 attachment_model_json['stub'] = True # Construct a model instance of Attachment by calling from_dict on the json representation attachment_model = Attachment.from_dict(attachment_model_json) assert attachment_model != False # Construct a model instance of Attachment by calling from_dict on the json representation attachment_model_dict = Attachment.from_dict(attachment_model_json).__dict__ attachment_model2 = Attachment(**attachment_model_dict) # Verify the model instances are equivalent assert attachment_model == attachment_model2 # Convert model instance back to dict and verify no loss of data attachment_model_json2 = attachment_model.to_dict() assert attachment_model_json2 == attachment_model_json class TestModel_BulkDocs(): """ Test Class for BulkDocs """ def test_bulk_docs_serialization(self): """ Test serialization/deserialization for BulkDocs """ # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' # Construct a json representation of a BulkDocs model bulk_docs_model_json = {} bulk_docs_model_json['docs'] = [document_model] bulk_docs_model_json['new_edits'] = True # Construct a model instance of BulkDocs by calling from_dict on the json representation bulk_docs_model = BulkDocs.from_dict(bulk_docs_model_json) assert bulk_docs_model != False # Construct a model instance of BulkDocs by calling from_dict on the json representation bulk_docs_model_dict = BulkDocs.from_dict(bulk_docs_model_json).__dict__ bulk_docs_model2 = BulkDocs(**bulk_docs_model_dict) # Verify the model instances are equivalent assert bulk_docs_model == bulk_docs_model2 # Convert model instance back to dict and verify no loss of data bulk_docs_model_json2 = bulk_docs_model.to_dict() assert bulk_docs_model_json2 == bulk_docs_model_json class TestModel_BulkGetQueryDocument(): """ Test Class for BulkGetQueryDocument """ def test_bulk_get_query_document_serialization(self): """ Test serialization/deserialization for BulkGetQueryDocument """ # Construct a json representation of a BulkGetQueryDocument model bulk_get_query_document_model_json = {} bulk_get_query_document_model_json['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model_json['id'] = 'testString' bulk_get_query_document_model_json['rev'] = 'testString' # Construct a model instance of BulkGetQueryDocument by calling from_dict on the json representation bulk_get_query_document_model = BulkGetQueryDocument.from_dict(bulk_get_query_document_model_json) assert bulk_get_query_document_model != False # Construct a model instance of BulkGetQueryDocument by calling from_dict on the json representation bulk_get_query_document_model_dict = BulkGetQueryDocument.from_dict(bulk_get_query_document_model_json).__dict__ bulk_get_query_document_model2 = BulkGetQueryDocument(**bulk_get_query_document_model_dict) # Verify the model instances are equivalent assert bulk_get_query_document_model == bulk_get_query_document_model2 # Convert model instance back to dict and verify no loss of data bulk_get_query_document_model_json2 = bulk_get_query_document_model.to_dict() assert bulk_get_query_document_model_json2 == bulk_get_query_document_model_json class TestModel_BulkGetResult(): """ Test Class for BulkGetResult """ def test_bulk_get_result_serialization(self): """ Test serialization/deserialization for BulkGetResult """ # Construct dict forms of any model objects needed in order to build this model. document_result_model = {} # DocumentResult document_result_model['id'] = 'testString' document_result_model['rev'] = 'testString' document_result_model['ok'] = True document_result_model['caused_by'] = 'testString' document_result_model['error'] = 'testString' document_result_model['reason'] = 'testString' attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' bulk_get_result_document_model = {} # BulkGetResultDocument bulk_get_result_document_model['error'] = document_result_model bulk_get_result_document_model['ok'] = document_model bulk_get_result_item_model = {} # BulkGetResultItem bulk_get_result_item_model['docs'] = [bulk_get_result_document_model] bulk_get_result_item_model['id'] = 'testString' # Construct a json representation of a BulkGetResult model bulk_get_result_model_json = {} bulk_get_result_model_json['results'] = [bulk_get_result_item_model] # Construct a model instance of BulkGetResult by calling from_dict on the json representation bulk_get_result_model = BulkGetResult.from_dict(bulk_get_result_model_json) assert bulk_get_result_model != False # Construct a model instance of BulkGetResult by calling from_dict on the json representation bulk_get_result_model_dict = BulkGetResult.from_dict(bulk_get_result_model_json).__dict__ bulk_get_result_model2 = BulkGetResult(**bulk_get_result_model_dict) # Verify the model instances are equivalent assert bulk_get_result_model == bulk_get_result_model2 # Convert model instance back to dict and verify no loss of data bulk_get_result_model_json2 = bulk_get_result_model.to_dict() assert bulk_get_result_model_json2 == bulk_get_result_model_json class TestModel_BulkGetResultDocument(): """ Test Class for BulkGetResultDocument """ def test_bulk_get_result_document_serialization(self): """ Test serialization/deserialization for BulkGetResultDocument """ # Construct dict forms of any model objects needed in order to build this model. document_result_model = {} # DocumentResult document_result_model['id'] = 'testString' document_result_model['rev'] = 'testString' document_result_model['ok'] = True document_result_model['caused_by'] = 'testString' document_result_model['error'] = 'testString' document_result_model['reason'] = 'testString' attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' # Construct a json representation of a BulkGetResultDocument model bulk_get_result_document_model_json = {} bulk_get_result_document_model_json['error'] = document_result_model bulk_get_result_document_model_json['ok'] = document_model # Construct a model instance of BulkGetResultDocument by calling from_dict on the json representation bulk_get_result_document_model = BulkGetResultDocument.from_dict(bulk_get_result_document_model_json) assert bulk_get_result_document_model != False # Construct a model instance of BulkGetResultDocument by calling from_dict on the json representation bulk_get_result_document_model_dict = BulkGetResultDocument.from_dict(bulk_get_result_document_model_json).__dict__ bulk_get_result_document_model2 = BulkGetResultDocument(**bulk_get_result_document_model_dict) # Verify the model instances are equivalent assert bulk_get_result_document_model == bulk_get_result_document_model2 # Convert model instance back to dict and verify no loss of data bulk_get_result_document_model_json2 = bulk_get_result_document_model.to_dict() assert bulk_get_result_document_model_json2 == bulk_get_result_document_model_json class TestModel_BulkGetResultItem(): """ Test Class for BulkGetResultItem """ def test_bulk_get_result_item_serialization(self): """ Test serialization/deserialization for BulkGetResultItem """ # Construct dict forms of any model objects needed in order to build this model. document_result_model = {} # DocumentResult document_result_model['id'] = 'testString' document_result_model['rev'] = 'testString' document_result_model['ok'] = True document_result_model['caused_by'] = 'testString' document_result_model['error'] = 'testString' document_result_model['reason'] = 'testString' attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' bulk_get_result_document_model = {} # BulkGetResultDocument bulk_get_result_document_model['error'] = document_result_model bulk_get_result_document_model['ok'] = document_model # Construct a json representation of a BulkGetResultItem model bulk_get_result_item_model_json = {} bulk_get_result_item_model_json['docs'] = [bulk_get_result_document_model] bulk_get_result_item_model_json['id'] = 'testString' # Construct a model instance of BulkGetResultItem by calling from_dict on the json representation bulk_get_result_item_model = BulkGetResultItem.from_dict(bulk_get_result_item_model_json) assert bulk_get_result_item_model != False # Construct a model instance of BulkGetResultItem by calling from_dict on the json representation bulk_get_result_item_model_dict = BulkGetResultItem.from_dict(bulk_get_result_item_model_json).__dict__ bulk_get_result_item_model2 = BulkGetResultItem(**bulk_get_result_item_model_dict) # Verify the model instances are equivalent assert bulk_get_result_item_model == bulk_get_result_item_model2 # Convert model instance back to dict and verify no loss of data bulk_get_result_item_model_json2 = bulk_get_result_item_model.to_dict() assert bulk_get_result_item_model_json2 == bulk_get_result_item_model_json class TestModel_CapacityThroughputInformation(): """ Test Class for CapacityThroughputInformation """ def test_capacity_throughput_information_serialization(self): """ Test serialization/deserialization for CapacityThroughputInformation """ # Construct dict forms of any model objects needed in order to build this model. throughput_information_model = {} # ThroughputInformation throughput_information_model['blocks'] = 0 throughput_information_model['query'] = 0 throughput_information_model['read'] = 0 throughput_information_model['write'] = 0 capacity_throughput_information_current_model = {} # CapacityThroughputInformationCurrent capacity_throughput_information_current_model['throughput'] = throughput_information_model capacity_throughput_information_target_model = {} # CapacityThroughputInformationTarget capacity_throughput_information_target_model['throughput'] = throughput_information_model # Construct a json representation of a CapacityThroughputInformation model capacity_throughput_information_model_json = {} capacity_throughput_information_model_json['current'] = capacity_throughput_information_current_model capacity_throughput_information_model_json['target'] = capacity_throughput_information_target_model # Construct a model instance of CapacityThroughputInformation by calling from_dict on the json representation capacity_throughput_information_model = CapacityThroughputInformation.from_dict(capacity_throughput_information_model_json) assert capacity_throughput_information_model != False # Construct a model instance of CapacityThroughputInformation by calling from_dict on the json representation capacity_throughput_information_model_dict = CapacityThroughputInformation.from_dict(capacity_throughput_information_model_json).__dict__ capacity_throughput_information_model2 = CapacityThroughputInformation(**capacity_throughput_information_model_dict) # Verify the model instances are equivalent assert capacity_throughput_information_model == capacity_throughput_information_model2 # Convert model instance back to dict and verify no loss of data capacity_throughput_information_model_json2 = capacity_throughput_information_model.to_dict() assert capacity_throughput_information_model_json2 == capacity_throughput_information_model_json class TestModel_CapacityThroughputInformationCurrent(): """ Test Class for CapacityThroughputInformationCurrent """ def test_capacity_throughput_information_current_serialization(self): """ Test serialization/deserialization for CapacityThroughputInformationCurrent """ # Construct dict forms of any model objects needed in order to build this model. throughput_information_model = {} # ThroughputInformation throughput_information_model['blocks'] = 0 throughput_information_model['query'] = 0 throughput_information_model['read'] = 0 throughput_information_model['write'] = 0 # Construct a json representation of a CapacityThroughputInformationCurrent model capacity_throughput_information_current_model_json = {} capacity_throughput_information_current_model_json['throughput'] = throughput_information_model # Construct a model instance of CapacityThroughputInformationCurrent by calling from_dict on the json representation capacity_throughput_information_current_model = CapacityThroughputInformationCurrent.from_dict(capacity_throughput_information_current_model_json) assert capacity_throughput_information_current_model != False # Construct a model instance of CapacityThroughputInformationCurrent by calling from_dict on the json representation capacity_throughput_information_current_model_dict = CapacityThroughputInformationCurrent.from_dict(capacity_throughput_information_current_model_json).__dict__ capacity_throughput_information_current_model2 = CapacityThroughputInformationCurrent(**capacity_throughput_information_current_model_dict) # Verify the model instances are equivalent assert capacity_throughput_information_current_model == capacity_throughput_information_current_model2 # Convert model instance back to dict and verify no loss of data capacity_throughput_information_current_model_json2 = capacity_throughput_information_current_model.to_dict() assert capacity_throughput_information_current_model_json2 == capacity_throughput_information_current_model_json class TestModel_CapacityThroughputInformationTarget(): """ Test Class for CapacityThroughputInformationTarget """ def test_capacity_throughput_information_target_serialization(self): """ Test serialization/deserialization for CapacityThroughputInformationTarget """ # Construct dict forms of any model objects needed in order to build this model. throughput_information_model = {} # ThroughputInformation throughput_information_model['blocks'] = 0 throughput_information_model['query'] = 0 throughput_information_model['read'] = 0 throughput_information_model['write'] = 0 # Construct a json representation of a CapacityThroughputInformationTarget model capacity_throughput_information_target_model_json = {} capacity_throughput_information_target_model_json['throughput'] = throughput_information_model # Construct a model instance of CapacityThroughputInformationTarget by calling from_dict on the json representation capacity_throughput_information_target_model = CapacityThroughputInformationTarget.from_dict(capacity_throughput_information_target_model_json) assert capacity_throughput_information_target_model != False # Construct a model instance of CapacityThroughputInformationTarget by calling from_dict on the json representation capacity_throughput_information_target_model_dict = CapacityThroughputInformationTarget.from_dict(capacity_throughput_information_target_model_json).__dict__ capacity_throughput_information_target_model2 = CapacityThroughputInformationTarget(**capacity_throughput_information_target_model_dict) # Verify the model instances are equivalent assert capacity_throughput_information_target_model == capacity_throughput_information_target_model2 # Convert model instance back to dict and verify no loss of data capacity_throughput_information_target_model_json2 = capacity_throughput_information_target_model.to_dict() assert capacity_throughput_information_target_model_json2 == capacity_throughput_information_target_model_json class TestModel_Change(): """ Test Class for Change """ def test_change_serialization(self): """ Test serialization/deserialization for Change """ # Construct a json representation of a Change model change_model_json = {} change_model_json['rev'] = 'testString' # Construct a model instance of Change by calling from_dict on the json representation change_model = Change.from_dict(change_model_json) assert change_model != False # Construct a model instance of Change by calling from_dict on the json representation change_model_dict = Change.from_dict(change_model_json).__dict__ change_model2 = Change(**change_model_dict) # Verify the model instances are equivalent assert change_model == change_model2 # Convert model instance back to dict and verify no loss of data change_model_json2 = change_model.to_dict() assert change_model_json2 == change_model_json class TestModel_ChangesResult(): """ Test Class for ChangesResult """ def test_changes_result_serialization(self): """ Test serialization/deserialization for ChangesResult """ # Construct dict forms of any model objects needed in order to build this model. change_model = {} # Change change_model['rev'] = 'testString' attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' changes_result_item_model = {} # ChangesResultItem changes_result_item_model['changes'] = [change_model] changes_result_item_model['deleted'] = True changes_result_item_model['doc'] = document_model changes_result_item_model['id'] = 'testString' changes_result_item_model['seq'] = 'testString' # Construct a json representation of a ChangesResult model changes_result_model_json = {} changes_result_model_json['last_seq'] = 'testString' changes_result_model_json['pending'] = 26 changes_result_model_json['results'] = [changes_result_item_model] # Construct a model instance of ChangesResult by calling from_dict on the json representation changes_result_model = ChangesResult.from_dict(changes_result_model_json) assert changes_result_model != False # Construct a model instance of ChangesResult by calling from_dict on the json representation changes_result_model_dict = ChangesResult.from_dict(changes_result_model_json).__dict__ changes_result_model2 = ChangesResult(**changes_result_model_dict) # Verify the model instances are equivalent assert changes_result_model == changes_result_model2 # Convert model instance back to dict and verify no loss of data changes_result_model_json2 = changes_result_model.to_dict() assert changes_result_model_json2 == changes_result_model_json class TestModel_ChangesResultItem(): """ Test Class for ChangesResultItem """ def test_changes_result_item_serialization(self): """ Test serialization/deserialization for ChangesResultItem """ # Construct dict forms of any model objects needed in order to build this model. change_model = {} # Change change_model['rev'] = 'testString' attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' # Construct a json representation of a ChangesResultItem model changes_result_item_model_json = {} changes_result_item_model_json['changes'] = [change_model] changes_result_item_model_json['deleted'] = True changes_result_item_model_json['doc'] = document_model changes_result_item_model_json['id'] = 'testString' changes_result_item_model_json['seq'] = 'testString' # Construct a model instance of ChangesResultItem by calling from_dict on the json representation changes_result_item_model = ChangesResultItem.from_dict(changes_result_item_model_json) assert changes_result_item_model != False # Construct a model instance of ChangesResultItem by calling from_dict on the json representation changes_result_item_model_dict = ChangesResultItem.from_dict(changes_result_item_model_json).__dict__ changes_result_item_model2 = ChangesResultItem(**changes_result_item_model_dict) # Verify the model instances are equivalent assert changes_result_item_model == changes_result_item_model2 # Convert model instance back to dict and verify no loss of data changes_result_item_model_json2 = changes_result_item_model.to_dict() assert changes_result_item_model_json2 == changes_result_item_model_json class TestModel_ContentInformationSizes(): """ Test Class for ContentInformationSizes """ def test_content_information_sizes_serialization(self): """ Test serialization/deserialization for ContentInformationSizes """ # Construct a json representation of a ContentInformationSizes model content_information_sizes_model_json = {} content_information_sizes_model_json['active'] = 26 content_information_sizes_model_json['external'] = 26 content_information_sizes_model_json['file'] = 26 # Construct a model instance of ContentInformationSizes by calling from_dict on the json representation content_information_sizes_model = ContentInformationSizes.from_dict(content_information_sizes_model_json) assert content_information_sizes_model != False # Construct a model instance of ContentInformationSizes by calling from_dict on the json representation content_information_sizes_model_dict = ContentInformationSizes.from_dict(content_information_sizes_model_json).__dict__ content_information_sizes_model2 = ContentInformationSizes(**content_information_sizes_model_dict) # Verify the model instances are equivalent assert content_information_sizes_model == content_information_sizes_model2 # Convert model instance back to dict and verify no loss of data content_information_sizes_model_json2 = content_information_sizes_model.to_dict() assert content_information_sizes_model_json2 == content_information_sizes_model_json class TestModel_CorsInformation(): """ Test Class for CorsInformation """ def test_cors_information_serialization(self): """ Test serialization/deserialization for CorsInformation """ # Construct a json representation of a CorsInformation model cors_information_model_json = {} cors_information_model_json['allow_credentials'] = True cors_information_model_json['enable_cors'] = True cors_information_model_json['origins'] = ['testString'] # Construct a model instance of CorsInformation by calling from_dict on the json representation cors_information_model = CorsInformation.from_dict(cors_information_model_json) assert cors_information_model != False # Construct a model instance of CorsInformation by calling from_dict on the json representation cors_information_model_dict = CorsInformation.from_dict(cors_information_model_json).__dict__ cors_information_model2 = CorsInformation(**cors_information_model_dict) # Verify the model instances are equivalent assert cors_information_model == cors_information_model2 # Convert model instance back to dict and verify no loss of data cors_information_model_json2 = cors_information_model.to_dict() assert cors_information_model_json2 == cors_information_model_json class TestModel_CurrentThroughputInformation(): """ Test Class for CurrentThroughputInformation """ def test_current_throughput_information_serialization(self): """ Test serialization/deserialization for CurrentThroughputInformation """ # Construct dict forms of any model objects needed in order to build this model. current_throughput_information_throughput_model = {} # CurrentThroughputInformationThroughput current_throughput_information_throughput_model['query'] = 0 current_throughput_information_throughput_model['read'] = 0 current_throughput_information_throughput_model['write'] = 0 # Construct a json representation of a CurrentThroughputInformation model current_throughput_information_model_json = {} current_throughput_information_model_json['throughput'] = current_throughput_information_throughput_model # Construct a model instance of CurrentThroughputInformation by calling from_dict on the json representation current_throughput_information_model = CurrentThroughputInformation.from_dict(current_throughput_information_model_json) assert current_throughput_information_model != False # Construct a model instance of CurrentThroughputInformation by calling from_dict on the json representation current_throughput_information_model_dict = CurrentThroughputInformation.from_dict(current_throughput_information_model_json).__dict__ current_throughput_information_model2 = CurrentThroughputInformation(**current_throughput_information_model_dict) # Verify the model instances are equivalent assert current_throughput_information_model == current_throughput_information_model2 # Convert model instance back to dict and verify no loss of data current_throughput_information_model_json2 = current_throughput_information_model.to_dict() assert current_throughput_information_model_json2 == current_throughput_information_model_json class TestModel_CurrentThroughputInformationThroughput(): """ Test Class for CurrentThroughputInformationThroughput """ def test_current_throughput_information_throughput_serialization(self): """ Test serialization/deserialization for CurrentThroughputInformationThroughput """ # Construct a json representation of a CurrentThroughputInformationThroughput model current_throughput_information_throughput_model_json = {} current_throughput_information_throughput_model_json['query'] = 0 current_throughput_information_throughput_model_json['read'] = 0 current_throughput_information_throughput_model_json['write'] = 0 # Construct a model instance of CurrentThroughputInformationThroughput by calling from_dict on the json representation current_throughput_information_throughput_model = CurrentThroughputInformationThroughput.from_dict(current_throughput_information_throughput_model_json) assert current_throughput_information_throughput_model != False # Construct a model instance of CurrentThroughputInformationThroughput by calling from_dict on the json representation current_throughput_information_throughput_model_dict = CurrentThroughputInformationThroughput.from_dict(current_throughput_information_throughput_model_json).__dict__ current_throughput_information_throughput_model2 = CurrentThroughputInformationThroughput(**current_throughput_information_throughput_model_dict) # Verify the model instances are equivalent assert current_throughput_information_throughput_model == current_throughput_information_throughput_model2 # Convert model instance back to dict and verify no loss of data current_throughput_information_throughput_model_json2 = current_throughput_information_throughput_model.to_dict() assert current_throughput_information_throughput_model_json2 == current_throughput_information_throughput_model_json class TestModel_DatabaseInformation(): """ Test Class for DatabaseInformation """ def test_database_information_serialization(self): """ Test serialization/deserialization for DatabaseInformation """ # Construct dict forms of any model objects needed in order to build this model. database_information_cluster_model = {} # DatabaseInformationCluster database_information_cluster_model['n'] = 1 database_information_cluster_model['q'] = 1 database_information_cluster_model['r'] = 1 database_information_cluster_model['w'] = 1 database_information_props_model = {} # DatabaseInformationProps database_information_props_model['partitioned'] = True content_information_sizes_model = {} # ContentInformationSizes content_information_sizes_model['active'] = 26 content_information_sizes_model['external'] = 26 content_information_sizes_model['file'] = 26 # Construct a json representation of a DatabaseInformation model database_information_model_json = {} database_information_model_json['cluster'] = database_information_cluster_model database_information_model_json['committed_update_seq'] = 'testString' database_information_model_json['compact_running'] = True database_information_model_json['compacted_seq'] = 'testString' database_information_model_json['db_name'] = 'testString' database_information_model_json['disk_format_version'] = 26 database_information_model_json['doc_count'] = 0 database_information_model_json['doc_del_count'] = 0 database_information_model_json['engine'] = 'testString' database_information_model_json['props'] = database_information_props_model database_information_model_json['sizes'] = content_information_sizes_model database_information_model_json['update_seq'] = 'testString' database_information_model_json['uuid'] = 'testString' # Construct a model instance of DatabaseInformation by calling from_dict on the json representation database_information_model = DatabaseInformation.from_dict(database_information_model_json) assert database_information_model != False # Construct a model instance of DatabaseInformation by calling from_dict on the json representation database_information_model_dict = DatabaseInformation.from_dict(database_information_model_json).__dict__ database_information_model2 = DatabaseInformation(**database_information_model_dict) # Verify the model instances are equivalent assert database_information_model == database_information_model2 # Convert model instance back to dict and verify no loss of data database_information_model_json2 = database_information_model.to_dict() assert database_information_model_json2 == database_information_model_json class TestModel_DatabaseInformationCluster(): """ Test Class for DatabaseInformationCluster """ def test_database_information_cluster_serialization(self): """ Test serialization/deserialization for DatabaseInformationCluster """ # Construct a json representation of a DatabaseInformationCluster model database_information_cluster_model_json = {} database_information_cluster_model_json['n'] = 1 database_information_cluster_model_json['q'] = 1 database_information_cluster_model_json['r'] = 1 database_information_cluster_model_json['w'] = 1 # Construct a model instance of DatabaseInformationCluster by calling from_dict on the json representation database_information_cluster_model = DatabaseInformationCluster.from_dict(database_information_cluster_model_json) assert database_information_cluster_model != False # Construct a model instance of DatabaseInformationCluster by calling from_dict on the json representation database_information_cluster_model_dict = DatabaseInformationCluster.from_dict(database_information_cluster_model_json).__dict__ database_information_cluster_model2 = DatabaseInformationCluster(**database_information_cluster_model_dict) # Verify the model instances are equivalent assert database_information_cluster_model == database_information_cluster_model2 # Convert model instance back to dict and verify no loss of data database_information_cluster_model_json2 = database_information_cluster_model.to_dict() assert database_information_cluster_model_json2 == database_information_cluster_model_json class TestModel_DatabaseInformationProps(): """ Test Class for DatabaseInformationProps """ def test_database_information_props_serialization(self): """ Test serialization/deserialization for DatabaseInformationProps """ # Construct a json representation of a DatabaseInformationProps model database_information_props_model_json = {} database_information_props_model_json['partitioned'] = True # Construct a model instance of DatabaseInformationProps by calling from_dict on the json representation database_information_props_model = DatabaseInformationProps.from_dict(database_information_props_model_json) assert database_information_props_model != False # Construct a model instance of DatabaseInformationProps by calling from_dict on the json representation database_information_props_model_dict = DatabaseInformationProps.from_dict(database_information_props_model_json).__dict__ database_information_props_model2 = DatabaseInformationProps(**database_information_props_model_dict) # Verify the model instances are equivalent assert database_information_props_model == database_information_props_model2 # Convert model instance back to dict and verify no loss of data database_information_props_model_json2 = database_information_props_model.to_dict() assert database_information_props_model_json2 == database_information_props_model_json class TestModel_DbEvent(): """ Test Class for DbEvent """ def test_db_event_serialization(self): """ Test serialization/deserialization for DbEvent """ # Construct a json representation of a DbEvent model db_event_model_json = {} db_event_model_json['account'] = 'testString' db_event_model_json['db_name'] = 'testString' db_event_model_json['seq'] = 'testString' db_event_model_json['type'] = 'created' # Construct a model instance of DbEvent by calling from_dict on the json representation db_event_model = DbEvent.from_dict(db_event_model_json) assert db_event_model != False # Construct a model instance of DbEvent by calling from_dict on the json representation db_event_model_dict = DbEvent.from_dict(db_event_model_json).__dict__ db_event_model2 = DbEvent(**db_event_model_dict) # Verify the model instances are equivalent assert db_event_model == db_event_model2 # Convert model instance back to dict and verify no loss of data db_event_model_json2 = db_event_model.to_dict() assert db_event_model_json2 == db_event_model_json class TestModel_DbUpdates(): """ Test Class for DbUpdates """ def test_db_updates_serialization(self): """ Test serialization/deserialization for DbUpdates """ # Construct dict forms of any model objects needed in order to build this model. db_event_model = {} # DbEvent db_event_model['account'] = 'testString' db_event_model['db_name'] = 'testString' db_event_model['seq'] = 'testString' db_event_model['type'] = 'created' # Construct a json representation of a DbUpdates model db_updates_model_json = {} db_updates_model_json['last_seq'] = 'testString' db_updates_model_json['results'] = [db_event_model] # Construct a model instance of DbUpdates by calling from_dict on the json representation db_updates_model = DbUpdates.from_dict(db_updates_model_json) assert db_updates_model != False # Construct a model instance of DbUpdates by calling from_dict on the json representation db_updates_model_dict = DbUpdates.from_dict(db_updates_model_json).__dict__ db_updates_model2 = DbUpdates(**db_updates_model_dict) # Verify the model instances are equivalent assert db_updates_model == db_updates_model2 # Convert model instance back to dict and verify no loss of data db_updates_model_json2 = db_updates_model.to_dict() assert db_updates_model_json2 == db_updates_model_json class TestModel_DbsInfoResult(): """ Test Class for DbsInfoResult """ def test_dbs_info_result_serialization(self): """ Test serialization/deserialization for DbsInfoResult """ # Construct dict forms of any model objects needed in order to build this model. database_information_cluster_model = {} # DatabaseInformationCluster database_information_cluster_model['n'] = 1 database_information_cluster_model['q'] = 1 database_information_cluster_model['r'] = 1 database_information_cluster_model['w'] = 1 database_information_props_model = {} # DatabaseInformationProps database_information_props_model['partitioned'] = True content_information_sizes_model = {} # ContentInformationSizes content_information_sizes_model['active'] = 26 content_information_sizes_model['external'] = 26 content_information_sizes_model['file'] = 26 database_information_model = {} # DatabaseInformation database_information_model['cluster'] = database_information_cluster_model database_information_model['committed_update_seq'] = 'testString' database_information_model['compact_running'] = True database_information_model['compacted_seq'] = 'testString' database_information_model['db_name'] = 'testString' database_information_model['disk_format_version'] = 26 database_information_model['doc_count'] = 0 database_information_model['doc_del_count'] = 0 database_information_model['engine'] = 'testString' database_information_model['props'] = database_information_props_model database_information_model['sizes'] = content_information_sizes_model database_information_model['update_seq'] = 'testString' database_information_model['uuid'] = 'testString' # Construct a json representation of a DbsInfoResult model dbs_info_result_model_json = {} dbs_info_result_model_json['error'] = 'testString' dbs_info_result_model_json['info'] = database_information_model dbs_info_result_model_json['key'] = 'testString' # Construct a model instance of DbsInfoResult by calling from_dict on the json representation dbs_info_result_model = DbsInfoResult.from_dict(dbs_info_result_model_json) assert dbs_info_result_model != False # Construct a model instance of DbsInfoResult by calling from_dict on the json representation dbs_info_result_model_dict = DbsInfoResult.from_dict(dbs_info_result_model_json).__dict__ dbs_info_result_model2 = DbsInfoResult(**dbs_info_result_model_dict) # Verify the model instances are equivalent assert dbs_info_result_model == dbs_info_result_model2 # Convert model instance back to dict and verify no loss of data dbs_info_result_model_json2 = dbs_info_result_model.to_dict() assert dbs_info_result_model_json2 == dbs_info_result_model_json class TestModel_DesignDocument(): """ Test Class for DesignDocument """ def test_design_document_serialization(self): """ Test serialization/deserialization for DesignDocument """ # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' analyzer_model = {} # Analyzer analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] analyzer_configuration_model = {} # AnalyzerConfiguration analyzer_configuration_model['name'] = 'classic' analyzer_configuration_model['stopwords'] = ['testString'] analyzer_configuration_model['fields'] = {} search_index_definition_model = {} # SearchIndexDefinition search_index_definition_model['analyzer'] = analyzer_configuration_model search_index_definition_model['index'] = 'testString' design_document_options_model = {} # DesignDocumentOptions design_document_options_model['partitioned'] = True design_document_views_map_reduce_model = {} # DesignDocumentViewsMapReduce design_document_views_map_reduce_model['map'] = 'testString' design_document_views_map_reduce_model['reduce'] = 'testString' geo_index_definition_model = {} # GeoIndexDefinition geo_index_definition_model['index'] = 'testString' # Construct a json representation of a DesignDocument model design_document_model_json = {} design_document_model_json['_attachments'] = {} design_document_model_json['_conflicts'] = ['testString'] design_document_model_json['_deleted'] = True design_document_model_json['_deleted_conflicts'] = ['testString'] design_document_model_json['_id'] = 'testString' design_document_model_json['_local_seq'] = 'testString' design_document_model_json['_rev'] = 'testString' design_document_model_json['_revisions'] = revisions_model design_document_model_json['_revs_info'] = [document_revision_status_model] design_document_model_json['autoupdate'] = True design_document_model_json['filters'] = {} design_document_model_json['indexes'] = {} design_document_model_json['language'] = 'javascript' design_document_model_json['options'] = design_document_options_model design_document_model_json['validate_doc_update'] = 'testString' design_document_model_json['views'] = {} design_document_model_json['st_indexes'] = {} design_document_model_json['foo'] = 'testString' # Construct a model instance of DesignDocument by calling from_dict on the json representation design_document_model = DesignDocument.from_dict(design_document_model_json) assert design_document_model != False # Construct a model instance of DesignDocument by calling from_dict on the json representation design_document_model_dict = DesignDocument.from_dict(design_document_model_json).__dict__ design_document_model2 = DesignDocument(**design_document_model_dict) # Verify the model instances are equivalent assert design_document_model == design_document_model2 # Convert model instance back to dict and verify no loss of data design_document_model_json2 = design_document_model.to_dict() assert design_document_model_json2 == design_document_model_json # Test get_properties and set_properties methods. design_document_model.set_properties({}) actual_dict = design_document_model.get_properties() assert actual_dict == {} expected_dict = {'foo': 'testString'} design_document_model.set_properties(expected_dict) actual_dict = design_document_model.get_properties() assert actual_dict == expected_dict class TestModel_DesignDocumentInformation(): """ Test Class for DesignDocumentInformation """ def test_design_document_information_serialization(self): """ Test serialization/deserialization for DesignDocumentInformation """ # Construct dict forms of any model objects needed in order to build this model. content_information_sizes_model = {} # ContentInformationSizes content_information_sizes_model['active'] = 26 content_information_sizes_model['external'] = 26 content_information_sizes_model['file'] = 26 design_document_view_index_model = {} # DesignDocumentViewIndex design_document_view_index_model['compact_running'] = True design_document_view_index_model['language'] = 'testString' design_document_view_index_model['signature'] = 'testString' design_document_view_index_model['sizes'] = content_information_sizes_model design_document_view_index_model['updater_running'] = True design_document_view_index_model['waiting_clients'] = 0 design_document_view_index_model['waiting_commit'] = True # Construct a json representation of a DesignDocumentInformation model design_document_information_model_json = {} design_document_information_model_json['name'] = 'testString' design_document_information_model_json['view_index'] = design_document_view_index_model # Construct a model instance of DesignDocumentInformation by calling from_dict on the json representation design_document_information_model = DesignDocumentInformation.from_dict(design_document_information_model_json) assert design_document_information_model != False # Construct a model instance of DesignDocumentInformation by calling from_dict on the json representation design_document_information_model_dict = DesignDocumentInformation.from_dict(design_document_information_model_json).__dict__ design_document_information_model2 = DesignDocumentInformation(**design_document_information_model_dict) # Verify the model instances are equivalent assert design_document_information_model == design_document_information_model2 # Convert model instance back to dict and verify no loss of data design_document_information_model_json2 = design_document_information_model.to_dict() assert design_document_information_model_json2 == design_document_information_model_json class TestModel_DesignDocumentOptions(): """ Test Class for DesignDocumentOptions """ def test_design_document_options_serialization(self): """ Test serialization/deserialization for DesignDocumentOptions """ # Construct a json representation of a DesignDocumentOptions model design_document_options_model_json = {} design_document_options_model_json['partitioned'] = True # Construct a model instance of DesignDocumentOptions by calling from_dict on the json representation design_document_options_model = DesignDocumentOptions.from_dict(design_document_options_model_json) assert design_document_options_model != False # Construct a model instance of DesignDocumentOptions by calling from_dict on the json representation design_document_options_model_dict = DesignDocumentOptions.from_dict(design_document_options_model_json).__dict__ design_document_options_model2 = DesignDocumentOptions(**design_document_options_model_dict) # Verify the model instances are equivalent assert design_document_options_model == design_document_options_model2 # Convert model instance back to dict and verify no loss of data design_document_options_model_json2 = design_document_options_model.to_dict() assert design_document_options_model_json2 == design_document_options_model_json class TestModel_DesignDocumentViewIndex(): """ Test Class for DesignDocumentViewIndex """ def test_design_document_view_index_serialization(self): """ Test serialization/deserialization for DesignDocumentViewIndex """ # Construct dict forms of any model objects needed in order to build this model. content_information_sizes_model = {} # ContentInformationSizes content_information_sizes_model['active'] = 26 content_information_sizes_model['external'] = 26 content_information_sizes_model['file'] = 26 # Construct a json representation of a DesignDocumentViewIndex model design_document_view_index_model_json = {} design_document_view_index_model_json['compact_running'] = True design_document_view_index_model_json['language'] = 'testString' design_document_view_index_model_json['signature'] = 'testString' design_document_view_index_model_json['sizes'] = content_information_sizes_model design_document_view_index_model_json['updater_running'] = True design_document_view_index_model_json['waiting_clients'] = 0 design_document_view_index_model_json['waiting_commit'] = True # Construct a model instance of DesignDocumentViewIndex by calling from_dict on the json representation design_document_view_index_model = DesignDocumentViewIndex.from_dict(design_document_view_index_model_json) assert design_document_view_index_model != False # Construct a model instance of DesignDocumentViewIndex by calling from_dict on the json representation design_document_view_index_model_dict = DesignDocumentViewIndex.from_dict(design_document_view_index_model_json).__dict__ design_document_view_index_model2 = DesignDocumentViewIndex(**design_document_view_index_model_dict) # Verify the model instances are equivalent assert design_document_view_index_model == design_document_view_index_model2 # Convert model instance back to dict and verify no loss of data design_document_view_index_model_json2 = design_document_view_index_model.to_dict() assert design_document_view_index_model_json2 == design_document_view_index_model_json class TestModel_DesignDocumentViewsMapReduce(): """ Test Class for DesignDocumentViewsMapReduce """ def test_design_document_views_map_reduce_serialization(self): """ Test serialization/deserialization for DesignDocumentViewsMapReduce """ # Construct a json representation of a DesignDocumentViewsMapReduce model design_document_views_map_reduce_model_json = {} design_document_views_map_reduce_model_json['map'] = 'testString' design_document_views_map_reduce_model_json['reduce'] = 'testString' # Construct a model instance of DesignDocumentViewsMapReduce by calling from_dict on the json representation design_document_views_map_reduce_model = DesignDocumentViewsMapReduce.from_dict(design_document_views_map_reduce_model_json) assert design_document_views_map_reduce_model != False # Construct a model instance of DesignDocumentViewsMapReduce by calling from_dict on the json representation design_document_views_map_reduce_model_dict = DesignDocumentViewsMapReduce.from_dict(design_document_views_map_reduce_model_json).__dict__ design_document_views_map_reduce_model2 = DesignDocumentViewsMapReduce(**design_document_views_map_reduce_model_dict) # Verify the model instances are equivalent assert design_document_views_map_reduce_model == design_document_views_map_reduce_model2 # Convert model instance back to dict and verify no loss of data design_document_views_map_reduce_model_json2 = design_document_views_map_reduce_model.to_dict() assert design_document_views_map_reduce_model_json2 == design_document_views_map_reduce_model_json class TestModel_DocsResultRow(): """ Test Class for DocsResultRow """ def test_docs_result_row_serialization(self): """ Test serialization/deserialization for DocsResultRow """ # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' docs_result_row_value_model = {} # DocsResultRowValue docs_result_row_value_model['rev'] = 'testString' # Construct a json representation of a DocsResultRow model docs_result_row_model_json = {} docs_result_row_model_json['caused_by'] = 'testString' docs_result_row_model_json['error'] = 'testString' docs_result_row_model_json['reason'] = 'testString' docs_result_row_model_json['doc'] = document_model docs_result_row_model_json['id'] = 'testString' docs_result_row_model_json['key'] = 'testString' docs_result_row_model_json['value'] = docs_result_row_value_model # Construct a model instance of DocsResultRow by calling from_dict on the json representation docs_result_row_model = DocsResultRow.from_dict(docs_result_row_model_json) assert docs_result_row_model != False # Construct a model instance of DocsResultRow by calling from_dict on the json representation docs_result_row_model_dict = DocsResultRow.from_dict(docs_result_row_model_json).__dict__ docs_result_row_model2 = DocsResultRow(**docs_result_row_model_dict) # Verify the model instances are equivalent assert docs_result_row_model == docs_result_row_model2 # Convert model instance back to dict and verify no loss of data docs_result_row_model_json2 = docs_result_row_model.to_dict() assert docs_result_row_model_json2 == docs_result_row_model_json class TestModel_DocsResultRowValue(): """ Test Class for DocsResultRowValue """ def test_docs_result_row_value_serialization(self): """ Test serialization/deserialization for DocsResultRowValue """ # Construct a json representation of a DocsResultRowValue model docs_result_row_value_model_json = {} docs_result_row_value_model_json['rev'] = 'testString' # Construct a model instance of DocsResultRowValue by calling from_dict on the json representation docs_result_row_value_model = DocsResultRowValue.from_dict(docs_result_row_value_model_json) assert docs_result_row_value_model != False # Construct a model instance of DocsResultRowValue by calling from_dict on the json representation docs_result_row_value_model_dict = DocsResultRowValue.from_dict(docs_result_row_value_model_json).__dict__ docs_result_row_value_model2 = DocsResultRowValue(**docs_result_row_value_model_dict) # Verify the model instances are equivalent assert docs_result_row_value_model == docs_result_row_value_model2 # Convert model instance back to dict and verify no loss of data docs_result_row_value_model_json2 = docs_result_row_value_model.to_dict() assert docs_result_row_value_model_json2 == docs_result_row_value_model_json class TestModel_Document(): """ Test Class for Document """ def test_document_serialization(self): """ Test serialization/deserialization for Document """ # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a json representation of a Document model document_model_json = {} document_model_json['_attachments'] = {} document_model_json['_conflicts'] = ['testString'] document_model_json['_deleted'] = True document_model_json['_deleted_conflicts'] = ['testString'] document_model_json['_id'] = 'testString' document_model_json['_local_seq'] = 'testString' document_model_json['_rev'] = 'testString' document_model_json['_revisions'] = revisions_model document_model_json['_revs_info'] = [document_revision_status_model] document_model_json['foo'] = 'testString' # Construct a model instance of Document by calling from_dict on the json representation document_model = Document.from_dict(document_model_json) assert document_model != False # Construct a model instance of Document by calling from_dict on the json representation document_model_dict = Document.from_dict(document_model_json).__dict__ document_model2 = Document(**document_model_dict) # Verify the model instances are equivalent assert document_model == document_model2 # Convert model instance back to dict and verify no loss of data document_model_json2 = document_model.to_dict() assert document_model_json2 == document_model_json # Test get_properties and set_properties methods. document_model.set_properties({}) actual_dict = document_model.get_properties() assert actual_dict == {} expected_dict = {'foo': 'testString'} document_model.set_properties(expected_dict) actual_dict = document_model.get_properties() assert actual_dict == expected_dict class TestModel_DocumentResult(): """ Test Class for DocumentResult """ def test_document_result_serialization(self): """ Test serialization/deserialization for DocumentResult """ # Construct a json representation of a DocumentResult model document_result_model_json = {} document_result_model_json['id'] = 'testString' document_result_model_json['rev'] = 'testString' document_result_model_json['ok'] = True document_result_model_json['caused_by'] = 'testString' document_result_model_json['error'] = 'testString' document_result_model_json['reason'] = 'testString' # Construct a model instance of DocumentResult by calling from_dict on the json representation document_result_model = DocumentResult.from_dict(document_result_model_json) assert document_result_model != False # Construct a model instance of DocumentResult by calling from_dict on the json representation document_result_model_dict = DocumentResult.from_dict(document_result_model_json).__dict__ document_result_model2 = DocumentResult(**document_result_model_dict) # Verify the model instances are equivalent assert document_result_model == document_result_model2 # Convert model instance back to dict and verify no loss of data document_result_model_json2 = document_result_model.to_dict() assert document_result_model_json2 == document_result_model_json class TestModel_DocumentRevisionStatus(): """ Test Class for DocumentRevisionStatus """ def test_document_revision_status_serialization(self): """ Test serialization/deserialization for DocumentRevisionStatus """ # Construct a json representation of a DocumentRevisionStatus model document_revision_status_model_json = {} document_revision_status_model_json['rev'] = 'testString' document_revision_status_model_json['status'] = 'available' # Construct a model instance of DocumentRevisionStatus by calling from_dict on the json representation document_revision_status_model = DocumentRevisionStatus.from_dict(document_revision_status_model_json) assert document_revision_status_model != False # Construct a model instance of DocumentRevisionStatus by calling from_dict on the json representation document_revision_status_model_dict = DocumentRevisionStatus.from_dict(document_revision_status_model_json).__dict__ document_revision_status_model2 = DocumentRevisionStatus(**document_revision_status_model_dict) # Verify the model instances are equivalent assert document_revision_status_model == document_revision_status_model2 # Convert model instance back to dict and verify no loss of data document_revision_status_model_json2 = document_revision_status_model.to_dict() assert document_revision_status_model_json2 == document_revision_status_model_json class TestModel_DocumentShardInfo(): """ Test Class for DocumentShardInfo """ def test_document_shard_info_serialization(self): """ Test serialization/deserialization for DocumentShardInfo """ # Construct a json representation of a DocumentShardInfo model document_shard_info_model_json = {} document_shard_info_model_json['nodes'] = ['testString'] document_shard_info_model_json['range'] = 'testString' # Construct a model instance of DocumentShardInfo by calling from_dict on the json representation document_shard_info_model = DocumentShardInfo.from_dict(document_shard_info_model_json) assert document_shard_info_model != False # Construct a model instance of DocumentShardInfo by calling from_dict on the json representation document_shard_info_model_dict = DocumentShardInfo.from_dict(document_shard_info_model_json).__dict__ document_shard_info_model2 = DocumentShardInfo(**document_shard_info_model_dict) # Verify the model instances are equivalent assert document_shard_info_model == document_shard_info_model2 # Convert model instance back to dict and verify no loss of data document_shard_info_model_json2 = document_shard_info_model.to_dict() assert document_shard_info_model_json2 == document_shard_info_model_json class TestModel_ExecutionStats(): """ Test Class for ExecutionStats """ def test_execution_stats_serialization(self): """ Test serialization/deserialization for ExecutionStats """ # Construct a json representation of a ExecutionStats model execution_stats_model_json = {} execution_stats_model_json['execution_time_ms'] = 72.5 execution_stats_model_json['results_returned'] = 0 execution_stats_model_json['total_docs_examined'] = 0 execution_stats_model_json['total_keys_examined'] = 0 execution_stats_model_json['total_quorum_docs_examined'] = 0 # Construct a model instance of ExecutionStats by calling from_dict on the json representation execution_stats_model = ExecutionStats.from_dict(execution_stats_model_json) assert execution_stats_model != False # Construct a model instance of ExecutionStats by calling from_dict on the json representation execution_stats_model_dict = ExecutionStats.from_dict(execution_stats_model_json).__dict__ execution_stats_model2 = ExecutionStats(**execution_stats_model_dict) # Verify the model instances are equivalent assert execution_stats_model == execution_stats_model2 # Convert model instance back to dict and verify no loss of data execution_stats_model_json2 = execution_stats_model.to_dict() assert execution_stats_model_json2 == execution_stats_model_json class TestModel_ExplainResult(): """ Test Class for ExplainResult """ def test_explain_result_serialization(self): """ Test serialization/deserialization for ExplainResult """ # Construct dict forms of any model objects needed in order to build this model. analyzer_model = {} # Analyzer analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] index_text_operator_default_field_model = {} # IndexTextOperatorDefaultField index_text_operator_default_field_model['analyzer'] = analyzer_model index_text_operator_default_field_model['enabled'] = True index_field_model = {} # IndexField index_field_model['name'] = 'testString' index_field_model['type'] = 'boolean' index_field_model['foo'] = 'asc' index_definition_model = {} # IndexDefinition index_definition_model['default_analyzer'] = analyzer_model index_definition_model['default_field'] = index_text_operator_default_field_model index_definition_model['fields'] = [index_field_model] index_definition_model['index_array_lengths'] = True index_definition_model['partial_filter_selector'] = {} index_information_model = {} # IndexInformation index_information_model['ddoc'] = 'testString' index_information_model['def'] = index_definition_model index_information_model['name'] = 'testString' index_information_model['type'] = 'json' explain_result_range_model = {} # ExplainResultRange explain_result_range_model['end_key'] = ['testString'] explain_result_range_model['start_key'] = ['testString'] # Construct a json representation of a ExplainResult model explain_result_model_json = {} explain_result_model_json['dbname'] = 'testString' explain_result_model_json['fields'] = ['testString'] explain_result_model_json['index'] = index_information_model explain_result_model_json['limit'] = 0 explain_result_model_json['opts'] = {} explain_result_model_json['range'] = explain_result_range_model explain_result_model_json['selector'] = {} explain_result_model_json['skip'] = 0 # Construct a model instance of ExplainResult by calling from_dict on the json representation explain_result_model = ExplainResult.from_dict(explain_result_model_json) assert explain_result_model != False # Construct a model instance of ExplainResult by calling from_dict on the json representation explain_result_model_dict = ExplainResult.from_dict(explain_result_model_json).__dict__ explain_result_model2 = ExplainResult(**explain_result_model_dict) # Verify the model instances are equivalent assert explain_result_model == explain_result_model2 # Convert model instance back to dict and verify no loss of data explain_result_model_json2 = explain_result_model.to_dict() assert explain_result_model_json2 == explain_result_model_json class TestModel_ExplainResultRange(): """ Test Class for ExplainResultRange """ def test_explain_result_range_serialization(self): """ Test serialization/deserialization for ExplainResultRange """ # Construct a json representation of a ExplainResultRange model explain_result_range_model_json = {} explain_result_range_model_json['end_key'] = ['testString'] explain_result_range_model_json['start_key'] = ['testString'] # Construct a model instance of ExplainResultRange by calling from_dict on the json representation explain_result_range_model = ExplainResultRange.from_dict(explain_result_range_model_json) assert explain_result_range_model != False # Construct a model instance of ExplainResultRange by calling from_dict on the json representation explain_result_range_model_dict = ExplainResultRange.from_dict(explain_result_range_model_json).__dict__ explain_result_range_model2 = ExplainResultRange(**explain_result_range_model_dict) # Verify the model instances are equivalent assert explain_result_range_model == explain_result_range_model2 # Convert model instance back to dict and verify no loss of data explain_result_range_model_json2 = explain_result_range_model.to_dict() assert explain_result_range_model_json2 == explain_result_range_model_json class TestModel_FindResult(): """ Test Class for FindResult """ def test_find_result_serialization(self): """ Test serialization/deserialization for FindResult """ # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' execution_stats_model = {} # ExecutionStats execution_stats_model['execution_time_ms'] = 72.5 execution_stats_model['results_returned'] = 0 execution_stats_model['total_docs_examined'] = 0 execution_stats_model['total_keys_examined'] = 0 execution_stats_model['total_quorum_docs_examined'] = 0 # Construct a json representation of a FindResult model find_result_model_json = {} find_result_model_json['bookmark'] = 'testString' find_result_model_json['docs'] = [document_model] find_result_model_json['execution_stats'] = execution_stats_model find_result_model_json['warning'] = 'testString' # Construct a model instance of FindResult by calling from_dict on the json representation find_result_model = FindResult.from_dict(find_result_model_json) assert find_result_model != False # Construct a model instance of FindResult by calling from_dict on the json representation find_result_model_dict = FindResult.from_dict(find_result_model_json).__dict__ find_result_model2 = FindResult(**find_result_model_dict) # Verify the model instances are equivalent assert find_result_model == find_result_model2 # Convert model instance back to dict and verify no loss of data find_result_model_json2 = find_result_model.to_dict() assert find_result_model_json2 == find_result_model_json class TestModel_GeoIndexDefinition(): """ Test Class for GeoIndexDefinition """ def test_geo_index_definition_serialization(self): """ Test serialization/deserialization for GeoIndexDefinition """ # Construct a json representation of a GeoIndexDefinition model geo_index_definition_model_json = {} geo_index_definition_model_json['index'] = 'testString' # Construct a model instance of GeoIndexDefinition by calling from_dict on the json representation geo_index_definition_model = GeoIndexDefinition.from_dict(geo_index_definition_model_json) assert geo_index_definition_model != False # Construct a model instance of GeoIndexDefinition by calling from_dict on the json representation geo_index_definition_model_dict = GeoIndexDefinition.from_dict(geo_index_definition_model_json).__dict__ geo_index_definition_model2 = GeoIndexDefinition(**geo_index_definition_model_dict) # Verify the model instances are equivalent assert geo_index_definition_model == geo_index_definition_model2 # Convert model instance back to dict and verify no loss of data geo_index_definition_model_json2 = geo_index_definition_model.to_dict() assert geo_index_definition_model_json2 == geo_index_definition_model_json class TestModel_GeoIndexInformation(): """ Test Class for GeoIndexInformation """ def test_geo_index_information_serialization(self): """ Test serialization/deserialization for GeoIndexInformation """ # Construct dict forms of any model objects needed in order to build this model. geo_index_stats_model = {} # GeoIndexStats geo_index_stats_model['data_size'] = 0 geo_index_stats_model['disk_size'] = 0 geo_index_stats_model['doc_count'] = 0 # Construct a json representation of a GeoIndexInformation model geo_index_information_model_json = {} geo_index_information_model_json['geo_index'] = geo_index_stats_model geo_index_information_model_json['name'] = 'testString' # Construct a model instance of GeoIndexInformation by calling from_dict on the json representation geo_index_information_model = GeoIndexInformation.from_dict(geo_index_information_model_json) assert geo_index_information_model != False # Construct a model instance of GeoIndexInformation by calling from_dict on the json representation geo_index_information_model_dict = GeoIndexInformation.from_dict(geo_index_information_model_json).__dict__ geo_index_information_model2 = GeoIndexInformation(**geo_index_information_model_dict) # Verify the model instances are equivalent assert geo_index_information_model == geo_index_information_model2 # Convert model instance back to dict and verify no loss of data geo_index_information_model_json2 = geo_index_information_model.to_dict() assert geo_index_information_model_json2 == geo_index_information_model_json class TestModel_GeoIndexStats(): """ Test Class for GeoIndexStats """ def test_geo_index_stats_serialization(self): """ Test serialization/deserialization for GeoIndexStats """ # Construct a json representation of a GeoIndexStats model geo_index_stats_model_json = {} geo_index_stats_model_json['data_size'] = 0 geo_index_stats_model_json['disk_size'] = 0 geo_index_stats_model_json['doc_count'] = 0 # Construct a model instance of GeoIndexStats by calling from_dict on the json representation geo_index_stats_model = GeoIndexStats.from_dict(geo_index_stats_model_json) assert geo_index_stats_model != False # Construct a model instance of GeoIndexStats by calling from_dict on the json representation geo_index_stats_model_dict = GeoIndexStats.from_dict(geo_index_stats_model_json).__dict__ geo_index_stats_model2 = GeoIndexStats(**geo_index_stats_model_dict) # Verify the model instances are equivalent assert geo_index_stats_model == geo_index_stats_model2 # Convert model instance back to dict and verify no loss of data geo_index_stats_model_json2 = geo_index_stats_model.to_dict() assert geo_index_stats_model_json2 == geo_index_stats_model_json class TestModel_GeoJsonFeature(): """ Test Class for GeoJsonFeature """ def test_geo_json_feature_serialization(self): """ Test serialization/deserialization for GeoJsonFeature """ # Construct dict forms of any model objects needed in order to build this model. geo_json_geometry_object_model = {} # GeoJsonGeometry geo_json_geometry_object_model['type'] = 'Point' geo_json_geometry_object_model['coordinates'] = ['testString'] # Construct a json representation of a GeoJsonFeature model geo_json_feature_model_json = {} geo_json_feature_model_json['_id'] = 'testString' geo_json_feature_model_json['_rev'] = 'testString' geo_json_feature_model_json['bbox'] = [72.5] geo_json_feature_model_json['geometry'] = geo_json_geometry_object_model geo_json_feature_model_json['properties'] = {} geo_json_feature_model_json['type'] = 'Feature' geo_json_feature_model_json['foo'] = 'testString' # Construct a model instance of GeoJsonFeature by calling from_dict on the json representation geo_json_feature_model = GeoJsonFeature.from_dict(geo_json_feature_model_json) assert geo_json_feature_model != False # Construct a model instance of GeoJsonFeature by calling from_dict on the json representation geo_json_feature_model_dict = GeoJsonFeature.from_dict(geo_json_feature_model_json).__dict__ geo_json_feature_model2 = GeoJsonFeature(**geo_json_feature_model_dict) # Verify the model instances are equivalent assert geo_json_feature_model == geo_json_feature_model2 # Convert model instance back to dict and verify no loss of data geo_json_feature_model_json2 = geo_json_feature_model.to_dict() assert geo_json_feature_model_json2 == geo_json_feature_model_json # Test get_properties and set_properties methods. geo_json_feature_model.set_properties({}) actual_dict = geo_json_feature_model.get_properties() assert actual_dict == {} expected_dict = {'foo': 'testString'} geo_json_feature_model.set_properties(expected_dict) actual_dict = geo_json_feature_model.get_properties() assert actual_dict == expected_dict class TestModel_GeoResult(): """ Test Class for GeoResult """ def test_geo_result_serialization(self): """ Test serialization/deserialization for GeoResult """ # Construct dict forms of any model objects needed in order to build this model. geo_json_geometry_object_model = {} # GeoJsonGeometry geo_json_geometry_object_model['type'] = 'Point' geo_json_geometry_object_model['coordinates'] = ['testString'] geo_json_feature_model = {} # GeoJsonFeature geo_json_feature_model['_id'] = 'testString' geo_json_feature_model['_rev'] = 'testString' geo_json_feature_model['bbox'] = [72.5] geo_json_feature_model['geometry'] = geo_json_geometry_object_model geo_json_feature_model['properties'] = {} geo_json_feature_model['type'] = 'Feature' geo_json_feature_model['foo'] = 'testString' attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' geo_json_geometry_model = {} # GeoJsonGeometry geo_json_geometry_model['type'] = 'Point' geo_json_geometry_model['coordinates'] = ['testString'] geo_result_row_model = {} # GeoResultRow geo_result_row_model['doc'] = document_model geo_result_row_model['geometry'] = geo_json_geometry_model geo_result_row_model['id'] = 'testString' geo_result_row_model['rev'] = 'testString' # Construct a json representation of a GeoResult model geo_result_model_json = {} geo_result_model_json['bookmark'] = 'testString' geo_result_model_json['features'] = [geo_json_feature_model] geo_result_model_json['rows'] = [geo_result_row_model] geo_result_model_json['type'] = 'FeatureCollection' # Construct a model instance of GeoResult by calling from_dict on the json representation geo_result_model = GeoResult.from_dict(geo_result_model_json) assert geo_result_model != False # Construct a model instance of GeoResult by calling from_dict on the json representation geo_result_model_dict = GeoResult.from_dict(geo_result_model_json).__dict__ geo_result_model2 = GeoResult(**geo_result_model_dict) # Verify the model instances are equivalent assert geo_result_model == geo_result_model2 # Convert model instance back to dict and verify no loss of data geo_result_model_json2 = geo_result_model.to_dict() assert geo_result_model_json2 == geo_result_model_json class TestModel_GeoResultRow(): """ Test Class for GeoResultRow """ def test_geo_result_row_serialization(self): """ Test serialization/deserialization for GeoResultRow """ # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' geo_json_geometry_model = {} # GeoJsonGeometry geo_json_geometry_model['type'] = 'Point' geo_json_geometry_model['coordinates'] = ['testString'] # Construct a json representation of a GeoResultRow model geo_result_row_model_json = {} geo_result_row_model_json['doc'] = document_model geo_result_row_model_json['geometry'] = geo_json_geometry_model geo_result_row_model_json['id'] = 'testString' geo_result_row_model_json['rev'] = 'testString' # Construct a model instance of GeoResultRow by calling from_dict on the json representation geo_result_row_model = GeoResultRow.from_dict(geo_result_row_model_json) assert geo_result_row_model != False # Construct a model instance of GeoResultRow by calling from_dict on the json representation geo_result_row_model_dict = GeoResultRow.from_dict(geo_result_row_model_json).__dict__ geo_result_row_model2 = GeoResultRow(**geo_result_row_model_dict) # Verify the model instances are equivalent assert geo_result_row_model == geo_result_row_model2 # Convert model instance back to dict and verify no loss of data geo_result_row_model_json2 = geo_result_row_model.to_dict() assert geo_result_row_model_json2 == geo_result_row_model_json class TestModel_IndexDefinition(): """ Test Class for IndexDefinition """ def test_index_definition_serialization(self): """ Test serialization/deserialization for IndexDefinition """ # Construct dict forms of any model objects needed in order to build this model. analyzer_model = {} # Analyzer analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] index_text_operator_default_field_model = {} # IndexTextOperatorDefaultField index_text_operator_default_field_model['analyzer'] = analyzer_model index_text_operator_default_field_model['enabled'] = True index_field_model = {} # IndexField index_field_model['name'] = 'testString' index_field_model['type'] = 'boolean' index_field_model['foo'] = 'asc' # Construct a json representation of a IndexDefinition model index_definition_model_json = {} index_definition_model_json['default_analyzer'] = analyzer_model index_definition_model_json['default_field'] = index_text_operator_default_field_model index_definition_model_json['fields'] = [index_field_model] index_definition_model_json['index_array_lengths'] = True index_definition_model_json['partial_filter_selector'] = {} # Construct a model instance of IndexDefinition by calling from_dict on the json representation index_definition_model = IndexDefinition.from_dict(index_definition_model_json) assert index_definition_model != False # Construct a model instance of IndexDefinition by calling from_dict on the json representation index_definition_model_dict = IndexDefinition.from_dict(index_definition_model_json).__dict__ index_definition_model2 = IndexDefinition(**index_definition_model_dict) # Verify the model instances are equivalent assert index_definition_model == index_definition_model2 # Convert model instance back to dict and verify no loss of data index_definition_model_json2 = index_definition_model.to_dict() assert index_definition_model_json2 == index_definition_model_json class TestModel_IndexField(): """ Test Class for IndexField """ def test_index_field_serialization(self): """ Test serialization/deserialization for IndexField """ # Construct a json representation of a IndexField model index_field_model_json = {} index_field_model_json['name'] = 'testString' index_field_model_json['type'] = 'boolean' index_field_model_json['foo'] = 'asc' # Construct a model instance of IndexField by calling from_dict on the json representation index_field_model = IndexField.from_dict(index_field_model_json) assert index_field_model != False # Construct a model instance of IndexField by calling from_dict on the json representation index_field_model_dict = IndexField.from_dict(index_field_model_json).__dict__ index_field_model2 = IndexField(**index_field_model_dict) # Verify the model instances are equivalent assert index_field_model == index_field_model2 # Convert model instance back to dict and verify no loss of data index_field_model_json2 = index_field_model.to_dict() assert index_field_model_json2 == index_field_model_json # Test get_properties and set_properties methods. index_field_model.set_properties({}) actual_dict = index_field_model.get_properties() assert actual_dict == {} expected_dict = {'foo': 'asc'} index_field_model.set_properties(expected_dict) actual_dict = index_field_model.get_properties() assert actual_dict == expected_dict class TestModel_IndexInformation(): """ Test Class for IndexInformation """ def test_index_information_serialization(self): """ Test serialization/deserialization for IndexInformation """ # Construct dict forms of any model objects needed in order to build this model. analyzer_model = {} # Analyzer analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] index_text_operator_default_field_model = {} # IndexTextOperatorDefaultField index_text_operator_default_field_model['analyzer'] = analyzer_model index_text_operator_default_field_model['enabled'] = True index_field_model = {} # IndexField index_field_model['name'] = 'testString' index_field_model['type'] = 'boolean' index_field_model['foo'] = 'asc' index_definition_model = {} # IndexDefinition index_definition_model['default_analyzer'] = analyzer_model index_definition_model['default_field'] = index_text_operator_default_field_model index_definition_model['fields'] = [index_field_model] index_definition_model['index_array_lengths'] = True index_definition_model['partial_filter_selector'] = {} # Construct a json representation of a IndexInformation model index_information_model_json = {} index_information_model_json['ddoc'] = 'testString' index_information_model_json['def'] = index_definition_model index_information_model_json['name'] = 'testString' index_information_model_json['type'] = 'json' # Construct a model instance of IndexInformation by calling from_dict on the json representation index_information_model = IndexInformation.from_dict(index_information_model_json) assert index_information_model != False # Construct a model instance of IndexInformation by calling from_dict on the json representation index_information_model_dict = IndexInformation.from_dict(index_information_model_json).__dict__ index_information_model2 = IndexInformation(**index_information_model_dict) # Verify the model instances are equivalent assert index_information_model == index_information_model2 # Convert model instance back to dict and verify no loss of data index_information_model_json2 = index_information_model.to_dict() assert index_information_model_json2 == index_information_model_json class TestModel_IndexResult(): """ Test Class for IndexResult """ def test_index_result_serialization(self): """ Test serialization/deserialization for IndexResult """ # Construct a json representation of a IndexResult model index_result_model_json = {} index_result_model_json['id'] = 'testString' index_result_model_json['name'] = 'testString' index_result_model_json['result'] = 'created' # Construct a model instance of IndexResult by calling from_dict on the json representation index_result_model = IndexResult.from_dict(index_result_model_json) assert index_result_model != False # Construct a model instance of IndexResult by calling from_dict on the json representation index_result_model_dict = IndexResult.from_dict(index_result_model_json).__dict__ index_result_model2 = IndexResult(**index_result_model_dict) # Verify the model instances are equivalent assert index_result_model == index_result_model2 # Convert model instance back to dict and verify no loss of data index_result_model_json2 = index_result_model.to_dict() assert index_result_model_json2 == index_result_model_json class TestModel_IndexTextOperatorDefaultField(): """ Test Class for IndexTextOperatorDefaultField """ def test_index_text_operator_default_field_serialization(self): """ Test serialization/deserialization for IndexTextOperatorDefaultField """ # Construct dict forms of any model objects needed in order to build this model. analyzer_model = {} # Analyzer analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] # Construct a json representation of a IndexTextOperatorDefaultField model index_text_operator_default_field_model_json = {} index_text_operator_default_field_model_json['analyzer'] = analyzer_model index_text_operator_default_field_model_json['enabled'] = True # Construct a model instance of IndexTextOperatorDefaultField by calling from_dict on the json representation index_text_operator_default_field_model = IndexTextOperatorDefaultField.from_dict(index_text_operator_default_field_model_json) assert index_text_operator_default_field_model != False # Construct a model instance of IndexTextOperatorDefaultField by calling from_dict on the json representation index_text_operator_default_field_model_dict = IndexTextOperatorDefaultField.from_dict(index_text_operator_default_field_model_json).__dict__ index_text_operator_default_field_model2 = IndexTextOperatorDefaultField(**index_text_operator_default_field_model_dict) # Verify the model instances are equivalent assert index_text_operator_default_field_model == index_text_operator_default_field_model2 # Convert model instance back to dict and verify no loss of data index_text_operator_default_field_model_json2 = index_text_operator_default_field_model.to_dict() assert index_text_operator_default_field_model_json2 == index_text_operator_default_field_model_json class TestModel_IndexesInformation(): """ Test Class for IndexesInformation """ def test_indexes_information_serialization(self): """ Test serialization/deserialization for IndexesInformation """ # Construct dict forms of any model objects needed in order to build this model. analyzer_model = {} # Analyzer analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] index_text_operator_default_field_model = {} # IndexTextOperatorDefaultField index_text_operator_default_field_model['analyzer'] = analyzer_model index_text_operator_default_field_model['enabled'] = True index_field_model = {} # IndexField index_field_model['name'] = 'testString' index_field_model['type'] = 'boolean' index_field_model['foo'] = 'asc' index_definition_model = {} # IndexDefinition index_definition_model['default_analyzer'] = analyzer_model index_definition_model['default_field'] = index_text_operator_default_field_model index_definition_model['fields'] = [index_field_model] index_definition_model['index_array_lengths'] = True index_definition_model['partial_filter_selector'] = {} index_information_model = {} # IndexInformation index_information_model['ddoc'] = 'testString' index_information_model['def'] = index_definition_model index_information_model['name'] = 'testString' index_information_model['type'] = 'json' # Construct a json representation of a IndexesInformation model indexes_information_model_json = {} indexes_information_model_json['total_rows'] = 0 indexes_information_model_json['indexes'] = [index_information_model] # Construct a model instance of IndexesInformation by calling from_dict on the json representation indexes_information_model = IndexesInformation.from_dict(indexes_information_model_json) assert indexes_information_model != False # Construct a model instance of IndexesInformation by calling from_dict on the json representation indexes_information_model_dict = IndexesInformation.from_dict(indexes_information_model_json).__dict__ indexes_information_model2 = IndexesInformation(**indexes_information_model_dict) # Verify the model instances are equivalent assert indexes_information_model == indexes_information_model2 # Convert model instance back to dict and verify no loss of data indexes_information_model_json2 = indexes_information_model.to_dict() assert indexes_information_model_json2 == indexes_information_model_json class TestModel_MembershipInformation(): """ Test Class for MembershipInformation """ def test_membership_information_serialization(self): """ Test serialization/deserialization for MembershipInformation """ # Construct a json representation of a MembershipInformation model membership_information_model_json = {} membership_information_model_json['all_nodes'] = ['testString'] membership_information_model_json['cluster_nodes'] = ['testString'] # Construct a model instance of MembershipInformation by calling from_dict on the json representation membership_information_model = MembershipInformation.from_dict(membership_information_model_json) assert membership_information_model != False # Construct a model instance of MembershipInformation by calling from_dict on the json representation membership_information_model_dict = MembershipInformation.from_dict(membership_information_model_json).__dict__ membership_information_model2 = MembershipInformation(**membership_information_model_dict) # Verify the model instances are equivalent assert membership_information_model == membership_information_model2 # Convert model instance back to dict and verify no loss of data membership_information_model_json2 = membership_information_model.to_dict() assert membership_information_model_json2 == membership_information_model_json class TestModel_Ok(): """ Test Class for Ok """ def test_ok_serialization(self): """ Test serialization/deserialization for Ok """ # Construct a json representation of a Ok model ok_model_json = {} ok_model_json['ok'] = True # Construct a model instance of Ok by calling from_dict on the json representation ok_model = Ok.from_dict(ok_model_json) assert ok_model != False # Construct a model instance of Ok by calling from_dict on the json representation ok_model_dict = Ok.from_dict(ok_model_json).__dict__ ok_model2 = Ok(**ok_model_dict) # Verify the model instances are equivalent assert ok_model == ok_model2 # Convert model instance back to dict and verify no loss of data ok_model_json2 = ok_model.to_dict() assert ok_model_json2 == ok_model_json class TestModel_PartitionInformation(): """ Test Class for PartitionInformation """ def test_partition_information_serialization(self): """ Test serialization/deserialization for PartitionInformation """ # Construct dict forms of any model objects needed in order to build this model. partition_information_indexes_indexes_model = {} # PartitionInformationIndexesIndexes partition_information_indexes_indexes_model['search'] = 0 partition_information_indexes_indexes_model['view'] = 0 partition_information_indexes_model = {} # PartitionInformationIndexes partition_information_indexes_model['count'] = 0 partition_information_indexes_model['indexes'] = partition_information_indexes_indexes_model partition_information_indexes_model['limit'] = 0 partition_information_sizes_model = {} # PartitionInformationSizes partition_information_sizes_model['active'] = 0 partition_information_sizes_model['external'] = 0 # Construct a json representation of a PartitionInformation model partition_information_model_json = {} partition_information_model_json['db_name'] = 'testString' partition_information_model_json['doc_count'] = 0 partition_information_model_json['doc_del_count'] = 0 partition_information_model_json['partition'] = 'testString' partition_information_model_json['partitioned_indexes'] = partition_information_indexes_model partition_information_model_json['sizes'] = partition_information_sizes_model # Construct a model instance of PartitionInformation by calling from_dict on the json representation partition_information_model = PartitionInformation.from_dict(partition_information_model_json) assert partition_information_model != False # Construct a model instance of PartitionInformation by calling from_dict on the json representation partition_information_model_dict = PartitionInformation.from_dict(partition_information_model_json).__dict__ partition_information_model2 = PartitionInformation(**partition_information_model_dict) # Verify the model instances are equivalent assert partition_information_model == partition_information_model2 # Convert model instance back to dict and verify no loss of data partition_information_model_json2 = partition_information_model.to_dict() assert partition_information_model_json2 == partition_information_model_json class TestModel_PartitionInformationIndexes(): """ Test Class for PartitionInformationIndexes """ def test_partition_information_indexes_serialization(self): """ Test serialization/deserialization for PartitionInformationIndexes """ # Construct dict forms of any model objects needed in order to build this model. partition_information_indexes_indexes_model = {} # PartitionInformationIndexesIndexes partition_information_indexes_indexes_model['search'] = 0 partition_information_indexes_indexes_model['view'] = 0 # Construct a json representation of a PartitionInformationIndexes model partition_information_indexes_model_json = {} partition_information_indexes_model_json['count'] = 0 partition_information_indexes_model_json['indexes'] = partition_information_indexes_indexes_model partition_information_indexes_model_json['limit'] = 0 # Construct a model instance of PartitionInformationIndexes by calling from_dict on the json representation partition_information_indexes_model = PartitionInformationIndexes.from_dict(partition_information_indexes_model_json) assert partition_information_indexes_model != False # Construct a model instance of PartitionInformationIndexes by calling from_dict on the json representation partition_information_indexes_model_dict = PartitionInformationIndexes.from_dict(partition_information_indexes_model_json).__dict__ partition_information_indexes_model2 = PartitionInformationIndexes(**partition_information_indexes_model_dict) # Verify the model instances are equivalent assert partition_information_indexes_model == partition_information_indexes_model2 # Convert model instance back to dict and verify no loss of data partition_information_indexes_model_json2 = partition_information_indexes_model.to_dict() assert partition_information_indexes_model_json2 == partition_information_indexes_model_json class TestModel_PartitionInformationIndexesIndexes(): """ Test Class for PartitionInformationIndexesIndexes """ def test_partition_information_indexes_indexes_serialization(self): """ Test serialization/deserialization for PartitionInformationIndexesIndexes """ # Construct a json representation of a PartitionInformationIndexesIndexes model partition_information_indexes_indexes_model_json = {} partition_information_indexes_indexes_model_json['search'] = 0 partition_information_indexes_indexes_model_json['view'] = 0 # Construct a model instance of PartitionInformationIndexesIndexes by calling from_dict on the json representation partition_information_indexes_indexes_model = PartitionInformationIndexesIndexes.from_dict(partition_information_indexes_indexes_model_json) assert partition_information_indexes_indexes_model != False # Construct a model instance of PartitionInformationIndexesIndexes by calling from_dict on the json representation partition_information_indexes_indexes_model_dict = PartitionInformationIndexesIndexes.from_dict(partition_information_indexes_indexes_model_json).__dict__ partition_information_indexes_indexes_model2 = PartitionInformationIndexesIndexes(**partition_information_indexes_indexes_model_dict) # Verify the model instances are equivalent assert partition_information_indexes_indexes_model == partition_information_indexes_indexes_model2 # Convert model instance back to dict and verify no loss of data partition_information_indexes_indexes_model_json2 = partition_information_indexes_indexes_model.to_dict() assert partition_information_indexes_indexes_model_json2 == partition_information_indexes_indexes_model_json class TestModel_PartitionInformationSizes(): """ Test Class for PartitionInformationSizes """ def test_partition_information_sizes_serialization(self): """ Test serialization/deserialization for PartitionInformationSizes """ # Construct a json representation of a PartitionInformationSizes model partition_information_sizes_model_json = {} partition_information_sizes_model_json['active'] = 0 partition_information_sizes_model_json['external'] = 0 # Construct a model instance of PartitionInformationSizes by calling from_dict on the json representation partition_information_sizes_model = PartitionInformationSizes.from_dict(partition_information_sizes_model_json) assert partition_information_sizes_model != False # Construct a model instance of PartitionInformationSizes by calling from_dict on the json representation partition_information_sizes_model_dict = PartitionInformationSizes.from_dict(partition_information_sizes_model_json).__dict__ partition_information_sizes_model2 = PartitionInformationSizes(**partition_information_sizes_model_dict) # Verify the model instances are equivalent assert partition_information_sizes_model == partition_information_sizes_model2 # Convert model instance back to dict and verify no loss of data partition_information_sizes_model_json2 = partition_information_sizes_model.to_dict() assert partition_information_sizes_model_json2 == partition_information_sizes_model_json class TestModel_ReplicationCreateTargetParameters(): """ Test Class for ReplicationCreateTargetParameters """ def test_replication_create_target_parameters_serialization(self): """ Test serialization/deserialization for ReplicationCreateTargetParameters """ # Construct a json representation of a ReplicationCreateTargetParameters model replication_create_target_parameters_model_json = {} replication_create_target_parameters_model_json['n'] = 1 replication_create_target_parameters_model_json['partitioned'] = False replication_create_target_parameters_model_json['q'] = 1 # Construct a model instance of ReplicationCreateTargetParameters by calling from_dict on the json representation replication_create_target_parameters_model = ReplicationCreateTargetParameters.from_dict(replication_create_target_parameters_model_json) assert replication_create_target_parameters_model != False # Construct a model instance of ReplicationCreateTargetParameters by calling from_dict on the json representation replication_create_target_parameters_model_dict = ReplicationCreateTargetParameters.from_dict(replication_create_target_parameters_model_json).__dict__ replication_create_target_parameters_model2 = ReplicationCreateTargetParameters(**replication_create_target_parameters_model_dict) # Verify the model instances are equivalent assert replication_create_target_parameters_model == replication_create_target_parameters_model2 # Convert model instance back to dict and verify no loss of data replication_create_target_parameters_model_json2 = replication_create_target_parameters_model.to_dict() assert replication_create_target_parameters_model_json2 == replication_create_target_parameters_model_json class TestModel_ReplicationDatabase(): """ Test Class for ReplicationDatabase """ def test_replication_database_serialization(self): """ Test serialization/deserialization for ReplicationDatabase """ # Construct dict forms of any model objects needed in order to build this model. replication_database_auth_basic_model = {} # ReplicationDatabaseAuthBasic replication_database_auth_basic_model['password'] = 'testString' replication_database_auth_basic_model['username'] = 'testString' replication_database_auth_iam_model = {} # ReplicationDatabaseAuthIam replication_database_auth_iam_model['api_key'] = 'testString' replication_database_auth_model = {} # ReplicationDatabaseAuth replication_database_auth_model['basic'] = replication_database_auth_basic_model replication_database_auth_model['iam'] = replication_database_auth_iam_model # Construct a json representation of a ReplicationDatabase model replication_database_model_json = {} replication_database_model_json['auth'] = replication_database_auth_model replication_database_model_json['headers'] = {} replication_database_model_json['url'] = 'testString' # Construct a model instance of ReplicationDatabase by calling from_dict on the json representation replication_database_model = ReplicationDatabase.from_dict(replication_database_model_json) assert replication_database_model != False # Construct a model instance of ReplicationDatabase by calling from_dict on the json representation replication_database_model_dict = ReplicationDatabase.from_dict(replication_database_model_json).__dict__ replication_database_model2 = ReplicationDatabase(**replication_database_model_dict) # Verify the model instances are equivalent assert replication_database_model == replication_database_model2 # Convert model instance back to dict and verify no loss of data replication_database_model_json2 = replication_database_model.to_dict() assert replication_database_model_json2 == replication_database_model_json class TestModel_ReplicationDatabaseAuth(): """ Test Class for ReplicationDatabaseAuth """ def test_replication_database_auth_serialization(self): """ Test serialization/deserialization for ReplicationDatabaseAuth """ # Construct dict forms of any model objects needed in order to build this model. replication_database_auth_basic_model = {} # ReplicationDatabaseAuthBasic replication_database_auth_basic_model['password'] = 'testString' replication_database_auth_basic_model['username'] = 'testString' replication_database_auth_iam_model = {} # ReplicationDatabaseAuthIam replication_database_auth_iam_model['api_key'] = 'testString' # Construct a json representation of a ReplicationDatabaseAuth model replication_database_auth_model_json = {} replication_database_auth_model_json['basic'] = replication_database_auth_basic_model replication_database_auth_model_json['iam'] = replication_database_auth_iam_model # Construct a model instance of ReplicationDatabaseAuth by calling from_dict on the json representation replication_database_auth_model = ReplicationDatabaseAuth.from_dict(replication_database_auth_model_json) assert replication_database_auth_model != False # Construct a model instance of ReplicationDatabaseAuth by calling from_dict on the json representation replication_database_auth_model_dict = ReplicationDatabaseAuth.from_dict(replication_database_auth_model_json).__dict__ replication_database_auth_model2 = ReplicationDatabaseAuth(**replication_database_auth_model_dict) # Verify the model instances are equivalent assert replication_database_auth_model == replication_database_auth_model2 # Convert model instance back to dict and verify no loss of data replication_database_auth_model_json2 = replication_database_auth_model.to_dict() assert replication_database_auth_model_json2 == replication_database_auth_model_json class TestModel_ReplicationDatabaseAuthBasic(): """ Test Class for ReplicationDatabaseAuthBasic """ def test_replication_database_auth_basic_serialization(self): """ Test serialization/deserialization for ReplicationDatabaseAuthBasic """ # Construct a json representation of a ReplicationDatabaseAuthBasic model replication_database_auth_basic_model_json = {} replication_database_auth_basic_model_json['password'] = 'testString' replication_database_auth_basic_model_json['username'] = 'testString' # Construct a model instance of ReplicationDatabaseAuthBasic by calling from_dict on the json representation replication_database_auth_basic_model = ReplicationDatabaseAuthBasic.from_dict(replication_database_auth_basic_model_json) assert replication_database_auth_basic_model != False # Construct a model instance of ReplicationDatabaseAuthBasic by calling from_dict on the json representation replication_database_auth_basic_model_dict = ReplicationDatabaseAuthBasic.from_dict(replication_database_auth_basic_model_json).__dict__ replication_database_auth_basic_model2 = ReplicationDatabaseAuthBasic(**replication_database_auth_basic_model_dict) # Verify the model instances are equivalent assert replication_database_auth_basic_model == replication_database_auth_basic_model2 # Convert model instance back to dict and verify no loss of data replication_database_auth_basic_model_json2 = replication_database_auth_basic_model.to_dict() assert replication_database_auth_basic_model_json2 == replication_database_auth_basic_model_json class TestModel_ReplicationDatabaseAuthIam(): """ Test Class for ReplicationDatabaseAuthIam """ def test_replication_database_auth_iam_serialization(self): """ Test serialization/deserialization for ReplicationDatabaseAuthIam """ # Construct a json representation of a ReplicationDatabaseAuthIam model replication_database_auth_iam_model_json = {} replication_database_auth_iam_model_json['api_key'] = 'testString' # Construct a model instance of ReplicationDatabaseAuthIam by calling from_dict on the json representation replication_database_auth_iam_model = ReplicationDatabaseAuthIam.from_dict(replication_database_auth_iam_model_json) assert replication_database_auth_iam_model != False # Construct a model instance of ReplicationDatabaseAuthIam by calling from_dict on the json representation replication_database_auth_iam_model_dict = ReplicationDatabaseAuthIam.from_dict(replication_database_auth_iam_model_json).__dict__ replication_database_auth_iam_model2 = ReplicationDatabaseAuthIam(**replication_database_auth_iam_model_dict) # Verify the model instances are equivalent assert replication_database_auth_iam_model == replication_database_auth_iam_model2 # Convert model instance back to dict and verify no loss of data replication_database_auth_iam_model_json2 = replication_database_auth_iam_model.to_dict() assert replication_database_auth_iam_model_json2 == replication_database_auth_iam_model_json class TestModel_ReplicationDocument(): """ Test Class for ReplicationDocument """ def test_replication_document_serialization(self): """ Test serialization/deserialization for ReplicationDocument """ # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' replication_create_target_parameters_model = {} # ReplicationCreateTargetParameters replication_create_target_parameters_model['n'] = 1 replication_create_target_parameters_model['partitioned'] = False replication_create_target_parameters_model['q'] = 1 replication_database_auth_basic_model = {} # ReplicationDatabaseAuthBasic replication_database_auth_basic_model['password'] = 'testString' replication_database_auth_basic_model['username'] = 'testString' replication_database_auth_iam_model = {} # ReplicationDatabaseAuthIam replication_database_auth_iam_model['api_key'] = 'testString' replication_database_auth_model = {} # ReplicationDatabaseAuth replication_database_auth_model['basic'] = replication_database_auth_basic_model replication_database_auth_model['iam'] = replication_database_auth_iam_model replication_database_model = {} # ReplicationDatabase replication_database_model['auth'] = replication_database_auth_model replication_database_model['headers'] = {} replication_database_model['url'] = 'testString' user_context_model = {} # UserContext user_context_model['db'] = 'testString' user_context_model['name'] = 'testString' user_context_model['roles'] = ['_reader'] # Construct a json representation of a ReplicationDocument model replication_document_model_json = {} replication_document_model_json['_attachments'] = {} replication_document_model_json['_conflicts'] = ['testString'] replication_document_model_json['_deleted'] = True replication_document_model_json['_deleted_conflicts'] = ['testString'] replication_document_model_json['_id'] = 'testString' replication_document_model_json['_local_seq'] = 'testString' replication_document_model_json['_rev'] = 'testString' replication_document_model_json['_revisions'] = revisions_model replication_document_model_json['_revs_info'] = [document_revision_status_model] replication_document_model_json['cancel'] = True replication_document_model_json['checkpoint_interval'] = 0 replication_document_model_json['connection_timeout'] = 0 replication_document_model_json['continuous'] = False replication_document_model_json['create_target'] = False replication_document_model_json['create_target_params'] = replication_create_target_parameters_model replication_document_model_json['doc_ids'] = ['testString'] replication_document_model_json['filter'] = 'testString' replication_document_model_json['http_connections'] = 1 replication_document_model_json['query_params'] = {} replication_document_model_json['retries_per_request'] = 0 replication_document_model_json['selector'] = {} replication_document_model_json['since_seq'] = 'testString' replication_document_model_json['socket_options'] = 'testString' replication_document_model_json['source'] = replication_database_model replication_document_model_json['source_proxy'] = 'testString' replication_document_model_json['target'] = replication_database_model replication_document_model_json['target_proxy'] = 'testString' replication_document_model_json['use_checkpoints'] = True replication_document_model_json['user_ctx'] = user_context_model replication_document_model_json['worker_batch_size'] = 1 replication_document_model_json['worker_processes'] = 1 replication_document_model_json['foo'] = 'testString' # Construct a model instance of ReplicationDocument by calling from_dict on the json representation replication_document_model = ReplicationDocument.from_dict(replication_document_model_json) assert replication_document_model != False # Construct a model instance of ReplicationDocument by calling from_dict on the json representation replication_document_model_dict = ReplicationDocument.from_dict(replication_document_model_json).__dict__ replication_document_model2 = ReplicationDocument(**replication_document_model_dict) # Verify the model instances are equivalent assert replication_document_model == replication_document_model2 # Convert model instance back to dict and verify no loss of data replication_document_model_json2 = replication_document_model.to_dict() assert replication_document_model_json2 == replication_document_model_json # Test get_properties and set_properties methods. replication_document_model.set_properties({}) actual_dict = replication_document_model.get_properties() assert actual_dict == {} expected_dict = {'foo': 'testString'} replication_document_model.set_properties(expected_dict) actual_dict = replication_document_model.get_properties() assert actual_dict == expected_dict class TestModel_Revisions(): """ Test Class for Revisions """ def test_revisions_serialization(self): """ Test serialization/deserialization for Revisions """ # Construct a json representation of a Revisions model revisions_model_json = {} revisions_model_json['ids'] = ['testString'] revisions_model_json['start'] = 1 # Construct a model instance of Revisions by calling from_dict on the json representation revisions_model = Revisions.from_dict(revisions_model_json) assert revisions_model != False # Construct a model instance of Revisions by calling from_dict on the json representation revisions_model_dict = Revisions.from_dict(revisions_model_json).__dict__ revisions_model2 = Revisions(**revisions_model_dict) # Verify the model instances are equivalent assert revisions_model == revisions_model2 # Convert model instance back to dict and verify no loss of data revisions_model_json2 = revisions_model.to_dict() assert revisions_model_json2 == revisions_model_json class TestModel_RevsDiff(): """ Test Class for RevsDiff """ def test_revs_diff_serialization(self): """ Test serialization/deserialization for RevsDiff """ # Construct a json representation of a RevsDiff model revs_diff_model_json = {} revs_diff_model_json['missing'] = ['testString'] revs_diff_model_json['possible_ancestors'] = ['testString'] # Construct a model instance of RevsDiff by calling from_dict on the json representation revs_diff_model = RevsDiff.from_dict(revs_diff_model_json) assert revs_diff_model != False # Construct a model instance of RevsDiff by calling from_dict on the json representation revs_diff_model_dict = RevsDiff.from_dict(revs_diff_model_json).__dict__ revs_diff_model2 = RevsDiff(**revs_diff_model_dict) # Verify the model instances are equivalent assert revs_diff_model == revs_diff_model2 # Convert model instance back to dict and verify no loss of data revs_diff_model_json2 = revs_diff_model.to_dict() assert revs_diff_model_json2 == revs_diff_model_json class TestModel_SchedulerDocsResult(): """ Test Class for SchedulerDocsResult """ def test_scheduler_docs_result_serialization(self): """ Test serialization/deserialization for SchedulerDocsResult """ # Construct dict forms of any model objects needed in order to build this model. scheduler_info_model = {} # SchedulerInfo scheduler_info_model['changes_pending'] = 0 scheduler_info_model['checkpointed_source_seq'] = 'testString' scheduler_info_model['doc_write_failures'] = 0 scheduler_info_model['docs_read'] = 0 scheduler_info_model['docs_written'] = 0 scheduler_info_model['error'] = 'testString' scheduler_info_model['missing_revisions_found'] = 0 scheduler_info_model['revisions_checked'] = 0 scheduler_info_model['source_seq'] = 'testString' scheduler_info_model['through_seq'] = 'testString' scheduler_document_model = {} # SchedulerDocument scheduler_document_model['database'] = 'testString' scheduler_document_model['doc_id'] = 'testString' scheduler_document_model['error_count'] = 0 scheduler_document_model['id'] = 'testString' scheduler_document_model['info'] = scheduler_info_model scheduler_document_model['last_updated'] = "2019-01-01T12:00:00Z" scheduler_document_model['node'] = 'testString' scheduler_document_model['source'] = 'testString' scheduler_document_model['source_proxy'] = 'testString' scheduler_document_model['start_time'] = "2019-01-01T12:00:00Z" scheduler_document_model['state'] = 'initializing' scheduler_document_model['target'] = 'testString' scheduler_document_model['target_proxy'] = 'testString' # Construct a json representation of a SchedulerDocsResult model scheduler_docs_result_model_json = {} scheduler_docs_result_model_json['total_rows'] = 0 scheduler_docs_result_model_json['docs'] = [scheduler_document_model] # Construct a model instance of SchedulerDocsResult by calling from_dict on the json representation scheduler_docs_result_model = SchedulerDocsResult.from_dict(scheduler_docs_result_model_json) assert scheduler_docs_result_model != False # Construct a model instance of SchedulerDocsResult by calling from_dict on the json representation scheduler_docs_result_model_dict = SchedulerDocsResult.from_dict(scheduler_docs_result_model_json).__dict__ scheduler_docs_result_model2 = SchedulerDocsResult(**scheduler_docs_result_model_dict) # Verify the model instances are equivalent assert scheduler_docs_result_model == scheduler_docs_result_model2 # Convert model instance back to dict and verify no loss of data scheduler_docs_result_model_json2 = scheduler_docs_result_model.to_dict() assert scheduler_docs_result_model_json2 == scheduler_docs_result_model_json class TestModel_SchedulerDocument(): """ Test Class for SchedulerDocument """ def test_scheduler_document_serialization(self): """ Test serialization/deserialization for SchedulerDocument """ # Construct dict forms of any model objects needed in order to build this model. scheduler_info_model = {} # SchedulerInfo scheduler_info_model['changes_pending'] = 0 scheduler_info_model['checkpointed_source_seq'] = 'testString' scheduler_info_model['doc_write_failures'] = 0 scheduler_info_model['docs_read'] = 0 scheduler_info_model['docs_written'] = 0 scheduler_info_model['error'] = 'testString' scheduler_info_model['missing_revisions_found'] = 0 scheduler_info_model['revisions_checked'] = 0 scheduler_info_model['source_seq'] = 'testString' scheduler_info_model['through_seq'] = 'testString' # Construct a json representation of a SchedulerDocument model scheduler_document_model_json = {} scheduler_document_model_json['database'] = 'testString' scheduler_document_model_json['doc_id'] = 'testString' scheduler_document_model_json['error_count'] = 0 scheduler_document_model_json['id'] = 'testString' scheduler_document_model_json['info'] = scheduler_info_model scheduler_document_model_json['last_updated'] = "2019-01-01T12:00:00Z" scheduler_document_model_json['node'] = 'testString' scheduler_document_model_json['source'] = 'testString' scheduler_document_model_json['source_proxy'] = 'testString' scheduler_document_model_json['start_time'] = "2019-01-01T12:00:00Z" scheduler_document_model_json['state'] = 'initializing' scheduler_document_model_json['target'] = 'testString' scheduler_document_model_json['target_proxy'] = 'testString' # Construct a model instance of SchedulerDocument by calling from_dict on the json representation scheduler_document_model = SchedulerDocument.from_dict(scheduler_document_model_json) assert scheduler_document_model != False # Construct a model instance of SchedulerDocument by calling from_dict on the json representation scheduler_document_model_dict = SchedulerDocument.from_dict(scheduler_document_model_json).__dict__ scheduler_document_model2 = SchedulerDocument(**scheduler_document_model_dict) # Verify the model instances are equivalent assert scheduler_document_model == scheduler_document_model2 # Convert model instance back to dict and verify no loss of data scheduler_document_model_json2 = scheduler_document_model.to_dict() assert scheduler_document_model_json2 == scheduler_document_model_json class TestModel_SchedulerInfo(): """ Test Class for SchedulerInfo """ def test_scheduler_info_serialization(self): """ Test serialization/deserialization for SchedulerInfo """ # Construct a json representation of a SchedulerInfo model scheduler_info_model_json = {} scheduler_info_model_json['changes_pending'] = 0 scheduler_info_model_json['checkpointed_source_seq'] = 'testString' scheduler_info_model_json['doc_write_failures'] = 0 scheduler_info_model_json['docs_read'] = 0 scheduler_info_model_json['docs_written'] = 0 scheduler_info_model_json['error'] = 'testString' scheduler_info_model_json['missing_revisions_found'] = 0 scheduler_info_model_json['revisions_checked'] = 0 scheduler_info_model_json['source_seq'] = 'testString' scheduler_info_model_json['through_seq'] = 'testString' # Construct a model instance of SchedulerInfo by calling from_dict on the json representation scheduler_info_model = SchedulerInfo.from_dict(scheduler_info_model_json) assert scheduler_info_model != False # Construct a model instance of SchedulerInfo by calling from_dict on the json representation scheduler_info_model_dict = SchedulerInfo.from_dict(scheduler_info_model_json).__dict__ scheduler_info_model2 = SchedulerInfo(**scheduler_info_model_dict) # Verify the model instances are equivalent assert scheduler_info_model == scheduler_info_model2 # Convert model instance back to dict and verify no loss of data scheduler_info_model_json2 = scheduler_info_model.to_dict() assert scheduler_info_model_json2 == scheduler_info_model_json class TestModel_SchedulerJob(): """ Test Class for SchedulerJob """ def test_scheduler_job_serialization(self): """ Test serialization/deserialization for SchedulerJob """ # Construct dict forms of any model objects needed in order to build this model. scheduler_job_event_model = {} # SchedulerJobEvent scheduler_job_event_model['reason'] = 'testString' scheduler_job_event_model['timestamp'] = "2019-01-01T12:00:00Z" scheduler_job_event_model['type'] = 'testString' scheduler_info_model = {} # SchedulerInfo scheduler_info_model['changes_pending'] = 0 scheduler_info_model['checkpointed_source_seq'] = 'testString' scheduler_info_model['doc_write_failures'] = 0 scheduler_info_model['docs_read'] = 0 scheduler_info_model['docs_written'] = 0 scheduler_info_model['error'] = 'testString' scheduler_info_model['missing_revisions_found'] = 0 scheduler_info_model['revisions_checked'] = 0 scheduler_info_model['source_seq'] = 'testString' scheduler_info_model['through_seq'] = 'testString' # Construct a json representation of a SchedulerJob model scheduler_job_model_json = {} scheduler_job_model_json['database'] = 'testString' scheduler_job_model_json['doc_id'] = 'testString' scheduler_job_model_json['history'] = [scheduler_job_event_model] scheduler_job_model_json['id'] = 'testString' scheduler_job_model_json['info'] = scheduler_info_model scheduler_job_model_json['node'] = 'testString' scheduler_job_model_json['pid'] = 'testString' scheduler_job_model_json['source'] = 'testString' scheduler_job_model_json['start_time'] = "2019-01-01T12:00:00Z" scheduler_job_model_json['target'] = 'testString' scheduler_job_model_json['user'] = 'testString' # Construct a model instance of SchedulerJob by calling from_dict on the json representation scheduler_job_model = SchedulerJob.from_dict(scheduler_job_model_json) assert scheduler_job_model != False # Construct a model instance of SchedulerJob by calling from_dict on the json representation scheduler_job_model_dict = SchedulerJob.from_dict(scheduler_job_model_json).__dict__ scheduler_job_model2 = SchedulerJob(**scheduler_job_model_dict) # Verify the model instances are equivalent assert scheduler_job_model == scheduler_job_model2 # Convert model instance back to dict and verify no loss of data scheduler_job_model_json2 = scheduler_job_model.to_dict() assert scheduler_job_model_json2 == scheduler_job_model_json class TestModel_SchedulerJobEvent(): """ Test Class for SchedulerJobEvent """ def test_scheduler_job_event_serialization(self): """ Test serialization/deserialization for SchedulerJobEvent """ # Construct a json representation of a SchedulerJobEvent model scheduler_job_event_model_json = {} scheduler_job_event_model_json['reason'] = 'testString' scheduler_job_event_model_json['timestamp'] = "2019-01-01T12:00:00Z" scheduler_job_event_model_json['type'] = 'testString' # Construct a model instance of SchedulerJobEvent by calling from_dict on the json representation scheduler_job_event_model = SchedulerJobEvent.from_dict(scheduler_job_event_model_json) assert scheduler_job_event_model != False # Construct a model instance of SchedulerJobEvent by calling from_dict on the json representation scheduler_job_event_model_dict = SchedulerJobEvent.from_dict(scheduler_job_event_model_json).__dict__ scheduler_job_event_model2 = SchedulerJobEvent(**scheduler_job_event_model_dict) # Verify the model instances are equivalent assert scheduler_job_event_model == scheduler_job_event_model2 # Convert model instance back to dict and verify no loss of data scheduler_job_event_model_json2 = scheduler_job_event_model.to_dict() assert scheduler_job_event_model_json2 == scheduler_job_event_model_json class TestModel_SchedulerJobsResult(): """ Test Class for SchedulerJobsResult """ def test_scheduler_jobs_result_serialization(self): """ Test serialization/deserialization for SchedulerJobsResult """ # Construct dict forms of any model objects needed in order to build this model. scheduler_job_event_model = {} # SchedulerJobEvent scheduler_job_event_model['reason'] = 'testString' scheduler_job_event_model['timestamp'] = "2019-01-01T12:00:00Z" scheduler_job_event_model['type'] = 'testString' scheduler_info_model = {} # SchedulerInfo scheduler_info_model['changes_pending'] = 0 scheduler_info_model['checkpointed_source_seq'] = 'testString' scheduler_info_model['doc_write_failures'] = 0 scheduler_info_model['docs_read'] = 0 scheduler_info_model['docs_written'] = 0 scheduler_info_model['error'] = 'testString' scheduler_info_model['missing_revisions_found'] = 0 scheduler_info_model['revisions_checked'] = 0 scheduler_info_model['source_seq'] = 'testString' scheduler_info_model['through_seq'] = 'testString' scheduler_job_model = {} # SchedulerJob scheduler_job_model['database'] = 'testString' scheduler_job_model['doc_id'] = 'testString' scheduler_job_model['history'] = [scheduler_job_event_model] scheduler_job_model['id'] = 'testString' scheduler_job_model['info'] = scheduler_info_model scheduler_job_model['node'] = 'testString' scheduler_job_model['pid'] = 'testString' scheduler_job_model['source'] = 'testString' scheduler_job_model['start_time'] = "2019-01-01T12:00:00Z" scheduler_job_model['target'] = 'testString' scheduler_job_model['user'] = 'testString' # Construct a json representation of a SchedulerJobsResult model scheduler_jobs_result_model_json = {} scheduler_jobs_result_model_json['total_rows'] = 0 scheduler_jobs_result_model_json['jobs'] = [scheduler_job_model] # Construct a model instance of SchedulerJobsResult by calling from_dict on the json representation scheduler_jobs_result_model = SchedulerJobsResult.from_dict(scheduler_jobs_result_model_json) assert scheduler_jobs_result_model != False # Construct a model instance of SchedulerJobsResult by calling from_dict on the json representation scheduler_jobs_result_model_dict = SchedulerJobsResult.from_dict(scheduler_jobs_result_model_json).__dict__ scheduler_jobs_result_model2 = SchedulerJobsResult(**scheduler_jobs_result_model_dict) # Verify the model instances are equivalent assert scheduler_jobs_result_model == scheduler_jobs_result_model2 # Convert model instance back to dict and verify no loss of data scheduler_jobs_result_model_json2 = scheduler_jobs_result_model.to_dict() assert scheduler_jobs_result_model_json2 == scheduler_jobs_result_model_json class TestModel_SearchAnalyzeResult(): """ Test Class for SearchAnalyzeResult """ def test_search_analyze_result_serialization(self): """ Test serialization/deserialization for SearchAnalyzeResult """ # Construct a json representation of a SearchAnalyzeResult model search_analyze_result_model_json = {} search_analyze_result_model_json['tokens'] = ['testString'] # Construct a model instance of SearchAnalyzeResult by calling from_dict on the json representation search_analyze_result_model = SearchAnalyzeResult.from_dict(search_analyze_result_model_json) assert search_analyze_result_model != False # Construct a model instance of SearchAnalyzeResult by calling from_dict on the json representation search_analyze_result_model_dict = SearchAnalyzeResult.from_dict(search_analyze_result_model_json).__dict__ search_analyze_result_model2 = SearchAnalyzeResult(**search_analyze_result_model_dict) # Verify the model instances are equivalent assert search_analyze_result_model == search_analyze_result_model2 # Convert model instance back to dict and verify no loss of data search_analyze_result_model_json2 = search_analyze_result_model.to_dict() assert search_analyze_result_model_json2 == search_analyze_result_model_json class TestModel_SearchIndexDefinition(): """ Test Class for SearchIndexDefinition """ def test_search_index_definition_serialization(self): """ Test serialization/deserialization for SearchIndexDefinition """ # Construct dict forms of any model objects needed in order to build this model. analyzer_model = {} # Analyzer analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] analyzer_configuration_model = {} # AnalyzerConfiguration analyzer_configuration_model['name'] = 'classic' analyzer_configuration_model['stopwords'] = ['testString'] analyzer_configuration_model['fields'] = {} # Construct a json representation of a SearchIndexDefinition model search_index_definition_model_json = {} search_index_definition_model_json['analyzer'] = analyzer_configuration_model search_index_definition_model_json['index'] = 'testString' # Construct a model instance of SearchIndexDefinition by calling from_dict on the json representation search_index_definition_model = SearchIndexDefinition.from_dict(search_index_definition_model_json) assert search_index_definition_model != False # Construct a model instance of SearchIndexDefinition by calling from_dict on the json representation search_index_definition_model_dict = SearchIndexDefinition.from_dict(search_index_definition_model_json).__dict__ search_index_definition_model2 = SearchIndexDefinition(**search_index_definition_model_dict) # Verify the model instances are equivalent assert search_index_definition_model == search_index_definition_model2 # Convert model instance back to dict and verify no loss of data search_index_definition_model_json2 = search_index_definition_model.to_dict() assert search_index_definition_model_json2 == search_index_definition_model_json class TestModel_SearchIndexInfo(): """ Test Class for SearchIndexInfo """ def test_search_index_info_serialization(self): """ Test serialization/deserialization for SearchIndexInfo """ # Construct a json representation of a SearchIndexInfo model search_index_info_model_json = {} search_index_info_model_json['committed_seq'] = 26 search_index_info_model_json['disk_size'] = 0 search_index_info_model_json['doc_count'] = 0 search_index_info_model_json['doc_del_count'] = 0 search_index_info_model_json['pending_seq'] = 26 # Construct a model instance of SearchIndexInfo by calling from_dict on the json representation search_index_info_model = SearchIndexInfo.from_dict(search_index_info_model_json) assert search_index_info_model != False # Construct a model instance of SearchIndexInfo by calling from_dict on the json representation search_index_info_model_dict = SearchIndexInfo.from_dict(search_index_info_model_json).__dict__ search_index_info_model2 = SearchIndexInfo(**search_index_info_model_dict) # Verify the model instances are equivalent assert search_index_info_model == search_index_info_model2 # Convert model instance back to dict and verify no loss of data search_index_info_model_json2 = search_index_info_model.to_dict() assert search_index_info_model_json2 == search_index_info_model_json class TestModel_SearchInfoResult(): """ Test Class for SearchInfoResult """ def test_search_info_result_serialization(self): """ Test serialization/deserialization for SearchInfoResult """ # Construct dict forms of any model objects needed in order to build this model. search_index_info_model = {} # SearchIndexInfo search_index_info_model['committed_seq'] = 26 search_index_info_model['disk_size'] = 0 search_index_info_model['doc_count'] = 0 search_index_info_model['doc_del_count'] = 0 search_index_info_model['pending_seq'] = 26 # Construct a json representation of a SearchInfoResult model search_info_result_model_json = {} search_info_result_model_json['name'] = 'testString' search_info_result_model_json['search_index'] = search_index_info_model # Construct a model instance of SearchInfoResult by calling from_dict on the json representation search_info_result_model = SearchInfoResult.from_dict(search_info_result_model_json) assert search_info_result_model != False # Construct a model instance of SearchInfoResult by calling from_dict on the json representation search_info_result_model_dict = SearchInfoResult.from_dict(search_info_result_model_json).__dict__ search_info_result_model2 = SearchInfoResult(**search_info_result_model_dict) # Verify the model instances are equivalent assert search_info_result_model == search_info_result_model2 # Convert model instance back to dict and verify no loss of data search_info_result_model_json2 = search_info_result_model.to_dict() assert search_info_result_model_json2 == search_info_result_model_json class TestModel_SearchResult(): """ Test Class for SearchResult """ def test_search_result_serialization(self): """ Test serialization/deserialization for SearchResult """ # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' search_result_row_model = {} # SearchResultRow search_result_row_model['doc'] = document_model search_result_row_model['fields'] = {} search_result_row_model['highlights'] = {} search_result_row_model['id'] = 'testString' search_result_properties_model = {} # SearchResultProperties search_result_properties_model['total_rows'] = 0 search_result_properties_model['bookmark'] = 'testString' search_result_properties_model['by'] = 'testString' search_result_properties_model['counts'] = {} search_result_properties_model['ranges'] = {} search_result_properties_model['rows'] = [search_result_row_model] # Construct a json representation of a SearchResult model search_result_model_json = {} search_result_model_json['total_rows'] = 0 search_result_model_json['bookmark'] = 'testString' search_result_model_json['by'] = 'testString' search_result_model_json['counts'] = {} search_result_model_json['ranges'] = {} search_result_model_json['rows'] = [search_result_row_model] search_result_model_json['groups'] = [search_result_properties_model] # Construct a model instance of SearchResult by calling from_dict on the json representation search_result_model = SearchResult.from_dict(search_result_model_json) assert search_result_model != False # Construct a model instance of SearchResult by calling from_dict on the json representation search_result_model_dict = SearchResult.from_dict(search_result_model_json).__dict__ search_result_model2 = SearchResult(**search_result_model_dict) # Verify the model instances are equivalent assert search_result_model == search_result_model2 # Convert model instance back to dict and verify no loss of data search_result_model_json2 = search_result_model.to_dict() assert search_result_model_json2 == search_result_model_json class TestModel_SearchResultProperties(): """ Test Class for SearchResultProperties """ def test_search_result_properties_serialization(self): """ Test serialization/deserialization for SearchResultProperties """ # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' search_result_row_model = {} # SearchResultRow search_result_row_model['doc'] = document_model search_result_row_model['fields'] = {} search_result_row_model['highlights'] = {} search_result_row_model['id'] = 'testString' # Construct a json representation of a SearchResultProperties model search_result_properties_model_json = {} search_result_properties_model_json['total_rows'] = 0 search_result_properties_model_json['bookmark'] = 'testString' search_result_properties_model_json['by'] = 'testString' search_result_properties_model_json['counts'] = {} search_result_properties_model_json['ranges'] = {} search_result_properties_model_json['rows'] = [search_result_row_model] # Construct a model instance of SearchResultProperties by calling from_dict on the json representation search_result_properties_model = SearchResultProperties.from_dict(search_result_properties_model_json) assert search_result_properties_model != False # Construct a model instance of SearchResultProperties by calling from_dict on the json representation search_result_properties_model_dict = SearchResultProperties.from_dict(search_result_properties_model_json).__dict__ search_result_properties_model2 = SearchResultProperties(**search_result_properties_model_dict) # Verify the model instances are equivalent assert search_result_properties_model == search_result_properties_model2 # Convert model instance back to dict and verify no loss of data search_result_properties_model_json2 = search_result_properties_model.to_dict() assert search_result_properties_model_json2 == search_result_properties_model_json class TestModel_SearchResultRow(): """ Test Class for SearchResultRow """ def test_search_result_row_serialization(self): """ Test serialization/deserialization for SearchResultRow """ # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' # Construct a json representation of a SearchResultRow model search_result_row_model_json = {} search_result_row_model_json['doc'] = document_model search_result_row_model_json['fields'] = {} search_result_row_model_json['highlights'] = {} search_result_row_model_json['id'] = 'testString' # Construct a model instance of SearchResultRow by calling from_dict on the json representation search_result_row_model = SearchResultRow.from_dict(search_result_row_model_json) assert search_result_row_model != False # Construct a model instance of SearchResultRow by calling from_dict on the json representation search_result_row_model_dict = SearchResultRow.from_dict(search_result_row_model_json).__dict__ search_result_row_model2 = SearchResultRow(**search_result_row_model_dict) # Verify the model instances are equivalent assert search_result_row_model == search_result_row_model2 # Convert model instance back to dict and verify no loss of data search_result_row_model_json2 = search_result_row_model.to_dict() assert search_result_row_model_json2 == search_result_row_model_json class TestModel_Security(): """ Test Class for Security """ def test_security_serialization(self): """ Test serialization/deserialization for Security """ # Construct dict forms of any model objects needed in order to build this model. security_object_model = {} # SecurityObject security_object_model['names'] = ['testString'] security_object_model['roles'] = ['testString'] # Construct a json representation of a Security model security_model_json = {} security_model_json['admins'] = security_object_model security_model_json['members'] = security_object_model security_model_json['cloudant'] = {} security_model_json['couchdb_auth_only'] = True # Construct a model instance of Security by calling from_dict on the json representation security_model = Security.from_dict(security_model_json) assert security_model != False # Construct a model instance of Security by calling from_dict on the json representation security_model_dict = Security.from_dict(security_model_json).__dict__ security_model2 = Security(**security_model_dict) # Verify the model instances are equivalent assert security_model == security_model2 # Convert model instance back to dict and verify no loss of data security_model_json2 = security_model.to_dict() assert security_model_json2 == security_model_json class TestModel_SecurityObject(): """ Test Class for SecurityObject """ def test_security_object_serialization(self): """ Test serialization/deserialization for SecurityObject """ # Construct a json representation of a SecurityObject model security_object_model_json = {} security_object_model_json['names'] = ['testString'] security_object_model_json['roles'] = ['testString'] # Construct a model instance of SecurityObject by calling from_dict on the json representation security_object_model = SecurityObject.from_dict(security_object_model_json) assert security_object_model != False # Construct a model instance of SecurityObject by calling from_dict on the json representation security_object_model_dict = SecurityObject.from_dict(security_object_model_json).__dict__ security_object_model2 = SecurityObject(**security_object_model_dict) # Verify the model instances are equivalent assert security_object_model == security_object_model2 # Convert model instance back to dict and verify no loss of data security_object_model_json2 = security_object_model.to_dict() assert security_object_model_json2 == security_object_model_json class TestModel_ServerInformation(): """ Test Class for ServerInformation """ def test_server_information_serialization(self): """ Test serialization/deserialization for ServerInformation """ # Construct dict forms of any model objects needed in order to build this model. server_vendor_model = {} # ServerVendor server_vendor_model['name'] = 'testString' server_vendor_model['variant'] = 'testString' server_vendor_model['version'] = 'testString' # Construct a json representation of a ServerInformation model server_information_model_json = {} server_information_model_json['couchdb'] = 'testString' server_information_model_json['features'] = ['testString'] server_information_model_json['vendor'] = server_vendor_model server_information_model_json['version'] = 'testString' server_information_model_json['features_flags'] = ['testString'] # Construct a model instance of ServerInformation by calling from_dict on the json representation server_information_model = ServerInformation.from_dict(server_information_model_json) assert server_information_model != False # Construct a model instance of ServerInformation by calling from_dict on the json representation server_information_model_dict = ServerInformation.from_dict(server_information_model_json).__dict__ server_information_model2 = ServerInformation(**server_information_model_dict) # Verify the model instances are equivalent assert server_information_model == server_information_model2 # Convert model instance back to dict and verify no loss of data server_information_model_json2 = server_information_model.to_dict() assert server_information_model_json2 == server_information_model_json class TestModel_ServerVendor(): """ Test Class for ServerVendor """ def test_server_vendor_serialization(self): """ Test serialization/deserialization for ServerVendor """ # Construct a json representation of a ServerVendor model server_vendor_model_json = {} server_vendor_model_json['name'] = 'testString' server_vendor_model_json['variant'] = 'testString' server_vendor_model_json['version'] = 'testString' # Construct a model instance of ServerVendor by calling from_dict on the json representation server_vendor_model = ServerVendor.from_dict(server_vendor_model_json) assert server_vendor_model != False # Construct a model instance of ServerVendor by calling from_dict on the json representation server_vendor_model_dict = ServerVendor.from_dict(server_vendor_model_json).__dict__ server_vendor_model2 = ServerVendor(**server_vendor_model_dict) # Verify the model instances are equivalent assert server_vendor_model == server_vendor_model2 # Convert model instance back to dict and verify no loss of data server_vendor_model_json2 = server_vendor_model.to_dict() assert server_vendor_model_json2 == server_vendor_model_json class TestModel_SessionAuthentication(): """ Test Class for SessionAuthentication """ def test_session_authentication_serialization(self): """ Test serialization/deserialization for SessionAuthentication """ # Construct a json representation of a SessionAuthentication model session_authentication_model_json = {} session_authentication_model_json['authenticated'] = 'testString' session_authentication_model_json['authentication_db'] = 'testString' session_authentication_model_json['authentication_handlers'] = ['testString'] # Construct a model instance of SessionAuthentication by calling from_dict on the json representation session_authentication_model = SessionAuthentication.from_dict(session_authentication_model_json) assert session_authentication_model != False # Construct a model instance of SessionAuthentication by calling from_dict on the json representation session_authentication_model_dict = SessionAuthentication.from_dict(session_authentication_model_json).__dict__ session_authentication_model2 = SessionAuthentication(**session_authentication_model_dict) # Verify the model instances are equivalent assert session_authentication_model == session_authentication_model2 # Convert model instance back to dict and verify no loss of data session_authentication_model_json2 = session_authentication_model.to_dict() assert session_authentication_model_json2 == session_authentication_model_json class TestModel_SessionInformation(): """ Test Class for SessionInformation """ def test_session_information_serialization(self): """ Test serialization/deserialization for SessionInformation """ # Construct dict forms of any model objects needed in order to build this model. session_authentication_model = {} # SessionAuthentication session_authentication_model['authenticated'] = 'testString' session_authentication_model['authentication_db'] = 'testString' session_authentication_model['authentication_handlers'] = ['testString'] user_context_model = {} # UserContext user_context_model['db'] = 'testString' user_context_model['name'] = 'testString' user_context_model['roles'] = ['_reader'] # Construct a json representation of a SessionInformation model session_information_model_json = {} session_information_model_json['ok'] = True session_information_model_json['info'] = session_authentication_model session_information_model_json['userCtx'] = user_context_model # Construct a model instance of SessionInformation by calling from_dict on the json representation session_information_model = SessionInformation.from_dict(session_information_model_json) assert session_information_model != False # Construct a model instance of SessionInformation by calling from_dict on the json representation session_information_model_dict = SessionInformation.from_dict(session_information_model_json).__dict__ session_information_model2 = SessionInformation(**session_information_model_dict) # Verify the model instances are equivalent assert session_information_model == session_information_model2 # Convert model instance back to dict and verify no loss of data session_information_model_json2 = session_information_model.to_dict() assert session_information_model_json2 == session_information_model_json class TestModel_ShardsInformation(): """ Test Class for ShardsInformation """ def test_shards_information_serialization(self): """ Test serialization/deserialization for ShardsInformation """ # Construct a json representation of a ShardsInformation model shards_information_model_json = {} shards_information_model_json['shards'] = {} # Construct a model instance of ShardsInformation by calling from_dict on the json representation shards_information_model = ShardsInformation.from_dict(shards_information_model_json) assert shards_information_model != False # Construct a model instance of ShardsInformation by calling from_dict on the json representation shards_information_model_dict = ShardsInformation.from_dict(shards_information_model_json).__dict__ shards_information_model2 = ShardsInformation(**shards_information_model_dict) # Verify the model instances are equivalent assert shards_information_model == shards_information_model2 # Convert model instance back to dict and verify no loss of data shards_information_model_json2 = shards_information_model.to_dict() assert shards_information_model_json2 == shards_information_model_json class TestModel_ThroughputInformation(): """ Test Class for ThroughputInformation """ def test_throughput_information_serialization(self): """ Test serialization/deserialization for ThroughputInformation """ # Construct a json representation of a ThroughputInformation model throughput_information_model_json = {} throughput_information_model_json['blocks'] = 0 throughput_information_model_json['query'] = 0 throughput_information_model_json['read'] = 0 throughput_information_model_json['write'] = 0 # Construct a model instance of ThroughputInformation by calling from_dict on the json representation throughput_information_model = ThroughputInformation.from_dict(throughput_information_model_json) assert throughput_information_model != False # Construct a model instance of ThroughputInformation by calling from_dict on the json representation throughput_information_model_dict = ThroughputInformation.from_dict(throughput_information_model_json).__dict__ throughput_information_model2 = ThroughputInformation(**throughput_information_model_dict) # Verify the model instances are equivalent assert throughput_information_model == throughput_information_model2 # Convert model instance back to dict and verify no loss of data throughput_information_model_json2 = throughput_information_model.to_dict() assert throughput_information_model_json2 == throughput_information_model_json class TestModel_UpInformation(): """ Test Class for UpInformation """ def test_up_information_serialization(self): """ Test serialization/deserialization for UpInformation """ # Construct a json representation of a UpInformation model up_information_model_json = {} up_information_model_json['seeds'] = { 'foo': 'bar' } up_information_model_json['status'] = 'maintenance_mode' # Construct a model instance of UpInformation by calling from_dict on the json representation up_information_model = UpInformation.from_dict(up_information_model_json) assert up_information_model != False # Construct a model instance of UpInformation by calling from_dict on the json representation up_information_model_dict = UpInformation.from_dict(up_information_model_json).__dict__ up_information_model2 = UpInformation(**up_information_model_dict) # Verify the model instances are equivalent assert up_information_model == up_information_model2 # Convert model instance back to dict and verify no loss of data up_information_model_json2 = up_information_model.to_dict() assert up_information_model_json2 == up_information_model_json class TestModel_UserContext(): """ Test Class for UserContext """ def test_user_context_serialization(self): """ Test serialization/deserialization for UserContext """ # Construct a json representation of a UserContext model user_context_model_json = {} user_context_model_json['db'] = 'testString' user_context_model_json['name'] = 'testString' user_context_model_json['roles'] = ['_reader'] # Construct a model instance of UserContext by calling from_dict on the json representation user_context_model = UserContext.from_dict(user_context_model_json) assert user_context_model != False # Construct a model instance of UserContext by calling from_dict on the json representation user_context_model_dict = UserContext.from_dict(user_context_model_json).__dict__ user_context_model2 = UserContext(**user_context_model_dict) # Verify the model instances are equivalent assert user_context_model == user_context_model2 # Convert model instance back to dict and verify no loss of data user_context_model_json2 = user_context_model.to_dict() assert user_context_model_json2 == user_context_model_json class TestModel_UuidsResult(): """ Test Class for UuidsResult """ def test_uuids_result_serialization(self): """ Test serialization/deserialization for UuidsResult """ # Construct a json representation of a UuidsResult model uuids_result_model_json = {} uuids_result_model_json['uuids'] = ['testString'] # Construct a model instance of UuidsResult by calling from_dict on the json representation uuids_result_model = UuidsResult.from_dict(uuids_result_model_json) assert uuids_result_model != False # Construct a model instance of UuidsResult by calling from_dict on the json representation uuids_result_model_dict = UuidsResult.from_dict(uuids_result_model_json).__dict__ uuids_result_model2 = UuidsResult(**uuids_result_model_dict) # Verify the model instances are equivalent assert uuids_result_model == uuids_result_model2 # Convert model instance back to dict and verify no loss of data uuids_result_model_json2 = uuids_result_model.to_dict() assert uuids_result_model_json2 == uuids_result_model_json class TestModel_ViewQueriesResult(): """ Test Class for ViewQueriesResult """ def test_view_queries_result_serialization(self): """ Test serialization/deserialization for ViewQueriesResult """ # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' view_result_row_model = {} # ViewResultRow view_result_row_model['caused_by'] = 'testString' view_result_row_model['error'] = 'testString' view_result_row_model['reason'] = 'testString' view_result_row_model['doc'] = document_model view_result_row_model['id'] = 'testString' view_result_row_model['key'] = 'testString' view_result_row_model['value'] = 'testString' view_result_model = {} # ViewResult view_result_model['total_rows'] = 0 view_result_model['update_seq'] = 'testString' view_result_model['rows'] = [view_result_row_model] # Construct a json representation of a ViewQueriesResult model view_queries_result_model_json = {} view_queries_result_model_json['results'] = [view_result_model] # Construct a model instance of ViewQueriesResult by calling from_dict on the json representation view_queries_result_model = ViewQueriesResult.from_dict(view_queries_result_model_json) assert view_queries_result_model != False # Construct a model instance of ViewQueriesResult by calling from_dict on the json representation view_queries_result_model_dict = ViewQueriesResult.from_dict(view_queries_result_model_json).__dict__ view_queries_result_model2 = ViewQueriesResult(**view_queries_result_model_dict) # Verify the model instances are equivalent assert view_queries_result_model == view_queries_result_model2 # Convert model instance back to dict and verify no loss of data view_queries_result_model_json2 = view_queries_result_model.to_dict() assert view_queries_result_model_json2 == view_queries_result_model_json class TestModel_ViewQuery(): """ Test Class for ViewQuery """ def test_view_query_serialization(self): """ Test serialization/deserialization for ViewQuery """ # Construct a json representation of a ViewQuery model view_query_model_json = {} view_query_model_json['att_encoding_info'] = False view_query_model_json['attachments'] = False view_query_model_json['conflicts'] = False view_query_model_json['descending'] = False view_query_model_json['include_docs'] = False view_query_model_json['inclusive_end'] = True view_query_model_json['limit'] = 0 view_query_model_json['skip'] = 0 view_query_model_json['update_seq'] = False view_query_model_json['endkey'] = 'testString' view_query_model_json['endkey_docid'] = 'testString' view_query_model_json['group'] = False view_query_model_json['group_level'] = 1 view_query_model_json['key'] = 'testString' view_query_model_json['keys'] = ['testString'] view_query_model_json['reduce'] = True view_query_model_json['stable'] = False view_query_model_json['startkey'] = 'testString' view_query_model_json['startkey_docid'] = 'testString' view_query_model_json['update'] = 'true' # Construct a model instance of ViewQuery by calling from_dict on the json representation view_query_model = ViewQuery.from_dict(view_query_model_json) assert view_query_model != False # Construct a model instance of ViewQuery by calling from_dict on the json representation view_query_model_dict = ViewQuery.from_dict(view_query_model_json).__dict__ view_query_model2 = ViewQuery(**view_query_model_dict) # Verify the model instances are equivalent assert view_query_model == view_query_model2 # Convert model instance back to dict and verify no loss of data view_query_model_json2 = view_query_model.to_dict() assert view_query_model_json2 == view_query_model_json class TestModel_ViewResult(): """ Test Class for ViewResult """ def test_view_result_serialization(self): """ Test serialization/deserialization for ViewResult """ # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' view_result_row_model = {} # ViewResultRow view_result_row_model['caused_by'] = 'testString' view_result_row_model['error'] = 'testString' view_result_row_model['reason'] = 'testString' view_result_row_model['doc'] = document_model view_result_row_model['id'] = 'testString' view_result_row_model['key'] = 'testString' view_result_row_model['value'] = 'testString' # Construct a json representation of a ViewResult model view_result_model_json = {} view_result_model_json['total_rows'] = 0 view_result_model_json['update_seq'] = 'testString' view_result_model_json['rows'] = [view_result_row_model] # Construct a model instance of ViewResult by calling from_dict on the json representation view_result_model = ViewResult.from_dict(view_result_model_json) assert view_result_model != False # Construct a model instance of ViewResult by calling from_dict on the json representation view_result_model_dict = ViewResult.from_dict(view_result_model_json).__dict__ view_result_model2 = ViewResult(**view_result_model_dict) # Verify the model instances are equivalent assert view_result_model == view_result_model2 # Convert model instance back to dict and verify no loss of data view_result_model_json2 = view_result_model.to_dict() assert view_result_model_json2 == view_result_model_json class TestModel_ViewResultRow(): """ Test Class for ViewResultRow """ def test_view_result_row_serialization(self): """ Test serialization/deserialization for ViewResultRow """ # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' # Construct a json representation of a ViewResultRow model view_result_row_model_json = {} view_result_row_model_json['caused_by'] = 'testString' view_result_row_model_json['error'] = 'testString' view_result_row_model_json['reason'] = 'testString' view_result_row_model_json['doc'] = document_model view_result_row_model_json['id'] = 'testString' view_result_row_model_json['key'] = 'testString' view_result_row_model_json['value'] = 'testString' # Construct a model instance of ViewResultRow by calling from_dict on the json representation view_result_row_model = ViewResultRow.from_dict(view_result_row_model_json) assert view_result_row_model != False # Construct a model instance of ViewResultRow by calling from_dict on the json representation view_result_row_model_dict = ViewResultRow.from_dict(view_result_row_model_json).__dict__ view_result_row_model2 = ViewResultRow(**view_result_row_model_dict) # Verify the model instances are equivalent assert view_result_row_model == view_result_row_model2 # Convert model instance back to dict and verify no loss of data view_result_row_model_json2 = view_result_row_model.to_dict() assert view_result_row_model_json2 == view_result_row_model_json class TestModel_GeoJsonGeometry(): """ Test Class for GeoJsonGeometry """ def test_geo_json_geometry_serialization(self): """ Test serialization/deserialization for GeoJsonGeometry """ # Construct a json representation of a GeoJsonGeometry model geo_json_geometry_model_json = {} geo_json_geometry_model_json['type'] = 'Point' geo_json_geometry_model_json['coordinates'] = ['testString'] # Construct a model instance of GeoJsonGeometry by calling from_dict on the json representation geo_json_geometry_model = GeoJsonGeometry.from_dict(geo_json_geometry_model_json) assert geo_json_geometry_model != False # Construct a model instance of GeoJsonGeometry by calling from_dict on the json representation geo_json_geometry_model_dict = GeoJsonGeometry.from_dict(geo_json_geometry_model_json).__dict__ geo_json_geometry_model2 = GeoJsonGeometry(**geo_json_geometry_model_dict) # Verify the model instances are equivalent assert geo_json_geometry_model == geo_json_geometry_model2 # Convert model instance back to dict and verify no loss of data geo_json_geometry_model_json2 = geo_json_geometry_model.to_dict() assert geo_json_geometry_model_json2 == geo_json_geometry_model_json class TestModel_GeoJsonGeometryCollection(): """ Test Class for GeoJsonGeometryCollection """ def test_geo_json_geometry_collection_serialization(self): """ Test serialization/deserialization for GeoJsonGeometryCollection """ # Construct dict forms of any model objects needed in order to build this model. geo_json_geometry_model = {} # GeoJsonGeometry geo_json_geometry_model['type'] = 'Point' geo_json_geometry_model['coordinates'] = ['testString'] # Construct a json representation of a GeoJsonGeometryCollection model geo_json_geometry_collection_model_json = {} geo_json_geometry_collection_model_json['type'] = 'Point' geo_json_geometry_collection_model_json['geometries'] = [geo_json_geometry_model] # Construct a model instance of GeoJsonGeometryCollection by calling from_dict on the json representation geo_json_geometry_collection_model = GeoJsonGeometryCollection.from_dict(geo_json_geometry_collection_model_json) assert geo_json_geometry_collection_model != False # Construct a model instance of GeoJsonGeometryCollection by calling from_dict on the json representation geo_json_geometry_collection_model_dict = GeoJsonGeometryCollection.from_dict(geo_json_geometry_collection_model_json).__dict__ geo_json_geometry_collection_model2 = GeoJsonGeometryCollection(**geo_json_geometry_collection_model_dict) # Verify the model instances are equivalent assert geo_json_geometry_collection_model == geo_json_geometry_collection_model2 # Convert model instance back to dict and verify no loss of data geo_json_geometry_collection_model_json2 = geo_json_geometry_collection_model.to_dict() assert geo_json_geometry_collection_model_json2 == geo_json_geometry_collection_model_json # endregion ############################################################################## # End of Model Tests ##############################################################################
41.556629
1,470
0.647074
from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime import base64 import inspect import io import json import os import pytest import re import requests import requests.models import responses import tempfile import urllib import gzip from ibmcloudant.cloudant_v1 import * _service = CloudantV1( authenticator=NoAuthAuthenticator() ) _base_url = 'http://localhost:5984' _service.set_service_url(_base_url) y encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_capacity_throughput_information_all_params(self): url = self.preprocess_url(_base_url + '/_api/v2/user/capacity/throughput') mock_response = '{"current": {"throughput": {"blocks": 0, "query": 0, "read": 0, "write": 0}}, "target": {"throughput": {"blocks": 0, "query": 0, "read": 0, "write": 0}}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) response = _service.get_capacity_throughput_information() assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_capacity_throughput_information_all_params_with_retries(self): _service.enable_retries() self.test_get_capacity_throughput_information_all_params() _service.disable_retries() self.test_get_capacity_throughput_information_all_params() class TestPutCapacityThroughputConfiguration(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_put_capacity_throughput_configuration_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/_api/v2/user/capacity/throughput') mock_response = '{"current": {"throughput": {"blocks": 0, "query": 0, "read": 0, "write": 0}}, "target": {"throughput": {"blocks": 0, "query": 0, "read": 0, "write": 0}}}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values blocks = 0 # Invoke method response = _service.put_capacity_throughput_configuration( blocks, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['blocks'] == 0 def test_put_capacity_throughput_configuration_all_params_with_retries(self): # Enable retries and run test_put_capacity_throughput_configuration_all_params. _service.enable_retries() self.test_put_capacity_throughput_configuration_all_params() # Disable retries and run test_put_capacity_throughput_configuration_all_params. _service.disable_retries() self.test_put_capacity_throughput_configuration_all_params() @responses.activate def test_put_capacity_throughput_configuration_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/_api/v2/user/capacity/throughput') mock_response = '{"current": {"throughput": {"blocks": 0, "query": 0, "read": 0, "write": 0}}, "target": {"throughput": {"blocks": 0, "query": 0, "read": 0, "write": 0}}}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values blocks = 0 # Pass in all but one required param and check for a ValueError req_param_dict = { "blocks": blocks, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.put_capacity_throughput_configuration(**req_copy) def test_put_capacity_throughput_configuration_value_error_with_retries(self): # Enable retries and run test_put_capacity_throughput_configuration_value_error. _service.enable_retries() self.test_put_capacity_throughput_configuration_value_error() # Disable retries and run test_put_capacity_throughput_configuration_value_error. _service.disable_retries() self.test_put_capacity_throughput_configuration_value_error() # endregion ############################################################################## # End of Service: Server ############################################################################## ############################################################################## # Start of Service: Changes ############################################################################## # region class TestNewInstance(): def test_new_instance(self): os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestGetDbUpdates(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_db_updates_all_params(self): url = self.preprocess_url(_base_url + '/_db_updates') mock_response = '{"last_seq": "last_seq", "results": [{"account": "account", "db_name": "db_name", "seq": "seq", "type": "created"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) feed = 'normal' heartbeat = 0 timeout = 0 since = '0' response = _service.get_db_updates( feed=feed, heartbeat=heartbeat, timeout=timeout, since=since, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'feed={}'.format(feed) in query_string assert 'heartbeat={}'.format(heartbeat) in query_string assert 'timeout={}'.format(timeout) in query_string assert 'since={}'.format(since) in query_string def test_get_db_updates_all_params_with_retries(self): _service.enable_retries() self.test_get_db_updates_all_params() _service.disable_retries() self.test_get_db_updates_all_params() @responses.activate def test_get_db_updates_required_params(self): url = self.preprocess_url(_base_url + '/_db_updates') mock_response = '{"last_seq": "last_seq", "results": [{"account": "account", "db_name": "db_name", "seq": "seq", "type": "created"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) response = _service.get_db_updates() assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_db_updates_required_params_with_retries(self): _service.enable_retries() self.test_get_db_updates_required_params() _service.disable_retries() self.test_get_db_updates_required_params() class TestPostChanges(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_changes_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_changes') mock_response = '{"last_seq": "last_seq", "pending": 7, "results": [{"changes": [{"rev": "rev"}], "deleted": false, "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "seq": "seq"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_ids = ['testString'] fields = ['testString'] selector = {} last_event_id = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False feed = 'normal' filter = 'testString' heartbeat = 0 include_docs = False limit = 0 seq_interval = 1 since = '0' style = 'main_only' timeout = 0 view = 'testString' # Invoke method response = _service.post_changes( db, doc_ids=doc_ids, fields=fields, selector=selector, last_event_id=last_event_id, att_encoding_info=att_encoding_info, attachments=attachments, conflicts=conflicts, descending=descending, feed=feed, filter=filter, heartbeat=heartbeat, include_docs=include_docs, limit=limit, seq_interval=seq_interval, since=since, style=style, timeout=timeout, view=view, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'conflicts={}'.format('true' if conflicts else 'false') in query_string assert 'descending={}'.format('true' if descending else 'false') in query_string assert 'feed={}'.format(feed) in query_string assert 'filter={}'.format(filter) in query_string assert 'heartbeat={}'.format(heartbeat) in query_string assert 'include_docs={}'.format('true' if include_docs else 'false') in query_string assert 'limit={}'.format(limit) in query_string assert 'seq_interval={}'.format(seq_interval) in query_string assert 'since={}'.format(since) in query_string assert 'style={}'.format(style) in query_string assert 'timeout={}'.format(timeout) in query_string assert 'view={}'.format(view) in query_string # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['doc_ids'] == ['testString'] assert req_body['fields'] == ['testString'] assert req_body['selector'] == {} def test_post_changes_all_params_with_retries(self): # Enable retries and run test_post_changes_all_params. _service.enable_retries() self.test_post_changes_all_params() # Disable retries and run test_post_changes_all_params. _service.disable_retries() self.test_post_changes_all_params() @responses.activate def test_post_changes_required_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_changes') mock_response = '{"last_seq": "last_seq", "pending": 7, "results": [{"changes": [{"rev": "rev"}], "deleted": false, "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "seq": "seq"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_ids = ['testString'] fields = ['testString'] selector = {} # Invoke method response = _service.post_changes( db, doc_ids=doc_ids, fields=fields, selector=selector, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['doc_ids'] == ['testString'] assert req_body['fields'] == ['testString'] assert req_body['selector'] == {} def test_post_changes_required_params_with_retries(self): # Enable retries and run test_post_changes_required_params. _service.enable_retries() self.test_post_changes_required_params() # Disable retries and run test_post_changes_required_params. _service.disable_retries() self.test_post_changes_required_params() @responses.activate def test_post_changes_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_changes') mock_response = '{"last_seq": "last_seq", "pending": 7, "results": [{"changes": [{"rev": "rev"}], "deleted": false, "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "seq": "seq"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_ids = ['testString'] fields = ['testString'] selector = {} # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_changes(**req_copy) def test_post_changes_value_error_with_retries(self): # Enable retries and run test_post_changes_value_error. _service.enable_retries() self.test_post_changes_value_error() # Disable retries and run test_post_changes_value_error. _service.disable_retries() self.test_post_changes_value_error() class TestPostChangesAsStream(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_changes_as_stream_all_params(self): url = self.preprocess_url(_base_url + '/testString/_changes') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) db = 'testString' doc_ids = ['0007741142412418284'] fields = ['testString'] selector = {} last_event_id = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False feed = 'normal' filter = 'testString' heartbeat = 0 include_docs = False limit = 0 seq_interval = 1 since = '0' style = 'main_only' timeout = 0 view = 'testString' response = _service.post_changes_as_stream( db, doc_ids=doc_ids, fields=fields, selector=selector, last_event_id=last_event_id, att_encoding_info=att_encoding_info, attachments=attachments, conflicts=conflicts, descending=descending, feed=feed, filter=filter, heartbeat=heartbeat, include_docs=include_docs, limit=limit, seq_interval=seq_interval, since=since, style=style, timeout=timeout, view=view, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'conflicts={}'.format('true' if conflicts else 'false') in query_string assert 'descending={}'.format('true' if descending else 'false') in query_string assert 'feed={}'.format(feed) in query_string assert 'filter={}'.format(filter) in query_string assert 'heartbeat={}'.format(heartbeat) in query_string assert 'include_docs={}'.format('true' if include_docs else 'false') in query_string assert 'limit={}'.format(limit) in query_string assert 'seq_interval={}'.format(seq_interval) in query_string assert 'since={}'.format(since) in query_string assert 'style={}'.format(style) in query_string assert 'timeout={}'.format(timeout) in query_string assert 'view={}'.format(view) in query_string responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['doc_ids'] == ['0007741142412418284'] assert req_body['fields'] == ['testString'] assert req_body['selector'] == {} result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_changes_as_stream_all_params_with_retries(self): _service.enable_retries() self.test_post_changes_as_stream_all_params() _service.disable_retries() self.test_post_changes_as_stream_all_params() @responses.activate def test_post_changes_as_stream_required_params(self): url = self.preprocess_url(_base_url + '/testString/_changes') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) db = 'testString' doc_ids = ['0007741142412418284'] fields = ['testString'] selector = {} response = _service.post_changes_as_stream( db, doc_ids=doc_ids, fields=fields, selector=selector, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['doc_ids'] == ['0007741142412418284'] assert req_body['fields'] == ['testString'] assert req_body['selector'] == {} result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_changes_as_stream_required_params_with_retries(self): _service.enable_retries() self.test_post_changes_as_stream_required_params() _service.disable_retries() self.test_post_changes_as_stream_required_params() @responses.activate def test_post_changes_as_stream_value_error(self): url = self.preprocess_url(_base_url + '/testString/_changes') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) db = 'testString' doc_ids = ['0007741142412418284'] fields = ['testString'] selector = {} req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_changes_as_stream(**req_copy) def test_post_changes_as_stream_value_error_with_retries(self): _service.enable_retries() self.test_post_changes_as_stream_value_error() _service.disable_retries() self.test_post_changes_as_stream_value_error() cluster": {"n": 1, "q": 1, "r": 1, "w": 1}, "committed_update_seq": "committed_update_seq", "compact_running": false, "compacted_seq": "compacted_seq", "db_name": "db_name", "disk_format_version": 19, "doc_count": 0, "doc_del_count": 0, "engine": "engine", "props": {"partitioned": false}, "sizes": {"active": 6, "external": 8, "file": 4}, "update_seq": "update_seq", "uuid": "uuid"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' # Invoke method response = _service.get_database_information( db, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_database_information_all_params_with_retries(self): # Enable retries and run test_get_database_information_all_params. _service.enable_retries() self.test_get_database_information_all_params() # Disable retries and run test_get_database_information_all_params. _service.disable_retries() self.test_get_database_information_all_params() @responses.activate def test_get_database_information_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString') mock_response = '{"cluster": {"n": 1, "q": 1, "r": 1, "w": 1}, "committed_update_seq": "committed_update_seq", "compact_running": false, "compacted_seq": "compacted_seq", "db_name": "db_name", "disk_format_version": 19, "doc_count": 0, "doc_del_count": 0, "engine": "engine", "props": {"partitioned": false}, "sizes": {"active": 6, "external": 8, "file": 4}, "update_seq": "update_seq", "uuid": "uuid"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_database_information(**req_copy) def test_get_database_information_value_error_with_retries(self): # Enable retries and run test_get_database_information_value_error. _service.enable_retries() self.test_get_database_information_value_error() # Disable retries and run test_get_database_information_value_error. _service.disable_retries() self.test_get_database_information_value_error() class TestPutDatabase(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_put_database_all_params(self): url = self.preprocess_url(_base_url + '/testString') mock_response = '{"ok": true}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) db = 'testString' partitioned = False q = 1 response = _service.put_database( db, partitioned=partitioned, q=q, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 201 query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'partitioned={}'.format('true' if partitioned else 'false') in query_string assert 'q={}'.format(q) in query_string def test_put_database_all_params_with_retries(self): _service.enable_retries() self.test_put_database_all_params() _service.disable_retries() self.test_put_database_all_params() @responses.activate def test_put_database_required_params(self): url = self.preprocess_url(_base_url + '/testString') mock_response = '{"ok": true}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) db = 'testString' response = _service.put_database( db, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 201 def test_put_database_required_params_with_retries(self): _service.enable_retries() self.test_put_database_required_params() _service.disable_retries() self.test_put_database_required_params() @responses.activate def test_put_database_value_error(self): url = self.preprocess_url(_base_url + '/testString') mock_response = '{"ok": true}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) db = 'testString' req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.put_database(**req_copy) def test_put_database_value_error_with_retries(self): _service.enable_retries() self.test_put_database_value_error() _service.disable_retries() self.test_put_database_value_error() } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_document(**req_copy) def test_post_document_value_error_with_retries(self): _service.enable_retries() self.test_post_document_value_error() _service.disable_retries() self.test_post_document_value_error() class TestPostAllDocs(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_all_docs_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_all_docs') mock_response = '{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 0 skip = 0 update_seq = False endkey = 'testString' key = 'testString' keys = ['testString'] startkey = 'testString' # Invoke method response = _service.post_all_docs( db, att_encoding_info=att_encoding_info, attachments=attachments, conflicts=conflicts, descending=descending, include_docs=include_docs, inclusive_end=inclusive_end, limit=limit, skip=skip, update_seq=update_seq, endkey=endkey, key=key, keys=keys, startkey=startkey, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['att_encoding_info'] == False assert req_body['attachments'] == False assert req_body['conflicts'] == False assert req_body['descending'] == False assert req_body['include_docs'] == False assert req_body['inclusive_end'] == True assert req_body['limit'] == 0 assert req_body['skip'] == 0 assert req_body['update_seq'] == False assert req_body['endkey'] == 'testString' assert req_body['key'] == 'testString' assert req_body['keys'] == ['testString'] assert req_body['startkey'] == 'testString' def test_post_all_docs_all_params_with_retries(self): # Enable retries and run test_post_all_docs_all_params. _service.enable_retries() self.test_post_all_docs_all_params() # Disable retries and run test_post_all_docs_all_params. _service.disable_retries() self.test_post_all_docs_all_params() @responses.activate def test_post_all_docs_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_all_docs') mock_response = '{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 0 skip = 0 update_seq = False endkey = 'testString' key = 'testString' keys = ['testString'] startkey = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_all_docs(**req_copy) def test_post_all_docs_value_error_with_retries(self): # Enable retries and run test_post_all_docs_value_error. _service.enable_retries() self.test_post_all_docs_value_error() # Disable retries and run test_post_all_docs_value_error. _service.disable_retries() self.test_post_all_docs_value_error() class TestPostAllDocsAsStream(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_all_docs_as_stream_all_params(self): url = self.preprocess_url(_base_url + '/testString/_all_docs') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) db = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' key = 'testString' keys = ['testString'] startkey = '0007741142412418284' response = _service.post_all_docs_as_stream( db, att_encoding_info=att_encoding_info, attachments=attachments, conflicts=conflicts, descending=descending, include_docs=include_docs, inclusive_end=inclusive_end, limit=limit, skip=skip, update_seq=update_seq, endkey=endkey, key=key, keys=keys, startkey=startkey, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['att_encoding_info'] == False assert req_body['attachments'] == False assert req_body['conflicts'] == False assert req_body['descending'] == False assert req_body['include_docs'] == False assert req_body['inclusive_end'] == True assert req_body['limit'] == 10 assert req_body['skip'] == 0 assert req_body['update_seq'] == False assert req_body['endkey'] == 'testString' assert req_body['key'] == 'testString' assert req_body['keys'] == ['testString'] assert req_body['startkey'] == '0007741142412418284' result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_all_docs_as_stream_all_params_with_retries(self): _service.enable_retries() self.test_post_all_docs_as_stream_all_params() _service.disable_retries() self.test_post_all_docs_as_stream_all_params() @responses.activate def test_post_all_docs_as_stream_value_error(self): url = self.preprocess_url(_base_url + '/testString/_all_docs') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) db = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' key = 'testString' keys = ['testString'] startkey = '0007741142412418284' req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_all_docs_as_stream(**req_copy) def test_post_all_docs_as_stream_value_error_with_retries(self): _service.enable_retries() self.test_post_all_docs_as_stream_value_error() _service.disable_retries() self.test_post_all_docs_as_stream_value_error() class TestPostAllDocsQueries(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_all_docs_queries_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_all_docs/queries') mock_response = '{"results": [{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a AllDocsQuery model all_docs_query_model = {} all_docs_query_model['att_encoding_info'] = False all_docs_query_model['attachments'] = False all_docs_query_model['conflicts'] = False all_docs_query_model['descending'] = False all_docs_query_model['include_docs'] = False all_docs_query_model['inclusive_end'] = True all_docs_query_model['limit'] = 0 all_docs_query_model['skip'] = 0 all_docs_query_model['update_seq'] = False all_docs_query_model['endkey'] = 'testString' all_docs_query_model['key'] = 'testString' all_docs_query_model['keys'] = ['testString'] all_docs_query_model['startkey'] = 'testString' # Set up parameter values db = 'testString' queries = [all_docs_query_model] # Invoke method response = _service.post_all_docs_queries( db, queries, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['queries'] == [all_docs_query_model] def test_post_all_docs_queries_all_params_with_retries(self): # Enable retries and run test_post_all_docs_queries_all_params. _service.enable_retries() self.test_post_all_docs_queries_all_params() # Disable retries and run test_post_all_docs_queries_all_params. _service.disable_retries() self.test_post_all_docs_queries_all_params() @responses.activate def test_post_all_docs_queries_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_all_docs/queries') mock_response = '{"results": [{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a AllDocsQuery model all_docs_query_model = {} all_docs_query_model['att_encoding_info'] = False all_docs_query_model['attachments'] = False all_docs_query_model['conflicts'] = False all_docs_query_model['descending'] = False all_docs_query_model['include_docs'] = False all_docs_query_model['inclusive_end'] = True all_docs_query_model['limit'] = 0 all_docs_query_model['skip'] = 0 all_docs_query_model['update_seq'] = False all_docs_query_model['endkey'] = 'testString' all_docs_query_model['key'] = 'testString' all_docs_query_model['keys'] = ['testString'] all_docs_query_model['startkey'] = 'testString' # Set up parameter values db = 'testString' queries = [all_docs_query_model] # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "queries": queries, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_all_docs_queries(**req_copy) def test_post_all_docs_queries_value_error_with_retries(self): # Enable retries and run test_post_all_docs_queries_value_error. _service.enable_retries() self.test_post_all_docs_queries_value_error() # Disable retries and run test_post_all_docs_queries_value_error. _service.disable_retries() self.test_post_all_docs_queries_value_error() class TestPostAllDocsQueriesAsStream(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_all_docs_queries_as_stream_all_params(self): url = self.preprocess_url(_base_url + '/testString/_all_docs/queries') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) all_docs_query_model = {} all_docs_query_model['att_encoding_info'] = False all_docs_query_model['attachments'] = False all_docs_query_model['conflicts'] = False all_docs_query_model['descending'] = False all_docs_query_model['include_docs'] = False all_docs_query_model['inclusive_end'] = True all_docs_query_model['limit'] = 0 all_docs_query_model['skip'] = 0 all_docs_query_model['update_seq'] = False all_docs_query_model['endkey'] = 'testString' all_docs_query_model['key'] = 'testString' all_docs_query_model['keys'] = ['small-appliances:1000042', 'small-appliances:1000043'] all_docs_query_model['startkey'] = 'testString' db = 'testString' queries = [all_docs_query_model] response = _service.post_all_docs_queries_as_stream( db, queries, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['queries'] == [all_docs_query_model] result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_all_docs_queries_as_stream_all_params_with_retries(self): _service.enable_retries() self.test_post_all_docs_queries_as_stream_all_params() _service.disable_retries() self.test_post_all_docs_queries_as_stream_all_params() @responses.activate def test_post_all_docs_queries_as_stream_value_error(self): url = self.preprocess_url(_base_url + '/testString/_all_docs/queries') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) all_docs_query_model = {} all_docs_query_model['att_encoding_info'] = False all_docs_query_model['attachments'] = False all_docs_query_model['conflicts'] = False all_docs_query_model['descending'] = False all_docs_query_model['include_docs'] = False all_docs_query_model['inclusive_end'] = True all_docs_query_model['limit'] = 0 all_docs_query_model['skip'] = 0 all_docs_query_model['update_seq'] = False all_docs_query_model['endkey'] = 'testString' all_docs_query_model['key'] = 'testString' all_docs_query_model['keys'] = ['small-appliances:1000042', 'small-appliances:1000043'] all_docs_query_model['startkey'] = 'testString' db = 'testString' queries = [all_docs_query_model] req_param_dict = { "db": db, "queries": queries, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_all_docs_queries_as_stream(**req_copy) def test_post_all_docs_queries_as_stream_value_error_with_retries(self): _service.enable_retries() self.test_post_all_docs_queries_as_stream_value_error() _service.disable_retries() self.test_post_all_docs_queries_as_stream_value_error() class TestPostBulkDocs(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_bulk_docs_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_docs') mock_response = '[{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}]' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Document model document_model = {} document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' # Construct a dict representation of a BulkDocs model bulk_docs_model = {} bulk_docs_model['docs'] = [document_model] bulk_docs_model['new_edits'] = True # Set up parameter values db = 'testString' bulk_docs = bulk_docs_model # Invoke method response = _service.post_bulk_docs( db, bulk_docs, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body == bulk_docs def test_post_bulk_docs_all_params_with_retries(self): # Enable retries and run test_post_bulk_docs_all_params. _service.enable_retries() self.test_post_bulk_docs_all_params() # Disable retries and run test_post_bulk_docs_all_params. _service.disable_retries() self.test_post_bulk_docs_all_params() @responses.activate def test_post_bulk_docs_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_docs') mock_response = '[{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}]' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Document model document_model = {} document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' # Construct a dict representation of a BulkDocs model bulk_docs_model = {} bulk_docs_model['docs'] = [document_model] bulk_docs_model['new_edits'] = True # Set up parameter values db = 'testString' bulk_docs = bulk_docs_model # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "bulk_docs": bulk_docs, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_bulk_docs(**req_copy) def test_post_bulk_docs_value_error_with_retries(self): # Enable retries and run test_post_bulk_docs_value_error. _service.enable_retries() self.test_post_bulk_docs_value_error() # Disable retries and run test_post_bulk_docs_value_error. _service.disable_retries() self.test_post_bulk_docs_value_error() class TestPostBulkGet(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_bulk_get_all_params(self): url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = '{"results": [{"docs": [{"error": {"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}, "ok": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}}], "id": "id"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'testString' bulk_get_query_document_model['rev'] = 'testString' db = 'testString' docs = [bulk_get_query_document_model] attachments = False att_encoding_info = False latest = False revs = False response = _service.post_bulk_get( db, docs, attachments=attachments, att_encoding_info=att_encoding_info, latest=latest, revs=revs, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'revs={}'.format('true' if revs else 'false') in query_string responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['docs'] == [bulk_get_query_document_model] def test_post_bulk_get_all_params_with_retries(self): _service.enable_retries() self.test_post_bulk_get_all_params() _service.disable_retries() self.test_post_bulk_get_all_params() @responses.activate def test_post_bulk_get_required_params(self): url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = '{"results": [{"docs": [{"error": {"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}, "ok": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}}], "id": "id"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'testString' bulk_get_query_document_model['rev'] = 'testString' db = 'testString' docs = [bulk_get_query_document_model] response = _service.post_bulk_get( db, docs, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['docs'] == [bulk_get_query_document_model] def test_post_bulk_get_required_params_with_retries(self): _service.enable_retries() self.test_post_bulk_get_required_params() _service.disable_retries() self.test_post_bulk_get_required_params() @responses.activate def test_post_bulk_get_value_error(self): url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = '{"results": [{"docs": [{"error": {"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}, "ok": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}}], "id": "id"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'testString' bulk_get_query_document_model['rev'] = 'testString' db = 'testString' docs = [bulk_get_query_document_model] req_param_dict = { "db": db, "docs": docs, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_bulk_get(**req_copy) def test_post_bulk_get_value_error_with_retries(self): _service.enable_retries() self.test_post_bulk_get_value_error() _service.disable_retries() self.test_post_bulk_get_value_error() class TestPostBulkGetAsMixed(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_bulk_get_as_mixed_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = 'This is a mock binary response.' responses.add(responses.POST, url, body=mock_response, content_type='multipart/mixed', status=200) # Construct a dict representation of a BulkGetQueryDocument model bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'order00067' bulk_get_query_document_model['rev'] = '3-917fa2381192822767f010b95b45325b' # Set up parameter values db = 'testString' docs = [bulk_get_query_document_model] attachments = False att_encoding_info = False latest = False revs = False # Invoke method response = _service.post_bulk_get_as_mixed( db, docs, attachments=attachments, att_encoding_info=att_encoding_info, latest=latest, revs=revs, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'revs={}'.format('true' if revs else 'false') in query_string # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['docs'] == [bulk_get_query_document_model] def test_post_bulk_get_as_mixed_all_params_with_retries(self): # Enable retries and run test_post_bulk_get_as_mixed_all_params. _service.enable_retries() self.test_post_bulk_get_as_mixed_all_params() # Disable retries and run test_post_bulk_get_as_mixed_all_params. _service.disable_retries() self.test_post_bulk_get_as_mixed_all_params() @responses.activate def test_post_bulk_get_as_mixed_required_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = 'This is a mock binary response.' responses.add(responses.POST, url, body=mock_response, content_type='multipart/mixed', status=200) # Construct a dict representation of a BulkGetQueryDocument model bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'order00067' bulk_get_query_document_model['rev'] = '3-917fa2381192822767f010b95b45325b' # Set up parameter values db = 'testString' docs = [bulk_get_query_document_model] # Invoke method response = _service.post_bulk_get_as_mixed( db, docs, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['docs'] == [bulk_get_query_document_model] def test_post_bulk_get_as_mixed_required_params_with_retries(self): # Enable retries and run test_post_bulk_get_as_mixed_required_params. _service.enable_retries() self.test_post_bulk_get_as_mixed_required_params() # Disable retries and run test_post_bulk_get_as_mixed_required_params. _service.disable_retries() self.test_post_bulk_get_as_mixed_required_params() @responses.activate def test_post_bulk_get_as_mixed_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = 'This is a mock binary response.' responses.add(responses.POST, url, body=mock_response, content_type='multipart/mixed', status=200) # Construct a dict representation of a BulkGetQueryDocument model bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'order00067' bulk_get_query_document_model['rev'] = '3-917fa2381192822767f010b95b45325b' # Set up parameter values db = 'testString' docs = [bulk_get_query_document_model] # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "docs": docs, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_bulk_get_as_mixed(**req_copy) def test_post_bulk_get_as_mixed_value_error_with_retries(self): # Enable retries and run test_post_bulk_get_as_mixed_value_error. _service.enable_retries() self.test_post_bulk_get_as_mixed_value_error() # Disable retries and run test_post_bulk_get_as_mixed_value_error. _service.disable_retries() self.test_post_bulk_get_as_mixed_value_error() class TestPostBulkGetAsRelated(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_bulk_get_as_related_all_params(self): url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = 'This is a mock binary response.' responses.add(responses.POST, url, body=mock_response, content_type='multipart/related', status=200) bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'order00067' bulk_get_query_document_model['rev'] = '3-917fa2381192822767f010b95b45325b' db = 'testString' docs = [bulk_get_query_document_model] attachments = False att_encoding_info = False latest = False revs = False response = _service.post_bulk_get_as_related( db, docs, attachments=attachments, att_encoding_info=att_encoding_info, latest=latest, revs=revs, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'revs={}'.format('true' if revs else 'false') in query_string responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['docs'] == [bulk_get_query_document_model] def test_post_bulk_get_as_related_all_params_with_retries(self): _service.enable_retries() self.test_post_bulk_get_as_related_all_params() _service.disable_retries() self.test_post_bulk_get_as_related_all_params() @responses.activate def test_post_bulk_get_as_related_required_params(self): url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = 'This is a mock binary response.' responses.add(responses.POST, url, body=mock_response, content_type='multipart/related', status=200) bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'order00067' bulk_get_query_document_model['rev'] = '3-917fa2381192822767f010b95b45325b' db = 'testString' docs = [bulk_get_query_document_model] response = _service.post_bulk_get_as_related( db, docs, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['docs'] == [bulk_get_query_document_model] def test_post_bulk_get_as_related_required_params_with_retries(self): _service.enable_retries() self.test_post_bulk_get_as_related_required_params() _service.disable_retries() self.test_post_bulk_get_as_related_required_params() @responses.activate def test_post_bulk_get_as_related_value_error(self): url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = 'This is a mock binary response.' responses.add(responses.POST, url, body=mock_response, content_type='multipart/related', status=200) bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'order00067' bulk_get_query_document_model['rev'] = '3-917fa2381192822767f010b95b45325b' db = 'testString' docs = [bulk_get_query_document_model] req_param_dict = { "db": db, "docs": docs, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_bulk_get_as_related(**req_copy) def test_post_bulk_get_as_related_value_error_with_retries(self): _service.enable_retries() self.test_post_bulk_get_as_related_value_error() _service.disable_retries() self.test_post_bulk_get_as_related_value_error() class TestPostBulkGetAsStream(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_bulk_get_as_stream_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a BulkGetQueryDocument model bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'order00067' bulk_get_query_document_model['rev'] = '3-917fa2381192822767f010b95b45325b' # Set up parameter values db = 'testString' docs = [bulk_get_query_document_model] attachments = False att_encoding_info = False latest = False revs = False # Invoke method response = _service.post_bulk_get_as_stream( db, docs, attachments=attachments, att_encoding_info=att_encoding_info, latest=latest, revs=revs, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'revs={}'.format('true' if revs else 'false') in query_string # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['docs'] == [bulk_get_query_document_model] # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_bulk_get_as_stream_all_params_with_retries(self): # Enable retries and run test_post_bulk_get_as_stream_all_params. _service.enable_retries() self.test_post_bulk_get_as_stream_all_params() # Disable retries and run test_post_bulk_get_as_stream_all_params. _service.disable_retries() self.test_post_bulk_get_as_stream_all_params() @responses.activate def test_post_bulk_get_as_stream_required_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a BulkGetQueryDocument model bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'order00067' bulk_get_query_document_model['rev'] = '3-917fa2381192822767f010b95b45325b' # Set up parameter values db = 'testString' docs = [bulk_get_query_document_model] # Invoke method response = _service.post_bulk_get_as_stream( db, docs, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['docs'] == [bulk_get_query_document_model] # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_bulk_get_as_stream_required_params_with_retries(self): # Enable retries and run test_post_bulk_get_as_stream_required_params. _service.enable_retries() self.test_post_bulk_get_as_stream_required_params() # Disable retries and run test_post_bulk_get_as_stream_required_params. _service.disable_retries() self.test_post_bulk_get_as_stream_required_params() @responses.activate def test_post_bulk_get_as_stream_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_bulk_get') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a BulkGetQueryDocument model bulk_get_query_document_model = {} bulk_get_query_document_model['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model['id'] = 'order00067' bulk_get_query_document_model['rev'] = '3-917fa2381192822767f010b95b45325b' # Set up parameter values db = 'testString' docs = [bulk_get_query_document_model] # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "docs": docs, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_bulk_get_as_stream(**req_copy) def test_post_bulk_get_as_stream_value_error_with_retries(self): # Enable retries and run test_post_bulk_get_as_stream_value_error. _service.enable_retries() self.test_post_bulk_get_as_stream_value_error() # Disable retries and run test_post_bulk_get_as_stream_value_error. _service.disable_retries() self.test_post_bulk_get_as_stream_value_error() class TestDeleteDocument(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_delete_document_all_params(self): url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) db = 'testString' doc_id = 'testString' if_match = 'testString' batch = 'ok' rev = 'testString' response = _service.delete_document( db, doc_id, if_match=if_match, batch=batch, rev=rev, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'batch={}'.format(batch) in query_string assert 'rev={}'.format(rev) in query_string def test_delete_document_all_params_with_retries(self): _service.enable_retries() self.test_delete_document_all_params() _service.disable_retries() self.test_delete_document_all_params() @responses.activate def test_delete_document_required_params(self): url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) db = 'testString' doc_id = 'testString' response = _service.delete_document( db, doc_id, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 def test_delete_document_required_params_with_retries(self): _service.enable_retries() self.test_delete_document_required_params() _service.disable_retries() self.test_delete_document_required_params() @responses.activate def test_delete_document_value_error(self): url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) db = 'testString' doc_id = 'testString' req_param_dict = { "db": db, "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_document(**req_copy) def test_delete_document_value_error_with_retries(self): _service.enable_retries() self.test_delete_document_value_error() _service.disable_retries() self.test_delete_document_value_error() class TestGetDocument(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_document_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' if_none_match = 'testString' attachments = False att_encoding_info = False conflicts = False deleted_conflicts = False latest = False local_seq = False meta = False rev = 'testString' revs = False revs_info = False # Invoke method response = _service.get_document( db, doc_id, if_none_match=if_none_match, attachments=attachments, att_encoding_info=att_encoding_info, conflicts=conflicts, deleted_conflicts=deleted_conflicts, latest=latest, local_seq=local_seq, meta=meta, rev=rev, revs=revs, revs_info=revs_info, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'conflicts={}'.format('true' if conflicts else 'false') in query_string assert 'deleted_conflicts={}'.format('true' if deleted_conflicts else 'false') in query_string assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'local_seq={}'.format('true' if local_seq else 'false') in query_string assert 'meta={}'.format('true' if meta else 'false') in query_string assert 'rev={}'.format(rev) in query_string assert 'revs={}'.format('true' if revs else 'false') in query_string assert 'revs_info={}'.format('true' if revs_info else 'false') in query_string def test_get_document_all_params_with_retries(self): # Enable retries and run test_get_document_all_params. _service.enable_retries() self.test_get_document_all_params() # Disable retries and run test_get_document_all_params. _service.disable_retries() self.test_get_document_all_params() @responses.activate def test_get_document_required_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Invoke method response = _service.get_document( db, doc_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_document_required_params_with_retries(self): # Enable retries and run test_get_document_required_params. _service.enable_retries() self.test_get_document_required_params() # Disable retries and run test_get_document_required_params. _service.disable_retries() self.test_get_document_required_params() @responses.activate def test_get_document_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_document(**req_copy) def test_get_document_value_error_with_retries(self): # Enable retries and run test_get_document_value_error. _service.enable_retries() self.test_get_document_value_error() # Disable retries and run test_get_document_value_error. _service.disable_retries() self.test_get_document_value_error() class TestGetDocumentAsMixed(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_document_as_mixed_all_params(self): url = self.preprocess_url(_base_url + '/testString/testString') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, body=mock_response, content_type='multipart/mixed', status=200) db = 'testString' doc_id = 'testString' if_none_match = 'testString' attachments = False att_encoding_info = False conflicts = False deleted_conflicts = False latest = False local_seq = False meta = False rev = 'testString' revs = False revs_info = False response = _service.get_document_as_mixed( db, doc_id, if_none_match=if_none_match, attachments=attachments, att_encoding_info=att_encoding_info, conflicts=conflicts, deleted_conflicts=deleted_conflicts, latest=latest, local_seq=local_seq, meta=meta, rev=rev, revs=revs, revs_info=revs_info, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'conflicts={}'.format('true' if conflicts else 'false') in query_string assert 'deleted_conflicts={}'.format('true' if deleted_conflicts else 'false') in query_string assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'local_seq={}'.format('true' if local_seq else 'false') in query_string assert 'meta={}'.format('true' if meta else 'false') in query_string assert 'rev={}'.format(rev) in query_string assert 'revs={}'.format('true' if revs else 'false') in query_string assert 'revs_info={}'.format('true' if revs_info else 'false') in query_string def test_get_document_as_mixed_all_params_with_retries(self): _service.enable_retries() self.test_get_document_as_mixed_all_params() _service.disable_retries() self.test_get_document_as_mixed_all_params() @responses.activate def test_get_document_as_mixed_required_params(self): url = self.preprocess_url(_base_url + '/testString/testString') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, body=mock_response, content_type='multipart/mixed', status=200) db = 'testString' doc_id = 'testString' response = _service.get_document_as_mixed( db, doc_id, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_document_as_mixed_required_params_with_retries(self): _service.enable_retries() self.test_get_document_as_mixed_required_params() _service.disable_retries() self.test_get_document_as_mixed_required_params() @responses.activate def test_get_document_as_mixed_value_error(self): url = self.preprocess_url(_base_url + '/testString/testString') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, body=mock_response, content_type='multipart/mixed', status=200) db = 'testString' doc_id = 'testString' req_param_dict = { "db": db, "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_document_as_mixed(**req_copy) def test_get_document_as_mixed_value_error_with_retries(self): _service.enable_retries() self.test_get_document_as_mixed_value_error() _service.disable_retries() self.test_get_document_as_mixed_value_error() class TestGetDocumentAsRelated(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_document_as_related_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, body=mock_response, content_type='multipart/related', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' if_none_match = 'testString' attachments = False att_encoding_info = False conflicts = False deleted_conflicts = False latest = False local_seq = False meta = False rev = 'testString' revs = False revs_info = False # Invoke method response = _service.get_document_as_related( db, doc_id, if_none_match=if_none_match, attachments=attachments, att_encoding_info=att_encoding_info, conflicts=conflicts, deleted_conflicts=deleted_conflicts, latest=latest, local_seq=local_seq, meta=meta, rev=rev, revs=revs, revs_info=revs_info, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'conflicts={}'.format('true' if conflicts else 'false') in query_string assert 'deleted_conflicts={}'.format('true' if deleted_conflicts else 'false') in query_string assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'local_seq={}'.format('true' if local_seq else 'false') in query_string assert 'meta={}'.format('true' if meta else 'false') in query_string assert 'rev={}'.format(rev) in query_string assert 'revs={}'.format('true' if revs else 'false') in query_string assert 'revs_info={}'.format('true' if revs_info else 'false') in query_string def test_get_document_as_related_all_params_with_retries(self): # Enable retries and run test_get_document_as_related_all_params. _service.enable_retries() self.test_get_document_as_related_all_params() # Disable retries and run test_get_document_as_related_all_params. _service.disable_retries() self.test_get_document_as_related_all_params() @responses.activate def test_get_document_as_related_required_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, body=mock_response, content_type='multipart/related', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Invoke method response = _service.get_document_as_related( db, doc_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_document_as_related_required_params_with_retries(self): # Enable retries and run test_get_document_as_related_required_params. _service.enable_retries() self.test_get_document_as_related_required_params() # Disable retries and run test_get_document_as_related_required_params. _service.disable_retries() self.test_get_document_as_related_required_params() @responses.activate def test_get_document_as_related_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, body=mock_response, content_type='multipart/related', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_document_as_related(**req_copy) def test_get_document_as_related_value_error_with_retries(self): # Enable retries and run test_get_document_as_related_value_error. _service.enable_retries() self.test_get_document_as_related_value_error() # Disable retries and run test_get_document_as_related_value_error. _service.disable_retries() self.test_get_document_as_related_value_error() class TestGetDocumentAsStream(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_document_as_stream_all_params(self): url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) db = 'testString' doc_id = 'testString' if_none_match = 'testString' attachments = False att_encoding_info = False conflicts = False deleted_conflicts = False latest = False local_seq = False meta = False rev = 'testString' revs = False revs_info = False response = _service.get_document_as_stream( db, doc_id, if_none_match=if_none_match, attachments=attachments, att_encoding_info=att_encoding_info, conflicts=conflicts, deleted_conflicts=deleted_conflicts, latest=latest, local_seq=local_seq, meta=meta, rev=rev, revs=revs, revs_info=revs_info, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'conflicts={}'.format('true' if conflicts else 'false') in query_string assert 'deleted_conflicts={}'.format('true' if deleted_conflicts else 'false') in query_string assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'local_seq={}'.format('true' if local_seq else 'false') in query_string assert 'meta={}'.format('true' if meta else 'false') in query_string assert 'rev={}'.format(rev) in query_string assert 'revs={}'.format('true' if revs else 'false') in query_string assert 'revs_info={}'.format('true' if revs_info else 'false') in query_string result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_get_document_as_stream_all_params_with_retries(self): _service.enable_retries() self.test_get_document_as_stream_all_params() _service.disable_retries() self.test_get_document_as_stream_all_params() @responses.activate def test_get_document_as_stream_required_params(self): url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) db = 'testString' doc_id = 'testString' response = _service.get_document_as_stream( db, doc_id, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_get_document_as_stream_required_params_with_retries(self): _service.enable_retries() self.test_get_document_as_stream_required_params() _service.disable_retries() self.test_get_document_as_stream_required_params() @responses.activate def test_get_document_as_stream_value_error(self): url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) db = 'testString' doc_id = 'testString' req_param_dict = { "db": db, "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_document_as_stream(**req_copy) def test_get_document_as_stream_value_error_with_retries(self): _service.enable_retries() self.test_get_document_as_stream_value_error() _service.disable_retries() self.test_get_document_as_stream_value_error() class TestPutDocument(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_put_document_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Document model document_model = {} document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'exampleid' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['brand'] = 'Foo' document_model['colours'] = '["red","green","black","blue"]' document_model['description'] = 'Slim Colourful Design Electronic Cooking Appliance for ...' document_model['image'] = 'assets/img/0gmsnghhew.jpg' document_model['keywords'] = '["Foo","Scales","Weight","Digital","Kitchen"]' document_model['name'] = 'Digital Kitchen Scales' document_model['price'] = '14.99' document_model['productid'] = '1000042' document_model['taxonomy'] = '["Home","Kitchen","Small Appliances"]' document_model['type'] = 'product' # Set up parameter values db = 'testString' doc_id = 'testString' document = document_model content_type = 'application/json' if_match = 'testString' batch = 'ok' new_edits = False rev = 'testString' # Invoke method response = _service.put_document( db, doc_id, document, content_type=content_type, if_match=if_match, batch=batch, new_edits=new_edits, rev=rev, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'batch={}'.format(batch) in query_string assert 'new_edits={}'.format('true' if new_edits else 'false') in query_string assert 'rev={}'.format(rev) in query_string # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params def test_put_document_all_params_with_retries(self): # Enable retries and run test_put_document_all_params. _service.enable_retries() self.test_put_document_all_params() # Disable retries and run test_put_document_all_params. _service.disable_retries() self.test_put_document_all_params() @responses.activate def test_put_document_required_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Document model document_model = {} document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'exampleid' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['brand'] = 'Foo' document_model['colours'] = '["red","green","black","blue"]' document_model['description'] = 'Slim Colourful Design Electronic Cooking Appliance for ...' document_model['image'] = 'assets/img/0gmsnghhew.jpg' document_model['keywords'] = '["Foo","Scales","Weight","Digital","Kitchen"]' document_model['name'] = 'Digital Kitchen Scales' document_model['price'] = '14.99' document_model['productid'] = '1000042' document_model['taxonomy'] = '["Home","Kitchen","Small Appliances"]' document_model['type'] = 'product' # Set up parameter values db = 'testString' doc_id = 'testString' document = document_model # Invoke method response = _service.put_document( db, doc_id, document, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params def test_put_document_required_params_with_retries(self): # Enable retries and run test_put_document_required_params. _service.enable_retries() self.test_put_document_required_params() # Disable retries and run test_put_document_required_params. _service.disable_retries() self.test_put_document_required_params() @responses.activate def test_put_document_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Document model document_model = {} document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'exampleid' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['brand'] = 'Foo' document_model['colours'] = '["red","green","black","blue"]' document_model['description'] = 'Slim Colourful Design Electronic Cooking Appliance for ...' document_model['image'] = 'assets/img/0gmsnghhew.jpg' document_model['keywords'] = '["Foo","Scales","Weight","Digital","Kitchen"]' document_model['name'] = 'Digital Kitchen Scales' document_model['price'] = '14.99' document_model['productid'] = '1000042' document_model['taxonomy'] = '["Home","Kitchen","Small Appliances"]' document_model['type'] = 'product' # Set up parameter values db = 'testString' doc_id = 'testString' document = document_model # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "doc_id": doc_id, "document": document, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.put_document(**req_copy) def test_put_document_value_error_with_retries(self): # Enable retries and run test_put_document_value_error. _service.enable_retries() self.test_put_document_value_error() # Disable retries and run test_put_document_value_error. _service.disable_retries() self.test_put_document_value_error() # endregion ############################################################################## # End of Service: Documents ############################################################################## ############################################################################## # Start of Service: DesignDocuments ############################################################################## # region class TestNewInstance(): def test_new_instance(self): os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestHeadDesignDocument(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_head_design_document_all_params(self): url = self.preprocess_url(_base_url + '/testString/_design/testString') responses.add(responses.HEAD, url, status=200) db = 'testString' ddoc = 'testString' if_none_match = 'testString' response = _service.head_design_document( db, ddoc, if_none_match=if_none_match, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 def test_head_design_document_all_params_with_retries(self): _service.enable_retries() self.test_head_design_document_all_params() _service.disable_retries() self.test_head_design_document_all_params() @responses.activate def test_head_design_document_required_params(self): url = self.preprocess_url(_base_url + '/testString/_design/testString') responses.add(responses.HEAD, url, status=200) db = 'testString' ddoc = 'testString' response = _service.head_design_document( db, ddoc, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 def test_head_design_document_required_params_with_retries(self): _service.enable_retries() self.test_head_design_document_required_params() _service.disable_retries() self.test_head_design_document_required_params() @responses.activate def test_head_design_document_value_error(self): url = self.preprocess_url(_base_url + '/testString/_design/testString') responses.add(responses.HEAD, url, status=200) db = 'testString' ddoc = 'testString' req_param_dict = { "db": db, "ddoc": ddoc, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.head_design_document(**req_copy) def test_head_design_document_value_error_with_retries(self): _service.enable_retries() self.test_head_design_document_value_error() _service.disable_retries() self.test_head_design_document_value_error() class TestDeleteDesignDocument(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_delete_design_document_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' if_match = 'testString' batch = 'ok' rev = 'testString' # Invoke method response = _service.delete_design_document( db, ddoc, if_match=if_match, batch=batch, rev=rev, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'batch={}'.format(batch) in query_string assert 'rev={}'.format(rev) in query_string def test_delete_design_document_all_params_with_retries(self): # Enable retries and run test_delete_design_document_all_params. _service.enable_retries() self.test_delete_design_document_all_params() # Disable retries and run test_delete_design_document_all_params. _service.disable_retries() self.test_delete_design_document_all_params() @responses.activate def test_delete_design_document_required_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' # Invoke method response = _service.delete_design_document( db, ddoc, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_delete_design_document_required_params_with_retries(self): # Enable retries and run test_delete_design_document_required_params. _service.enable_retries() self.test_delete_design_document_required_params() # Disable retries and run test_delete_design_document_required_params. _service.disable_retries() self.test_delete_design_document_required_params() @responses.activate def test_delete_design_document_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_design_document(**req_copy) def test_delete_design_document_value_error_with_retries(self): # Enable retries and run test_delete_design_document_value_error. _service.enable_retries() self.test_delete_design_document_value_error() # Disable retries and run test_delete_design_document_value_error. _service.disable_retries() self.test_delete_design_document_value_error() class TestGetDesignDocument(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_design_document_all_params(self): url = self.preprocess_url(_base_url + '/testString/_design/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}], "autoupdate": true, "filters": {"mapKey": "inner"}, "indexes": {"mapKey": {"analyzer": {"name": "classic", "stopwords": ["stopwords"], "fields": {"mapKey": {"name": "classic", "stopwords": ["stopwords"]}}}, "index": "index"}}, "language": "javascript", "options": {"partitioned": false}, "validate_doc_update": "validate_doc_update", "views": {"mapKey": {"map": "map", "reduce": "reduce"}}, "st_indexes": {"mapKey": {"index": "index"}}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) db = 'testString' ddoc = 'testString' if_none_match = 'testString' attachments = False att_encoding_info = False conflicts = False deleted_conflicts = False latest = False local_seq = False meta = False rev = 'testString' revs = False revs_info = False response = _service.get_design_document( db, ddoc, if_none_match=if_none_match, attachments=attachments, att_encoding_info=att_encoding_info, conflicts=conflicts, deleted_conflicts=deleted_conflicts, latest=latest, local_seq=local_seq, meta=meta, rev=rev, revs=revs, revs_info=revs_info, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'conflicts={}'.format('true' if conflicts else 'false') in query_string assert 'deleted_conflicts={}'.format('true' if deleted_conflicts else 'false') in query_string assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'local_seq={}'.format('true' if local_seq else 'false') in query_string assert 'meta={}'.format('true' if meta else 'false') in query_string assert 'rev={}'.format(rev) in query_string assert 'revs={}'.format('true' if revs else 'false') in query_string assert 'revs_info={}'.format('true' if revs_info else 'false') in query_string def test_get_design_document_all_params_with_retries(self): _service.enable_retries() self.test_get_design_document_all_params() _service.disable_retries() self.test_get_design_document_all_params() @responses.activate def test_get_design_document_required_params(self): url = self.preprocess_url(_base_url + '/testString/_design/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}], "autoupdate": true, "filters": {"mapKey": "inner"}, "indexes": {"mapKey": {"analyzer": {"name": "classic", "stopwords": ["stopwords"], "fields": {"mapKey": {"name": "classic", "stopwords": ["stopwords"]}}}, "index": "index"}}, "language": "javascript", "options": {"partitioned": false}, "validate_doc_update": "validate_doc_update", "views": {"mapKey": {"map": "map", "reduce": "reduce"}}, "st_indexes": {"mapKey": {"index": "index"}}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) db = 'testString' ddoc = 'testString' response = _service.get_design_document( db, ddoc, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_design_document_required_params_with_retries(self): _service.enable_retries() self.test_get_design_document_required_params() _service.disable_retries() self.test_get_design_document_required_params() @responses.activate def test_get_design_document_value_error(self): url = self.preprocess_url(_base_url + '/testString/_design/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}], "autoupdate": true, "filters": {"mapKey": "inner"}, "indexes": {"mapKey": {"analyzer": {"name": "classic", "stopwords": ["stopwords"], "fields": {"mapKey": {"name": "classic", "stopwords": ["stopwords"]}}}, "index": "index"}}, "language": "javascript", "options": {"partitioned": false}, "validate_doc_update": "validate_doc_update", "views": {"mapKey": {"map": "map", "reduce": "reduce"}}, "st_indexes": {"mapKey": {"index": "index"}}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) db = 'testString' ddoc = 'testString' req_param_dict = { "db": db, "ddoc": ddoc, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_design_document(**req_copy) def test_get_design_document_value_error_with_retries(self): _service.enable_retries() self.test_get_design_document_value_error() _service.disable_retries() self.test_get_design_document_value_error() class TestPutDesignDocument(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_put_design_document_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Analyzer model analyzer_model = {} analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] # Construct a dict representation of a AnalyzerConfiguration model analyzer_configuration_model = {} analyzer_configuration_model['name'] = 'classic' analyzer_configuration_model['stopwords'] = ['testString'] analyzer_configuration_model['fields'] = {} # Construct a dict representation of a SearchIndexDefinition model search_index_definition_model = {} search_index_definition_model['analyzer'] = analyzer_configuration_model search_index_definition_model['index'] = 'testString' # Construct a dict representation of a DesignDocumentOptions model design_document_options_model = {} design_document_options_model['partitioned'] = True # Construct a dict representation of a DesignDocumentViewsMapReduce model design_document_views_map_reduce_model = {} design_document_views_map_reduce_model['map'] = 'testString' design_document_views_map_reduce_model['reduce'] = 'testString' # Construct a dict representation of a GeoIndexDefinition model geo_index_definition_model = {} geo_index_definition_model['index'] = 'testString' # Construct a dict representation of a DesignDocument model design_document_model = {} design_document_model['_attachments'] = {} design_document_model['_conflicts'] = ['testString'] design_document_model['_deleted'] = True design_document_model['_deleted_conflicts'] = ['testString'] design_document_model['_id'] = 'testString' design_document_model['_local_seq'] = 'testString' design_document_model['_rev'] = 'testString' design_document_model['_revisions'] = revisions_model design_document_model['_revs_info'] = [document_revision_status_model] design_document_model['autoupdate'] = True design_document_model['filters'] = {} design_document_model['indexes'] = {} design_document_model['language'] = 'javascript' design_document_model['options'] = design_document_options_model design_document_model['validate_doc_update'] = 'testString' design_document_model['views'] = {} design_document_model['st_indexes'] = {} design_document_model['foo'] = 'testString' # Set up parameter values db = 'testString' ddoc = 'testString' design_document = design_document_model if_match = 'testString' batch = 'ok' new_edits = False rev = 'testString' # Invoke method response = _service.put_design_document( db, ddoc, design_document, if_match=if_match, batch=batch, new_edits=new_edits, rev=rev, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'batch={}'.format(batch) in query_string assert 'new_edits={}'.format('true' if new_edits else 'false') in query_string assert 'rev={}'.format(rev) in query_string # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body == design_document def test_put_design_document_all_params_with_retries(self): # Enable retries and run test_put_design_document_all_params. _service.enable_retries() self.test_put_design_document_all_params() # Disable retries and run test_put_design_document_all_params. _service.disable_retries() self.test_put_design_document_all_params() @responses.activate def test_put_design_document_required_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Analyzer model analyzer_model = {} analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] # Construct a dict representation of a AnalyzerConfiguration model analyzer_configuration_model = {} analyzer_configuration_model['name'] = 'classic' analyzer_configuration_model['stopwords'] = ['testString'] analyzer_configuration_model['fields'] = {} # Construct a dict representation of a SearchIndexDefinition model search_index_definition_model = {} search_index_definition_model['analyzer'] = analyzer_configuration_model search_index_definition_model['index'] = 'testString' # Construct a dict representation of a DesignDocumentOptions model design_document_options_model = {} design_document_options_model['partitioned'] = True # Construct a dict representation of a DesignDocumentViewsMapReduce model design_document_views_map_reduce_model = {} design_document_views_map_reduce_model['map'] = 'testString' design_document_views_map_reduce_model['reduce'] = 'testString' # Construct a dict representation of a GeoIndexDefinition model geo_index_definition_model = {} geo_index_definition_model['index'] = 'testString' # Construct a dict representation of a DesignDocument model design_document_model = {} design_document_model['_attachments'] = {} design_document_model['_conflicts'] = ['testString'] design_document_model['_deleted'] = True design_document_model['_deleted_conflicts'] = ['testString'] design_document_model['_id'] = 'testString' design_document_model['_local_seq'] = 'testString' design_document_model['_rev'] = 'testString' design_document_model['_revisions'] = revisions_model design_document_model['_revs_info'] = [document_revision_status_model] design_document_model['autoupdate'] = True design_document_model['filters'] = {} design_document_model['indexes'] = {} design_document_model['language'] = 'javascript' design_document_model['options'] = design_document_options_model design_document_model['validate_doc_update'] = 'testString' design_document_model['views'] = {} design_document_model['st_indexes'] = {} design_document_model['foo'] = 'testString' # Set up parameter values db = 'testString' ddoc = 'testString' design_document = design_document_model # Invoke method response = _service.put_design_document( db, ddoc, design_document, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body == design_document def test_put_design_document_required_params_with_retries(self): # Enable retries and run test_put_design_document_required_params. _service.enable_retries() self.test_put_design_document_required_params() # Disable retries and run test_put_design_document_required_params. _service.disable_retries() self.test_put_design_document_required_params() @responses.activate def test_put_design_document_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a Analyzer model analyzer_model = {} analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] # Construct a dict representation of a AnalyzerConfiguration model analyzer_configuration_model = {} analyzer_configuration_model['name'] = 'classic' analyzer_configuration_model['stopwords'] = ['testString'] analyzer_configuration_model['fields'] = {} # Construct a dict representation of a SearchIndexDefinition model search_index_definition_model = {} search_index_definition_model['analyzer'] = analyzer_configuration_model search_index_definition_model['index'] = 'testString' # Construct a dict representation of a DesignDocumentOptions model design_document_options_model = {} design_document_options_model['partitioned'] = True # Construct a dict representation of a DesignDocumentViewsMapReduce model design_document_views_map_reduce_model = {} design_document_views_map_reduce_model['map'] = 'testString' design_document_views_map_reduce_model['reduce'] = 'testString' # Construct a dict representation of a GeoIndexDefinition model geo_index_definition_model = {} geo_index_definition_model['index'] = 'testString' # Construct a dict representation of a DesignDocument model design_document_model = {} design_document_model['_attachments'] = {} design_document_model['_conflicts'] = ['testString'] design_document_model['_deleted'] = True design_document_model['_deleted_conflicts'] = ['testString'] design_document_model['_id'] = 'testString' design_document_model['_local_seq'] = 'testString' design_document_model['_rev'] = 'testString' design_document_model['_revisions'] = revisions_model design_document_model['_revs_info'] = [document_revision_status_model] design_document_model['autoupdate'] = True design_document_model['filters'] = {} design_document_model['indexes'] = {} design_document_model['language'] = 'javascript' design_document_model['options'] = design_document_options_model design_document_model['validate_doc_update'] = 'testString' design_document_model['views'] = {} design_document_model['st_indexes'] = {} design_document_model['foo'] = 'testString' # Set up parameter values db = 'testString' ddoc = 'testString' design_document = design_document_model # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, "design_document": design_document, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.put_design_document(**req_copy) def test_put_design_document_value_error_with_retries(self): # Enable retries and run test_put_design_document_value_error. _service.enable_retries() self.test_put_design_document_value_error() # Disable retries and run test_put_design_document_value_error. _service.disable_retries() self.test_put_design_document_value_error() class TestGetDesignDocumentInformation(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_design_document_information_all_params(self): url = self.preprocess_url(_base_url + '/testString/_design/testString/_info') mock_response = '{"name": "name", "view_index": {"compact_running": false, "language": "language", "signature": "signature", "sizes": {"active": 6, "external": 8, "file": 4}, "updater_running": false, "waiting_clients": 0, "waiting_commit": true}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) db = 'testString' ddoc = 'testString' response = _service.get_design_document_information( db, ddoc, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_design_document_information_all_params_with_retries(self): _service.enable_retries() self.test_get_design_document_information_all_params() _service.disable_retries() self.test_get_design_document_information_all_params() @responses.activate def test_get_design_document_information_value_error(self): url = self.preprocess_url(_base_url + '/testString/_design/testString/_info') mock_response = '{"name": "name", "view_index": {"compact_running": false, "language": "language", "signature": "signature", "sizes": {"active": 6, "external": 8, "file": 4}, "updater_running": false, "waiting_clients": 0, "waiting_commit": true}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) db = 'testString' ddoc = 'testString' req_param_dict = { "db": db, "ddoc": ddoc, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_design_document_information(**req_copy) def test_get_design_document_information_value_error_with_retries(self): _service.enable_retries() self.test_get_design_document_information_value_error() _service.disable_retries() self.test_get_design_document_information_value_error() class TestPostDesignDocs(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_design_docs_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_design_docs') mock_response = '{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' key = 'testString' keys = ['testString'] startkey = '0007741142412418284' accept = 'application/json' # Invoke method response = _service.post_design_docs( db, att_encoding_info=att_encoding_info, attachments=attachments, conflicts=conflicts, descending=descending, include_docs=include_docs, inclusive_end=inclusive_end, limit=limit, skip=skip, update_seq=update_seq, endkey=endkey, key=key, keys=keys, startkey=startkey, accept=accept, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['att_encoding_info'] == False assert req_body['attachments'] == False assert req_body['conflicts'] == False assert req_body['descending'] == False assert req_body['include_docs'] == False assert req_body['inclusive_end'] == True assert req_body['limit'] == 10 assert req_body['skip'] == 0 assert req_body['update_seq'] == False assert req_body['endkey'] == 'testString' assert req_body['key'] == 'testString' assert req_body['keys'] == ['testString'] assert req_body['startkey'] == '0007741142412418284' def test_post_design_docs_all_params_with_retries(self): # Enable retries and run test_post_design_docs_all_params. _service.enable_retries() self.test_post_design_docs_all_params() # Disable retries and run test_post_design_docs_all_params. _service.disable_retries() self.test_post_design_docs_all_params() @responses.activate def test_post_design_docs_required_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_design_docs') mock_response = '{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' key = 'testString' keys = ['testString'] startkey = '0007741142412418284' # Invoke method response = _service.post_design_docs( db, att_encoding_info=att_encoding_info, attachments=attachments, conflicts=conflicts, descending=descending, include_docs=include_docs, inclusive_end=inclusive_end, limit=limit, skip=skip, update_seq=update_seq, endkey=endkey, key=key, keys=keys, startkey=startkey, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['att_encoding_info'] == False assert req_body['attachments'] == False assert req_body['conflicts'] == False assert req_body['descending'] == False assert req_body['include_docs'] == False assert req_body['inclusive_end'] == True assert req_body['limit'] == 10 assert req_body['skip'] == 0 assert req_body['update_seq'] == False assert req_body['endkey'] == 'testString' assert req_body['key'] == 'testString' assert req_body['keys'] == ['testString'] assert req_body['startkey'] == '0007741142412418284' def test_post_design_docs_required_params_with_retries(self): # Enable retries and run test_post_design_docs_required_params. _service.enable_retries() self.test_post_design_docs_required_params() # Disable retries and run test_post_design_docs_required_params. _service.disable_retries() self.test_post_design_docs_required_params() @responses.activate def test_post_design_docs_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_design_docs') mock_response = '{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' key = 'testString' keys = ['testString'] startkey = '0007741142412418284' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_design_docs(**req_copy) def test_post_design_docs_value_error_with_retries(self): # Enable retries and run test_post_design_docs_value_error. _service.enable_retries() self.test_post_design_docs_value_error() # Disable retries and run test_post_design_docs_value_error. _service.disable_retries() self.test_post_design_docs_value_error() class TestPostDesignDocsQueries(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_design_docs_queries_all_params(self): url = self.preprocess_url(_base_url + '/testString/_design_docs/queries') mock_response = '{"results": [{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) all_docs_query_model = {} all_docs_query_model['att_encoding_info'] = False all_docs_query_model['attachments'] = False all_docs_query_model['conflicts'] = False all_docs_query_model['descending'] = False all_docs_query_model['include_docs'] = False all_docs_query_model['inclusive_end'] = True all_docs_query_model['limit'] = 0 all_docs_query_model['skip'] = 0 all_docs_query_model['update_seq'] = False all_docs_query_model['endkey'] = 'testString' all_docs_query_model['key'] = 'testString' all_docs_query_model['keys'] = ['small-appliances:1000042', 'small-appliances:1000043'] all_docs_query_model['startkey'] = 'testString' db = 'testString' queries = [all_docs_query_model] accept = 'application/json' response = _service.post_design_docs_queries( db, queries, accept=accept, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['queries'] == [all_docs_query_model] def test_post_design_docs_queries_all_params_with_retries(self): _service.enable_retries() self.test_post_design_docs_queries_all_params() _service.disable_retries() self.test_post_design_docs_queries_all_params() @responses.activate def test_post_design_docs_queries_required_params(self): url = self.preprocess_url(_base_url + '/testString/_design_docs/queries') mock_response = '{"results": [{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) all_docs_query_model = {} all_docs_query_model['att_encoding_info'] = False all_docs_query_model['attachments'] = False all_docs_query_model['conflicts'] = False all_docs_query_model['descending'] = False all_docs_query_model['include_docs'] = False all_docs_query_model['inclusive_end'] = True all_docs_query_model['limit'] = 0 all_docs_query_model['skip'] = 0 all_docs_query_model['update_seq'] = False all_docs_query_model['endkey'] = 'testString' all_docs_query_model['key'] = 'testString' all_docs_query_model['keys'] = ['small-appliances:1000042', 'small-appliances:1000043'] all_docs_query_model['startkey'] = 'testString' db = 'testString' queries = [all_docs_query_model] response = _service.post_design_docs_queries( db, queries, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['queries'] == [all_docs_query_model] def test_post_design_docs_queries_required_params_with_retries(self): _service.enable_retries() self.test_post_design_docs_queries_required_params() _service.disable_retries() self.test_post_design_docs_queries_required_params() @responses.activate def test_post_design_docs_queries_value_error(self): url = self.preprocess_url(_base_url + '/testString/_design_docs/queries') mock_response = '{"results": [{"total_rows": 0, "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "key", "value": {"rev": "rev"}}], "update_seq": "update_seq"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) all_docs_query_model = {} all_docs_query_model['att_encoding_info'] = False all_docs_query_model['attachments'] = False all_docs_query_model['conflicts'] = False all_docs_query_model['descending'] = False all_docs_query_model['include_docs'] = False all_docs_query_model['inclusive_end'] = True all_docs_query_model['limit'] = 0 all_docs_query_model['skip'] = 0 all_docs_query_model['update_seq'] = False all_docs_query_model['endkey'] = 'testString' all_docs_query_model['key'] = 'testString' all_docs_query_model['keys'] = ['small-appliances:1000042', 'small-appliances:1000043'] all_docs_query_model['startkey'] = 'testString' db = 'testString' queries = [all_docs_query_model] req_param_dict = { "db": db, "queries": queries, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_design_docs_queries(**req_copy) def test_post_design_docs_queries_value_error_with_retries(self): _service.enable_retries() self.test_post_design_docs_queries_value_error() _service.disable_retries() self.test_post_design_docs_queries_value_error() ddoc = 'testString' view = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = True inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' endkey_docid = 'testString' group = False group_level = 1 key = 'testString' keys = ['examplekey'] reduce = True stable = False startkey = 'testString' startkey_docid = 'testString' update = 'true' req_param_dict = { "db": db, "ddoc": ddoc, "view": view, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_view_as_stream(**req_copy) def test_post_view_as_stream_value_error_with_retries(self): _service.enable_retries() self.test_post_view_as_stream_value_error() _service.disable_retries() self.test_post_view_as_stream_value_error() class TestPostViewQueries(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_view_queries_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_view/testString/queries') mock_response = '{"results": [{"total_rows": 0, "update_seq": "update_seq", "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "anyValue", "value": "anyValue"}]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a ViewQuery model view_query_model = {} view_query_model['att_encoding_info'] = False view_query_model['attachments'] = False view_query_model['conflicts'] = False view_query_model['descending'] = False view_query_model['include_docs'] = False view_query_model['inclusive_end'] = True view_query_model['limit'] = 0 view_query_model['skip'] = 0 view_query_model['update_seq'] = False view_query_model['endkey'] = 'testString' view_query_model['endkey_docid'] = 'testString' view_query_model['group'] = False view_query_model['group_level'] = 1 view_query_model['key'] = 'testString' view_query_model['keys'] = ['testString'] view_query_model['reduce'] = True view_query_model['stable'] = False view_query_model['startkey'] = 'testString' view_query_model['startkey_docid'] = 'testString' view_query_model['update'] = 'true' # Set up parameter values db = 'testString' ddoc = 'testString' view = 'testString' queries = [view_query_model] # Invoke method response = _service.post_view_queries( db, ddoc, view, queries, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['queries'] == [view_query_model] def test_post_view_queries_all_params_with_retries(self): # Enable retries and run test_post_view_queries_all_params. _service.enable_retries() self.test_post_view_queries_all_params() # Disable retries and run test_post_view_queries_all_params. _service.disable_retries() self.test_post_view_queries_all_params() @responses.activate def test_post_view_queries_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_view/testString/queries') mock_response = '{"results": [{"total_rows": 0, "update_seq": "update_seq", "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "anyValue", "value": "anyValue"}]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Construct a dict representation of a ViewQuery model view_query_model = {} view_query_model['att_encoding_info'] = False view_query_model['attachments'] = False view_query_model['conflicts'] = False view_query_model['descending'] = False view_query_model['include_docs'] = False view_query_model['inclusive_end'] = True view_query_model['limit'] = 0 view_query_model['skip'] = 0 view_query_model['update_seq'] = False view_query_model['endkey'] = 'testString' view_query_model['endkey_docid'] = 'testString' view_query_model['group'] = False view_query_model['group_level'] = 1 view_query_model['key'] = 'testString' view_query_model['keys'] = ['testString'] view_query_model['reduce'] = True view_query_model['stable'] = False view_query_model['startkey'] = 'testString' view_query_model['startkey_docid'] = 'testString' view_query_model['update'] = 'true' # Set up parameter values db = 'testString' ddoc = 'testString' view = 'testString' queries = [view_query_model] # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, "view": view, "queries": queries, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_view_queries(**req_copy) def test_post_view_queries_value_error_with_retries(self): # Enable retries and run test_post_view_queries_value_error. _service.enable_retries() self.test_post_view_queries_value_error() # Disable retries and run test_post_view_queries_value_error. _service.disable_retries() self.test_post_view_queries_value_error() class TestPostViewQueriesAsStream(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_view_queries_as_stream_all_params(self): url = self.preprocess_url(_base_url + '/testString/_design/testString/_view/testString/queries') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) view_query_model = {} view_query_model['att_encoding_info'] = False view_query_model['attachments'] = False view_query_model['conflicts'] = False view_query_model['descending'] = False view_query_model['include_docs'] = True view_query_model['inclusive_end'] = True view_query_model['limit'] = 5 view_query_model['skip'] = 0 view_query_model['update_seq'] = False view_query_model['endkey'] = 'testString' view_query_model['endkey_docid'] = 'testString' view_query_model['group'] = False view_query_model['group_level'] = 1 view_query_model['key'] = 'testString' view_query_model['keys'] = ['testString'] view_query_model['reduce'] = True view_query_model['stable'] = False view_query_model['startkey'] = 'testString' view_query_model['startkey_docid'] = 'testString' view_query_model['update'] = 'true' db = 'testString' ddoc = 'testString' view = 'testString' queries = [view_query_model] response = _service.post_view_queries_as_stream( db, ddoc, view, queries, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['queries'] == [view_query_model] result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_view_queries_as_stream_all_params_with_retries(self): _service.enable_retries() self.test_post_view_queries_as_stream_all_params() _service.disable_retries() self.test_post_view_queries_as_stream_all_params() @responses.activate def test_post_view_queries_as_stream_value_error(self): url = self.preprocess_url(_base_url + '/testString/_design/testString/_view/testString/queries') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) view_query_model = {} view_query_model['att_encoding_info'] = False view_query_model['attachments'] = False view_query_model['conflicts'] = False view_query_model['descending'] = False view_query_model['include_docs'] = True view_query_model['inclusive_end'] = True view_query_model['limit'] = 5 view_query_model['skip'] = 0 view_query_model['update_seq'] = False view_query_model['endkey'] = 'testString' view_query_model['endkey_docid'] = 'testString' view_query_model['group'] = False view_query_model['group_level'] = 1 view_query_model['key'] = 'testString' view_query_model['keys'] = ['testString'] view_query_model['reduce'] = True view_query_model['stable'] = False view_query_model['startkey'] = 'testString' view_query_model['startkey_docid'] = 'testString' view_query_model['update'] = 'true' db = 'testString' ddoc = 'testString' view = 'testString' queries = [view_query_model] req_param_dict = { "db": db, "ddoc": ddoc, "view": view, "queries": queries, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_view_queries_as_stream(**req_copy) def test_post_view_queries_as_stream_value_error_with_retries(self): _service.enable_retries() self.test_post_view_queries_as_stream_value_error() _service.disable_retries() self.test_post_view_queries_as_stream_value_error() req_body['conflicts'] == False assert req_body['descending'] == False assert req_body['include_docs'] == False assert req_body['inclusive_end'] == True assert req_body['limit'] == 10 assert req_body['skip'] == 0 assert req_body['update_seq'] == False assert req_body['endkey'] == 'testString' assert req_body['key'] == 'testString' assert req_body['keys'] == ['testString'] assert req_body['startkey'] == '0007741142412418284' # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_partition_all_docs_as_stream_all_params_with_retries(self): # Enable retries and run test_post_partition_all_docs_as_stream_all_params. _service.enable_retries() self.test_post_partition_all_docs_as_stream_all_params() # Disable retries and run test_post_partition_all_docs_as_stream_all_params. _service.disable_retries() self.test_post_partition_all_docs_as_stream_all_params() @responses.activate def test_post_partition_all_docs_as_stream_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_all_docs') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = False inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' key = 'testString' keys = ['testString'] startkey = '0007741142412418284' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "partition_key": partition_key, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_partition_all_docs_as_stream(**req_copy) def test_post_partition_all_docs_as_stream_value_error_with_retries(self): # Enable retries and run test_post_partition_all_docs_as_stream_value_error. _service.enable_retries() self.test_post_partition_all_docs_as_stream_value_error() # Disable retries and run test_post_partition_all_docs_as_stream_value_error. _service.disable_retries() self.test_post_partition_all_docs_as_stream_value_error() class TestPostPartitionSearch(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_partition_search_all_params(self): url = self.preprocess_url(_base_url + '/testString/_partition/testString/_design/testString/_search/testString') mock_response = '{"total_rows": 0, "bookmark": "bookmark", "by": "by", "counts": {"mapKey": {"mapKey": 0}}, "ranges": {"mapKey": {"mapKey": 0}}, "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "fields": {"mapKey": "anyValue"}, "highlights": {"mapKey": ["inner"]}, "id": "id"}], "groups": [{"total_rows": 0, "bookmark": "bookmark", "by": "by", "counts": {"mapKey": {"mapKey": 0}}, "ranges": {"mapKey": {"mapKey": 0}}, "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "fields": {"mapKey": "anyValue"}, "highlights": {"mapKey": ["inner"]}, "id": "id"}]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) db = 'testString' partition_key = 'testString' ddoc = 'testString' index = 'testString' query = 'testString' bookmark = 'testString' highlight_fields = ['testString'] highlight_number = 1 highlight_post_tag = '</em>' highlight_pre_tag = '<em>' highlight_size = 1 include_docs = False include_fields = ['testString'] limit = 0 sort = ['testString'] stale = 'ok' response = _service.post_partition_search( db, partition_key, ddoc, index, query, bookmark=bookmark, highlight_fields=highlight_fields, highlight_number=highlight_number, highlight_post_tag=highlight_post_tag, highlight_pre_tag=highlight_pre_tag, highlight_size=highlight_size, include_docs=include_docs, include_fields=include_fields, limit=limit, sort=sort, stale=stale, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['query'] == 'testString' assert req_body['bookmark'] == 'testString' assert req_body['highlight_fields'] == ['testString'] assert req_body['highlight_number'] == 1 assert req_body['highlight_post_tag'] == '</em>' assert req_body['highlight_pre_tag'] == '<em>' assert req_body['highlight_size'] == 1 assert req_body['include_docs'] == False assert req_body['include_fields'] == ['testString'] assert req_body['limit'] == 0 assert req_body['sort'] == ['testString'] assert req_body['stale'] == 'ok' def test_post_partition_search_all_params_with_retries(self): _service.enable_retries() self.test_post_partition_search_all_params() _service.disable_retries() self.test_post_partition_search_all_params() @responses.activate def test_post_partition_search_value_error(self): url = self.preprocess_url(_base_url + '/testString/_partition/testString/_design/testString/_search/testString') mock_response = '{"total_rows": 0, "bookmark": "bookmark", "by": "by", "counts": {"mapKey": {"mapKey": 0}}, "ranges": {"mapKey": {"mapKey": 0}}, "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "fields": {"mapKey": "anyValue"}, "highlights": {"mapKey": ["inner"]}, "id": "id"}], "groups": [{"total_rows": 0, "bookmark": "bookmark", "by": "by", "counts": {"mapKey": {"mapKey": 0}}, "ranges": {"mapKey": {"mapKey": 0}}, "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "fields": {"mapKey": "anyValue"}, "highlights": {"mapKey": ["inner"]}, "id": "id"}]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) db = 'testString' partition_key = 'testString' ddoc = 'testString' index = 'testString' query = 'testString' bookmark = 'testString' highlight_fields = ['testString'] highlight_number = 1 highlight_post_tag = '</em>' highlight_pre_tag = '<em>' highlight_size = 1 include_docs = False include_fields = ['testString'] limit = 0 sort = ['testString'] stale = 'ok' req_param_dict = { "db": db, "partition_key": partition_key, "ddoc": ddoc, "index": index, "query": query, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_partition_search(**req_copy) def test_post_partition_search_value_error_with_retries(self): _service.enable_retries() self.test_post_partition_search_value_error() _service.disable_retries() self.test_post_partition_search_value_error() class TestPostPartitionSearchAsStream(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_partition_search_as_stream_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_design/testString/_search/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' ddoc = 'testString' index = 'testString' query = 'testString' bookmark = 'testString' highlight_fields = ['testString'] highlight_number = 1 highlight_post_tag = '</em>' highlight_pre_tag = '<em>' highlight_size = 1 include_docs = False include_fields = ['testString'] limit = 3 sort = ['testString'] stale = 'ok' # Invoke method response = _service.post_partition_search_as_stream( db, partition_key, ddoc, index, query, bookmark=bookmark, highlight_fields=highlight_fields, highlight_number=highlight_number, highlight_post_tag=highlight_post_tag, highlight_pre_tag=highlight_pre_tag, highlight_size=highlight_size, include_docs=include_docs, include_fields=include_fields, limit=limit, sort=sort, stale=stale, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['query'] == 'testString' assert req_body['bookmark'] == 'testString' assert req_body['highlight_fields'] == ['testString'] assert req_body['highlight_number'] == 1 assert req_body['highlight_post_tag'] == '</em>' assert req_body['highlight_pre_tag'] == '<em>' assert req_body['highlight_size'] == 1 assert req_body['include_docs'] == False assert req_body['include_fields'] == ['testString'] assert req_body['limit'] == 3 assert req_body['sort'] == ['testString'] assert req_body['stale'] == 'ok' # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_partition_search_as_stream_all_params_with_retries(self): # Enable retries and run test_post_partition_search_as_stream_all_params. _service.enable_retries() self.test_post_partition_search_as_stream_all_params() # Disable retries and run test_post_partition_search_as_stream_all_params. _service.disable_retries() self.test_post_partition_search_as_stream_all_params() @responses.activate def test_post_partition_search_as_stream_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_design/testString/_search/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' ddoc = 'testString' index = 'testString' query = 'testString' bookmark = 'testString' highlight_fields = ['testString'] highlight_number = 1 highlight_post_tag = '</em>' highlight_pre_tag = '<em>' highlight_size = 1 include_docs = False include_fields = ['testString'] limit = 3 sort = ['testString'] stale = 'ok' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "partition_key": partition_key, "ddoc": ddoc, "index": index, "query": query, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_partition_search_as_stream(**req_copy) def test_post_partition_search_as_stream_value_error_with_retries(self): # Enable retries and run test_post_partition_search_as_stream_value_error. _service.enable_retries() self.test_post_partition_search_as_stream_value_error() # Disable retries and run test_post_partition_search_as_stream_value_error. _service.disable_retries() self.test_post_partition_search_as_stream_value_error() class TestPostPartitionView(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_partition_view_all_params(self): url = self.preprocess_url(_base_url + '/testString/_partition/testString/_design/testString/_view/testString') mock_response = '{"total_rows": 0, "update_seq": "update_seq", "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "anyValue", "value": "anyValue"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) db = 'testString' partition_key = 'testString' ddoc = 'testString' view = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = True inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' endkey_docid = 'testString' group = False group_level = 1 key = 'testString' keys = ['examplekey'] reduce = True stable = False startkey = 'testString' startkey_docid = 'testString' update = 'true' response = _service.post_partition_view( db, partition_key, ddoc, view, att_encoding_info=att_encoding_info, attachments=attachments, conflicts=conflicts, descending=descending, include_docs=include_docs, inclusive_end=inclusive_end, limit=limit, skip=skip, update_seq=update_seq, endkey=endkey, endkey_docid=endkey_docid, group=group, group_level=group_level, key=key, keys=keys, reduce=reduce, stable=stable, startkey=startkey, startkey_docid=startkey_docid, update=update, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['att_encoding_info'] == False assert req_body['attachments'] == False assert req_body['conflicts'] == False assert req_body['descending'] == False assert req_body['include_docs'] == True assert req_body['inclusive_end'] == True assert req_body['limit'] == 10 assert req_body['skip'] == 0 assert req_body['update_seq'] == False assert req_body['endkey'] == 'testString' assert req_body['endkey_docid'] == 'testString' assert req_body['group'] == False assert req_body['group_level'] == 1 assert req_body['key'] == 'testString' assert req_body['keys'] == ['examplekey'] assert req_body['reduce'] == True assert req_body['stable'] == False assert req_body['startkey'] == 'testString' assert req_body['startkey_docid'] == 'testString' assert req_body['update'] == 'true' def test_post_partition_view_all_params_with_retries(self): _service.enable_retries() self.test_post_partition_view_all_params() _service.disable_retries() self.test_post_partition_view_all_params() @responses.activate def test_post_partition_view_value_error(self): url = self.preprocess_url(_base_url + '/testString/_partition/testString/_design/testString/_view/testString') mock_response = '{"total_rows": 0, "update_seq": "update_seq", "rows": [{"caused_by": "caused_by", "error": "error", "reason": "reason", "doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "id": "id", "key": "anyValue", "value": "anyValue"}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) db = 'testString' partition_key = 'testString' ddoc = 'testString' view = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = True inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' endkey_docid = 'testString' group = False group_level = 1 key = 'testString' keys = ['examplekey'] reduce = True stable = False startkey = 'testString' startkey_docid = 'testString' update = 'true' req_param_dict = { "db": db, "partition_key": partition_key, "ddoc": ddoc, "view": view, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_partition_view(**req_copy) def test_post_partition_view_value_error_with_retries(self): _service.enable_retries() self.test_post_partition_view_value_error() _service.disable_retries() self.test_post_partition_view_value_error() class TestPostPartitionViewAsStream(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_partition_view_as_stream_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_design/testString/_view/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' ddoc = 'testString' view = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = True inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' endkey_docid = 'testString' group = False group_level = 1 key = 'testString' keys = ['examplekey'] reduce = True stable = False startkey = 'testString' startkey_docid = 'testString' update = 'true' # Invoke method response = _service.post_partition_view_as_stream( db, partition_key, ddoc, view, att_encoding_info=att_encoding_info, attachments=attachments, conflicts=conflicts, descending=descending, include_docs=include_docs, inclusive_end=inclusive_end, limit=limit, skip=skip, update_seq=update_seq, endkey=endkey, endkey_docid=endkey_docid, group=group, group_level=group_level, key=key, keys=keys, reduce=reduce, stable=stable, startkey=startkey, startkey_docid=startkey_docid, update=update, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['att_encoding_info'] == False assert req_body['attachments'] == False assert req_body['conflicts'] == False assert req_body['descending'] == False assert req_body['include_docs'] == True assert req_body['inclusive_end'] == True assert req_body['limit'] == 10 assert req_body['skip'] == 0 assert req_body['update_seq'] == False assert req_body['endkey'] == 'testString' assert req_body['endkey_docid'] == 'testString' assert req_body['group'] == False assert req_body['group_level'] == 1 assert req_body['key'] == 'testString' assert req_body['keys'] == ['examplekey'] assert req_body['reduce'] == True assert req_body['stable'] == False assert req_body['startkey'] == 'testString' assert req_body['startkey_docid'] == 'testString' assert req_body['update'] == 'true' # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_partition_view_as_stream_all_params_with_retries(self): # Enable retries and run test_post_partition_view_as_stream_all_params. _service.enable_retries() self.test_post_partition_view_as_stream_all_params() # Disable retries and run test_post_partition_view_as_stream_all_params. _service.disable_retries() self.test_post_partition_view_as_stream_all_params() @responses.activate def test_post_partition_view_as_stream_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_design/testString/_view/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' ddoc = 'testString' view = 'testString' att_encoding_info = False attachments = False conflicts = False descending = False include_docs = True inclusive_end = True limit = 10 skip = 0 update_seq = False endkey = 'testString' endkey_docid = 'testString' group = False group_level = 1 key = 'testString' keys = ['examplekey'] reduce = True stable = False startkey = 'testString' startkey_docid = 'testString' update = 'true' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "partition_key": partition_key, "ddoc": ddoc, "view": view, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_partition_view_as_stream(**req_copy) def test_post_partition_view_as_stream_value_error_with_retries(self): # Enable retries and run test_post_partition_view_as_stream_value_error. _service.enable_retries() self.test_post_partition_view_as_stream_value_error() # Disable retries and run test_post_partition_view_as_stream_value_error. _service.disable_retries() self.test_post_partition_view_as_stream_value_error() class TestPostPartitionFind(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_partition_find_all_params(self): url = self.preprocess_url(_base_url + '/testString/_partition/testString/_find') mock_response = '{"bookmark": "bookmark", "docs": [{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}], "execution_stats": {"execution_time_ms": 17, "results_returned": 0, "total_docs_examined": 0, "total_keys_examined": 0, "total_quorum_docs_examined": 0}, "warning": "warning"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) db = 'testString' partition_key = 'testString' selector = {} bookmark = 'testString' conflicts = True execution_stats = True fields = ['testString'] limit = 0 skip = 0 sort = [{}] stable = True update = 'true' use_index = ['testString'] response = _service.post_partition_find( db, partition_key, selector, bookmark=bookmark, conflicts=conflicts, execution_stats=execution_stats, fields=fields, limit=limit, skip=skip, sort=sort, stable=stable, update=update, use_index=use_index, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['selector'] == {} assert req_body['bookmark'] == 'testString' assert req_body['conflicts'] == True assert req_body['execution_stats'] == True assert req_body['fields'] == ['testString'] assert req_body['limit'] == 0 assert req_body['skip'] == 0 assert req_body['sort'] == [{}] assert req_body['stable'] == True assert req_body['update'] == 'true' assert req_body['use_index'] == ['testString'] def test_post_partition_find_all_params_with_retries(self): _service.enable_retries() self.test_post_partition_find_all_params() _service.disable_retries() self.test_post_partition_find_all_params() @responses.activate def test_post_partition_find_value_error(self): url = self.preprocess_url(_base_url + '/testString/_partition/testString/_find') mock_response = '{"bookmark": "bookmark", "docs": [{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}], "execution_stats": {"execution_time_ms": 17, "results_returned": 0, "total_docs_examined": 0, "total_keys_examined": 0, "total_quorum_docs_examined": 0}, "warning": "warning"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) db = 'testString' partition_key = 'testString' selector = {} bookmark = 'testString' conflicts = True execution_stats = True fields = ['testString'] limit = 0 skip = 0 sort = [{}] stable = True update = 'true' use_index = ['testString'] req_param_dict = { "db": db, "partition_key": partition_key, "selector": selector, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_partition_find(**req_copy) def test_post_partition_find_value_error_with_retries(self): _service.enable_retries() self.test_post_partition_find_value_error() _service.disable_retries() self.test_post_partition_find_value_error() class TestPostPartitionFindAsStream(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_partition_find_as_stream_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_find') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' selector = {} bookmark = 'testString' conflicts = True execution_stats = True fields = ['productid', 'name', 'description'] limit = 0 skip = 0 sort = [{}] stable = True update = 'true' use_index = ['testString'] # Invoke method response = _service.post_partition_find_as_stream( db, partition_key, selector, bookmark=bookmark, conflicts=conflicts, execution_stats=execution_stats, fields=fields, limit=limit, skip=skip, sort=sort, stable=stable, update=update, use_index=use_index, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['selector'] == {} assert req_body['bookmark'] == 'testString' assert req_body['conflicts'] == True assert req_body['execution_stats'] == True assert req_body['fields'] == ['productid', 'name', 'description'] assert req_body['limit'] == 0 assert req_body['skip'] == 0 assert req_body['sort'] == [{}] assert req_body['stable'] == True assert req_body['update'] == 'true' assert req_body['use_index'] == ['testString'] # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_partition_find_as_stream_all_params_with_retries(self): # Enable retries and run test_post_partition_find_as_stream_all_params. _service.enable_retries() self.test_post_partition_find_as_stream_all_params() # Disable retries and run test_post_partition_find_as_stream_all_params. _service.disable_retries() self.test_post_partition_find_as_stream_all_params() @responses.activate def test_post_partition_find_as_stream_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_partition/testString/_find') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' partition_key = 'testString' selector = {} bookmark = 'testString' conflicts = True execution_stats = True fields = ['productid', 'name', 'description'] limit = 0 skip = 0 sort = [{}] stable = True update = 'true' use_index = ['testString'] # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "partition_key": partition_key, "selector": selector, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_partition_find_as_stream(**req_copy) def test_post_partition_find_as_stream_value_error_with_retries(self): # Enable retries and run test_post_partition_find_as_stream_value_error. _service.enable_retries() self.test_post_partition_find_as_stream_value_error() # Disable retries and run test_post_partition_find_as_stream_value_error. _service.disable_retries() self.test_post_partition_find_as_stream_value_error() # endregion ############################################################################## # End of Service: PartitionedDatabases ############################################################################## ############################################################################## # Start of Service: Queries ############################################################################## # region class TestNewInstance(): def test_new_instance(self): os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestPostExplain(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_explain_all_params(self): url = self.preprocess_url(_base_url + '/testString/_explain') mock_response = '{"dbname": "dbname", "fields": ["fields"], "index": {"ddoc": "ddoc", "def": {"default_analyzer": {"name": "classic", "stopwords": ["stopwords"]}, "default_field": {"analyzer": {"name": "classic", "stopwords": ["stopwords"]}, "enabled": true}, "fields": [{"name": "name", "type": "boolean"}], "index_array_lengths": true, "partial_filter_selector": {"mapKey": "anyValue"}}, "name": "name", "type": "json"}, "limit": 0, "opts": {"mapKey": "anyValue"}, "range": {"end_key": ["anyValue"], "start_key": ["anyValue"]}, "selector": {"mapKey": "anyValue"}, "skip": 0}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) db = 'testString' selector = {} bookmark = 'testString' conflicts = True execution_stats = True fields = ['testString'] limit = 0 skip = 0 sort = [{}] stable = True update = 'true' use_index = ['testString'] r = 1 response = _service.post_explain( db, selector, bookmark=bookmark, conflicts=conflicts, execution_stats=execution_stats, fields=fields, limit=limit, skip=skip, sort=sort, stable=stable, update=update, use_index=use_index, r=r, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['selector'] == {} assert req_body['bookmark'] == 'testString' assert req_body['conflicts'] == True assert req_body['execution_stats'] == True assert req_body['fields'] == ['testString'] assert req_body['limit'] == 0 assert req_body['skip'] == 0 assert req_body['sort'] == [{}] assert req_body['stable'] == True assert req_body['update'] == 'true' assert req_body['use_index'] == ['testString'] assert req_body['r'] == 1 def test_post_explain_all_params_with_retries(self): _service.enable_retries() self.test_post_explain_all_params() _service.disable_retries() self.test_post_explain_all_params() @responses.activate def test_post_explain_value_error(self): url = self.preprocess_url(_base_url + '/testString/_explain') mock_response = '{"dbname": "dbname", "fields": ["fields"], "index": {"ddoc": "ddoc", "def": {"default_analyzer": {"name": "classic", "stopwords": ["stopwords"]}, "default_field": {"analyzer": {"name": "classic", "stopwords": ["stopwords"]}, "enabled": true}, "fields": [{"name": "name", "type": "boolean"}], "index_array_lengths": true, "partial_filter_selector": {"mapKey": "anyValue"}}, "name": "name", "type": "json"}, "limit": 0, "opts": {"mapKey": "anyValue"}, "range": {"end_key": ["anyValue"], "start_key": ["anyValue"]}, "selector": {"mapKey": "anyValue"}, "skip": 0}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) db = 'testString' selector = {} bookmark = 'testString' conflicts = True execution_stats = True fields = ['testString'] limit = 0 skip = 0 sort = [{}] stable = True update = 'true' use_index = ['testString'] r = 1 req_param_dict = { "db": db, "selector": selector, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_explain(**req_copy) def test_post_explain_value_error_with_retries(self): _service.enable_retries() self.test_post_explain_value_error() _service.disable_retries() self.test_post_explain_value_error() class TestPostFind(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_find_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_find') mock_response = '{"bookmark": "bookmark", "docs": [{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}], "execution_stats": {"execution_time_ms": 17, "results_returned": 0, "total_docs_examined": 0, "total_keys_examined": 0, "total_quorum_docs_examined": 0}, "warning": "warning"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' selector = {} bookmark = 'testString' conflicts = True execution_stats = True fields = ['_id', 'type', 'name', 'email'] limit = 3 skip = 0 sort = [{}] stable = True update = 'true' use_index = ['testString'] r = 1 # Invoke method response = _service.post_find( db, selector, bookmark=bookmark, conflicts=conflicts, execution_stats=execution_stats, fields=fields, limit=limit, skip=skip, sort=sort, stable=stable, update=update, use_index=use_index, r=r, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['selector'] == {} assert req_body['bookmark'] == 'testString' assert req_body['conflicts'] == True assert req_body['execution_stats'] == True assert req_body['fields'] == ['_id', 'type', 'name', 'email'] assert req_body['limit'] == 3 assert req_body['skip'] == 0 assert req_body['sort'] == [{}] assert req_body['stable'] == True assert req_body['update'] == 'true' assert req_body['use_index'] == ['testString'] assert req_body['r'] == 1 def test_post_find_all_params_with_retries(self): # Enable retries and run test_post_find_all_params. _service.enable_retries() self.test_post_find_all_params() # Disable retries and run test_post_find_all_params. _service.disable_retries() self.test_post_find_all_params() @responses.activate def test_post_find_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_find') mock_response = '{"bookmark": "bookmark", "docs": [{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}], "execution_stats": {"execution_time_ms": 17, "results_returned": 0, "total_docs_examined": 0, "total_keys_examined": 0, "total_quorum_docs_examined": 0}, "warning": "warning"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' selector = {} bookmark = 'testString' conflicts = True execution_stats = True fields = ['_id', 'type', 'name', 'email'] limit = 3 skip = 0 sort = [{}] stable = True update = 'true' use_index = ['testString'] r = 1 # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "selector": selector, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_find(**req_copy) def test_post_find_value_error_with_retries(self): # Enable retries and run test_post_find_value_error. _service.enable_retries() self.test_post_find_value_error() # Disable retries and run test_post_find_value_error. _service.disable_retries() self.test_post_find_value_error() class TestPostFindAsStream(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_find_as_stream_all_params(self): url = self.preprocess_url(_base_url + '/testString/_find') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) db = 'testString' selector = {} bookmark = 'testString' conflicts = True execution_stats = True fields = ['_id', 'type', 'name', 'email'] limit = 3 skip = 0 sort = [{}] stable = True update = 'true' use_index = ['testString'] r = 1 response = _service.post_find_as_stream( db, selector, bookmark=bookmark, conflicts=conflicts, execution_stats=execution_stats, fields=fields, limit=limit, skip=skip, sort=sort, stable=stable, update=update, use_index=use_index, r=r, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['selector'] == {} assert req_body['bookmark'] == 'testString' assert req_body['conflicts'] == True assert req_body['execution_stats'] == True assert req_body['fields'] == ['_id', 'type', 'name', 'email'] assert req_body['limit'] == 3 assert req_body['skip'] == 0 assert req_body['sort'] == [{}] assert req_body['stable'] == True assert req_body['update'] == 'true' assert req_body['use_index'] == ['testString'] assert req_body['r'] == 1 result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_find_as_stream_all_params_with_retries(self): _service.enable_retries() self.test_post_find_as_stream_all_params() _service.disable_retries() self.test_post_find_as_stream_all_params() @responses.activate def test_post_find_as_stream_value_error(self): url = self.preprocess_url(_base_url + '/testString/_find') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) db = 'testString' selector = {} bookmark = 'testString' conflicts = True execution_stats = True fields = ['_id', 'type', 'name', 'email'] limit = 3 skip = 0 sort = [{}] stable = True update = 'true' use_index = ['testString'] r = 1 req_param_dict = { "db": db, "selector": selector, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_find_as_stream(**req_copy) def test_post_find_as_stream_value_error_with_retries(self): _service.enable_retries() self.test_post_find_as_stream_value_error() _service.disable_retries() self.test_post_find_as_stream_value_error() class TestGetIndexesInformation(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_indexes_information_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_index') mock_response = '{"total_rows": 0, "indexes": [{"ddoc": "ddoc", "def": {"default_analyzer": {"name": "classic", "stopwords": ["stopwords"]}, "default_field": {"analyzer": {"name": "classic", "stopwords": ["stopwords"]}, "enabled": true}, "fields": [{"name": "name", "type": "boolean"}], "index_array_lengths": true, "partial_filter_selector": {"mapKey": "anyValue"}}, "name": "name", "type": "json"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' # Invoke method response = _service.get_indexes_information( db, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_indexes_information_all_params_with_retries(self): # Enable retries and run test_get_indexes_information_all_params. _service.enable_retries() self.test_get_indexes_information_all_params() # Disable retries and run test_get_indexes_information_all_params. _service.disable_retries() self.test_get_indexes_information_all_params() @responses.activate def test_get_indexes_information_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_index') mock_response = '{"total_rows": 0, "indexes": [{"ddoc": "ddoc", "def": {"default_analyzer": {"name": "classic", "stopwords": ["stopwords"]}, "default_field": {"analyzer": {"name": "classic", "stopwords": ["stopwords"]}, "enabled": true}, "fields": [{"name": "name", "type": "boolean"}], "index_array_lengths": true, "partial_filter_selector": {"mapKey": "anyValue"}}, "name": "name", "type": "json"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_indexes_information(**req_copy) def test_get_indexes_information_value_error_with_retries(self): # Enable retries and run test_get_indexes_information_value_error. _service.enable_retries() self.test_get_indexes_information_value_error() # Disable retries and run test_get_indexes_information_value_error. _service.disable_retries() self.test_get_indexes_information_value_error() class TestPostIndex(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_index_all_params(self): url = self.preprocess_url(_base_url + '/testString/_index') mock_response = '{"id": "id", "name": "name", "result": "created"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) analyzer_model = {} analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] index_text_operator_default_field_model = {} index_text_operator_default_field_model['analyzer'] = analyzer_model index_text_operator_default_field_model['enabled'] = True index_field_model = {} index_field_model['name'] = 'testString' index_field_model['type'] = 'boolean' index_field_model['foo'] = 'asc' index_definition_model = {} index_definition_model['default_analyzer'] = analyzer_model index_definition_model['default_field'] = index_text_operator_default_field_model index_definition_model['fields'] = [index_field_model] index_definition_model['index_array_lengths'] = True index_definition_model['partial_filter_selector'] = {} db = 'testString' index = index_definition_model ddoc = 'testString' def_ = index_definition_model name = 'testString' partitioned = True type = 'json' response = _service.post_index( db, index, ddoc=ddoc, def_=def_, name=name, partitioned=partitioned, type=type, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['index'] == index_definition_model assert req_body['ddoc'] == 'testString' assert req_body['def'] == index_definition_model assert req_body['name'] == 'testString' assert req_body['partitioned'] == True assert req_body['type'] == 'json' def test_post_index_all_params_with_retries(self): _service.enable_retries() self.test_post_index_all_params() _service.disable_retries() self.test_post_index_all_params() @responses.activate def test_post_index_value_error(self): url = self.preprocess_url(_base_url + '/testString/_index') mock_response = '{"id": "id", "name": "name", "result": "created"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) analyzer_model = {} analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] index_text_operator_default_field_model = {} index_text_operator_default_field_model['analyzer'] = analyzer_model index_text_operator_default_field_model['enabled'] = True index_field_model = {} index_field_model['name'] = 'testString' index_field_model['type'] = 'boolean' index_field_model['foo'] = 'asc' index_definition_model = {} index_definition_model['default_analyzer'] = analyzer_model index_definition_model['default_field'] = index_text_operator_default_field_model index_definition_model['fields'] = [index_field_model] index_definition_model['index_array_lengths'] = True index_definition_model['partial_filter_selector'] = {} db = 'testString' index = index_definition_model ddoc = 'testString' def_ = index_definition_model name = 'testString' partitioned = True type = 'json' req_param_dict = { "db": db, "index": index, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_index(**req_copy) def test_post_index_value_error_with_retries(self): _service.enable_retries() self.test_post_index_value_error() _service.disable_retries() self.test_post_index_value_error() class TestDeleteIndex(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_delete_index_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_index/_design/testString/json/testString') mock_response = '{"ok": true}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' type = 'json' index = 'testString' # Invoke method response = _service.delete_index( db, ddoc, type, index, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_delete_index_all_params_with_retries(self): # Enable retries and run test_delete_index_all_params. _service.enable_retries() self.test_delete_index_all_params() # Disable retries and run test_delete_index_all_params. _service.disable_retries() self.test_delete_index_all_params() @responses.activate def test_delete_index_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_index/_design/testString/json/testString') mock_response = '{"ok": true}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' type = 'json' index = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, "type": type, "index": index, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_index(**req_copy) def test_delete_index_value_error_with_retries(self): # Enable retries and run test_delete_index_value_error. _service.enable_retries() self.test_delete_index_value_error() # Disable retries and run test_delete_index_value_error. _service.disable_retries() self.test_delete_index_value_error() # endregion ############################################################################## # End of Service: Queries ############################################################################## ############################################################################## # Start of Service: Searches ############################################################################## # region class TestNewInstance(): def test_new_instance(self): os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestPostSearchAnalyze(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_search_analyze_all_params(self): url = self.preprocess_url(_base_url + '/_search_analyze') mock_response = '{"tokens": ["tokens"]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) analyzer = 'arabic' text = 'testString' response = _service.post_search_analyze( analyzer, text, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['analyzer'] == 'arabic' assert req_body['text'] == 'testString' def test_post_search_analyze_all_params_with_retries(self): _service.enable_retries() self.test_post_search_analyze_all_params() _service.disable_retries() self.test_post_search_analyze_all_params() @responses.activate def test_post_search_analyze_value_error(self): url = self.preprocess_url(_base_url + '/_search_analyze') mock_response = '{"tokens": ["tokens"]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) analyzer = 'arabic' text = 'testString' req_param_dict = { "analyzer": analyzer, "text": text, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_search_analyze(**req_copy) def test_post_search_analyze_value_error_with_retries(self): _service.enable_retries() self.test_post_search_analyze_value_error() _service.disable_retries() self.test_post_search_analyze_value_error() class TestPostSearch(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_search_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_search/testString') mock_response = '{"total_rows": 0, "bookmark": "bookmark", "by": "by", "counts": {"mapKey": {"mapKey": 0}}, "ranges": {"mapKey": {"mapKey": 0}}, "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "fields": {"mapKey": "anyValue"}, "highlights": {"mapKey": ["inner"]}, "id": "id"}], "groups": [{"total_rows": 0, "bookmark": "bookmark", "by": "by", "counts": {"mapKey": {"mapKey": 0}}, "ranges": {"mapKey": {"mapKey": 0}}, "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "fields": {"mapKey": "anyValue"}, "highlights": {"mapKey": ["inner"]}, "id": "id"}]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' query = 'testString' bookmark = 'testString' highlight_fields = ['testString'] highlight_number = 1 highlight_post_tag = '</em>' highlight_pre_tag = '<em>' highlight_size = 1 include_docs = False include_fields = ['testString'] limit = 0 sort = ['testString'] stale = 'ok' counts = ['testString'] drilldown = [['testString']] group_field = 'testString' group_limit = 1 group_sort = ['testString'] ranges = {} # Invoke method response = _service.post_search( db, ddoc, index, query, bookmark=bookmark, highlight_fields=highlight_fields, highlight_number=highlight_number, highlight_post_tag=highlight_post_tag, highlight_pre_tag=highlight_pre_tag, highlight_size=highlight_size, include_docs=include_docs, include_fields=include_fields, limit=limit, sort=sort, stale=stale, counts=counts, drilldown=drilldown, group_field=group_field, group_limit=group_limit, group_sort=group_sort, ranges=ranges, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['query'] == 'testString' assert req_body['bookmark'] == 'testString' assert req_body['highlight_fields'] == ['testString'] assert req_body['highlight_number'] == 1 assert req_body['highlight_post_tag'] == '</em>' assert req_body['highlight_pre_tag'] == '<em>' assert req_body['highlight_size'] == 1 assert req_body['include_docs'] == False assert req_body['include_fields'] == ['testString'] assert req_body['limit'] == 0 assert req_body['sort'] == ['testString'] assert req_body['stale'] == 'ok' assert req_body['counts'] == ['testString'] assert req_body['drilldown'] == [['testString']] assert req_body['group_field'] == 'testString' assert req_body['group_limit'] == 1 assert req_body['group_sort'] == ['testString'] assert req_body['ranges'] == {} def test_post_search_all_params_with_retries(self): # Enable retries and run test_post_search_all_params. _service.enable_retries() self.test_post_search_all_params() # Disable retries and run test_post_search_all_params. _service.disable_retries() self.test_post_search_all_params() @responses.activate def test_post_search_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_search/testString') mock_response = '{"total_rows": 0, "bookmark": "bookmark", "by": "by", "counts": {"mapKey": {"mapKey": 0}}, "ranges": {"mapKey": {"mapKey": 0}}, "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "fields": {"mapKey": "anyValue"}, "highlights": {"mapKey": ["inner"]}, "id": "id"}], "groups": [{"total_rows": 0, "bookmark": "bookmark", "by": "by", "counts": {"mapKey": {"mapKey": 0}}, "ranges": {"mapKey": {"mapKey": 0}}, "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "fields": {"mapKey": "anyValue"}, "highlights": {"mapKey": ["inner"]}, "id": "id"}]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' query = 'testString' bookmark = 'testString' highlight_fields = ['testString'] highlight_number = 1 highlight_post_tag = '</em>' highlight_pre_tag = '<em>' highlight_size = 1 include_docs = False include_fields = ['testString'] limit = 0 sort = ['testString'] stale = 'ok' counts = ['testString'] drilldown = [['testString']] group_field = 'testString' group_limit = 1 group_sort = ['testString'] ranges = {} # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, "index": index, "query": query, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_search(**req_copy) def test_post_search_value_error_with_retries(self): # Enable retries and run test_post_search_value_error. _service.enable_retries() self.test_post_search_value_error() # Disable retries and run test_post_search_value_error. _service.disable_retries() self.test_post_search_value_error() class TestPostSearchAsStream(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_search_as_stream_all_params(self): url = self.preprocess_url(_base_url + '/testString/_design/testString/_search/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) db = 'testString' ddoc = 'testString' index = 'testString' query = 'testString' bookmark = 'testString' highlight_fields = ['testString'] highlight_number = 1 highlight_post_tag = '</em>' highlight_pre_tag = '<em>' highlight_size = 1 include_docs = False include_fields = ['testString'] limit = 3 sort = ['testString'] stale = 'ok' counts = ['testString'] drilldown = [['testString']] group_field = 'testString' group_limit = 1 group_sort = ['testString'] ranges = {} response = _service.post_search_as_stream( db, ddoc, index, query, bookmark=bookmark, highlight_fields=highlight_fields, highlight_number=highlight_number, highlight_post_tag=highlight_post_tag, highlight_pre_tag=highlight_pre_tag, highlight_size=highlight_size, include_docs=include_docs, include_fields=include_fields, limit=limit, sort=sort, stale=stale, counts=counts, drilldown=drilldown, group_field=group_field, group_limit=group_limit, group_sort=group_sort, ranges=ranges, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['query'] == 'testString' assert req_body['bookmark'] == 'testString' assert req_body['highlight_fields'] == ['testString'] assert req_body['highlight_number'] == 1 assert req_body['highlight_post_tag'] == '</em>' assert req_body['highlight_pre_tag'] == '<em>' assert req_body['highlight_size'] == 1 assert req_body['include_docs'] == False assert req_body['include_fields'] == ['testString'] assert req_body['limit'] == 3 assert req_body['sort'] == ['testString'] assert req_body['stale'] == 'ok' assert req_body['counts'] == ['testString'] assert req_body['drilldown'] == [['testString']] assert req_body['group_field'] == 'testString' assert req_body['group_limit'] == 1 assert req_body['group_sort'] == ['testString'] assert req_body['ranges'] == {} result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_post_search_as_stream_all_params_with_retries(self): _service.enable_retries() self.test_post_search_as_stream_all_params() _service.disable_retries() self.test_post_search_as_stream_all_params() @responses.activate def test_post_search_as_stream_value_error(self): url = self.preprocess_url(_base_url + '/testString/_design/testString/_search/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) db = 'testString' ddoc = 'testString' index = 'testString' query = 'testString' bookmark = 'testString' highlight_fields = ['testString'] highlight_number = 1 highlight_post_tag = '</em>' highlight_pre_tag = '<em>' highlight_size = 1 include_docs = False include_fields = ['testString'] limit = 3 sort = ['testString'] stale = 'ok' counts = ['testString'] drilldown = [['testString']] group_field = 'testString' group_limit = 1 group_sort = ['testString'] ranges = {} req_param_dict = { "db": db, "ddoc": ddoc, "index": index, "query": query, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_search_as_stream(**req_copy) def test_post_search_as_stream_value_error_with_retries(self): _service.enable_retries() self.test_post_search_as_stream_value_error() _service.disable_retries() self.test_post_search_as_stream_value_error() class TestGetSearchInfo(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_search_info_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_search_info/testString') mock_response = '{"name": "name", "search_index": {"committed_seq": 13, "disk_size": 0, "doc_count": 0, "doc_del_count": 0, "pending_seq": 11}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' # Invoke method response = _service.get_search_info( db, ddoc, index, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_search_info_all_params_with_retries(self): # Enable retries and run test_get_search_info_all_params. _service.enable_retries() self.test_get_search_info_all_params() # Disable retries and run test_get_search_info_all_params. _service.disable_retries() self.test_get_search_info_all_params() @responses.activate def test_get_search_info_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_search_info/testString') mock_response = '{"name": "name", "search_index": {"committed_seq": 13, "disk_size": 0, "doc_count": 0, "doc_del_count": 0, "pending_seq": 11}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, "index": index, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_search_info(**req_copy) def test_get_search_info_value_error_with_retries(self): # Enable retries and run test_get_search_info_value_error. _service.enable_retries() self.test_get_search_info_value_error() # Disable retries and run test_get_search_info_value_error. _service.disable_retries() self.test_get_search_info_value_error() # endregion ############################################################################## # End of Service: Searches ############################################################################## ############################################################################## # Start of Service: Geospatial ############################################################################## # region class TestNewInstance(): def test_new_instance(self): os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestGetGeo(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_geo_all_params(self): url = self.preprocess_url(_base_url + '/testString/_design/testString/_geo/testString') mock_response = '{"bookmark": "bookmark", "features": [{"_id": "id", "_rev": "rev", "bbox": [4], "geometry": {"type": "Point", "coordinates": ["anyValue"]}, "properties": {"mapKey": "anyValue"}, "type": "Feature"}], "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "geometry": {"type": "Point", "coordinates": ["anyValue"]}, "id": "id", "rev": "rev"}], "type": "FeatureCollection"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) db = 'testString' ddoc = 'testString' index = 'testString' bbox = 'testString' bookmark = 'testString' format = 'view' g = 'testString' include_docs = False lat = -90 limit = 0 lon = -180 nearest = False radius = 0 rangex = 0 rangey = 0 relation = 'intersects' skip = 0 stale = 'ok' response = _service.get_geo( db, ddoc, index, bbox=bbox, bookmark=bookmark, format=format, g=g, include_docs=include_docs, lat=lat, limit=limit, lon=lon, nearest=nearest, radius=radius, rangex=rangex, rangey=rangey, relation=relation, skip=skip, stale=stale, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'bbox={}'.format(bbox) in query_string assert 'bookmark={}'.format(bookmark) in query_string assert 'format={}'.format(format) in query_string assert 'g={}'.format(g) in query_string assert 'include_docs={}'.format('true' if include_docs else 'false') in query_string assert 'lat={}'.format(lat) in query_string assert 'limit={}'.format(limit) in query_string assert 'lon={}'.format(lon) in query_string assert 'nearest={}'.format('true' if nearest else 'false') in query_string assert 'radius={}'.format(radius) in query_string assert 'rangex={}'.format(rangex) in query_string assert 'rangey={}'.format(rangey) in query_string assert 'relation={}'.format(relation) in query_string assert 'skip={}'.format(skip) in query_string assert 'stale={}'.format(stale) in query_string def test_get_geo_all_params_with_retries(self): _service.enable_retries() self.test_get_geo_all_params() _service.disable_retries() self.test_get_geo_all_params() @responses.activate def test_get_geo_required_params(self): url = self.preprocess_url(_base_url + '/testString/_design/testString/_geo/testString') mock_response = '{"bookmark": "bookmark", "features": [{"_id": "id", "_rev": "rev", "bbox": [4], "geometry": {"type": "Point", "coordinates": ["anyValue"]}, "properties": {"mapKey": "anyValue"}, "type": "Feature"}], "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "geometry": {"type": "Point", "coordinates": ["anyValue"]}, "id": "id", "rev": "rev"}], "type": "FeatureCollection"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) db = 'testString' ddoc = 'testString' index = 'testString' response = _service.get_geo( db, ddoc, index, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_geo_required_params_with_retries(self): _service.enable_retries() self.test_get_geo_required_params() _service.disable_retries() self.test_get_geo_required_params() @responses.activate def test_get_geo_value_error(self): url = self.preprocess_url(_base_url + '/testString/_design/testString/_geo/testString') mock_response = '{"bookmark": "bookmark", "features": [{"_id": "id", "_rev": "rev", "bbox": [4], "geometry": {"type": "Point", "coordinates": ["anyValue"]}, "properties": {"mapKey": "anyValue"}, "type": "Feature"}], "rows": [{"doc": {"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}]}, "geometry": {"type": "Point", "coordinates": ["anyValue"]}, "id": "id", "rev": "rev"}], "type": "FeatureCollection"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) db = 'testString' ddoc = 'testString' index = 'testString' req_param_dict = { "db": db, "ddoc": ddoc, "index": index, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_geo(**req_copy) def test_get_geo_value_error_with_retries(self): _service.enable_retries() self.test_get_geo_value_error() _service.disable_retries() self.test_get_geo_value_error() class TestGetGeoAsStream(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_geo_as_stream_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_geo/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' bbox = 'testString' bookmark = 'testString' format = 'view' g = 'testString' include_docs = False lat = -90 limit = 0 lon = -180 nearest = False radius = 0 rangex = 0 rangey = 0 relation = 'intersects' skip = 0 stale = 'ok' # Invoke method response = _service.get_geo_as_stream( db, ddoc, index, bbox=bbox, bookmark=bookmark, format=format, g=g, include_docs=include_docs, lat=lat, limit=limit, lon=lon, nearest=nearest, radius=radius, rangex=rangex, rangey=rangey, relation=relation, skip=skip, stale=stale, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'bbox={}'.format(bbox) in query_string assert 'bookmark={}'.format(bookmark) in query_string assert 'format={}'.format(format) in query_string assert 'g={}'.format(g) in query_string assert 'include_docs={}'.format('true' if include_docs else 'false') in query_string assert 'lat={}'.format(lat) in query_string assert 'limit={}'.format(limit) in query_string assert 'lon={}'.format(lon) in query_string assert 'nearest={}'.format('true' if nearest else 'false') in query_string assert 'radius={}'.format(radius) in query_string assert 'rangex={}'.format(rangex) in query_string assert 'rangey={}'.format(rangey) in query_string assert 'relation={}'.format(relation) in query_string assert 'skip={}'.format(skip) in query_string assert 'stale={}'.format(stale) in query_string # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_get_geo_as_stream_all_params_with_retries(self): # Enable retries and run test_get_geo_as_stream_all_params. _service.enable_retries() self.test_get_geo_as_stream_all_params() # Disable retries and run test_get_geo_as_stream_all_params. _service.disable_retries() self.test_get_geo_as_stream_all_params() @responses.activate def test_get_geo_as_stream_required_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_geo/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' # Invoke method response = _service.get_geo_as_stream( db, ddoc, index, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Verify streamed JSON response result = response.get_result() assert isinstance(result, requests.models.Response) response_buf = result.iter_content(chunk_size=1024) assert str(next(response_buf), "utf-8") == mock_response def test_get_geo_as_stream_required_params_with_retries(self): # Enable retries and run test_get_geo_as_stream_required_params. _service.enable_retries() self.test_get_geo_as_stream_required_params() # Disable retries and run test_get_geo_as_stream_required_params. _service.disable_retries() self.test_get_geo_as_stream_required_params() @responses.activate def test_get_geo_as_stream_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_geo/testString') mock_response = '{"foo": "this is a mock response for JSON streaming"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, "index": index, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_geo_as_stream(**req_copy) def test_get_geo_as_stream_value_error_with_retries(self): # Enable retries and run test_get_geo_as_stream_value_error. _service.enable_retries() self.test_get_geo_as_stream_value_error() # Disable retries and run test_get_geo_as_stream_value_error. _service.disable_retries() self.test_get_geo_as_stream_value_error() class TestPostGeoCleanup(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_geo_cleanup_all_params(self): url = self.preprocess_url(_base_url + '/testString/_geo_cleanup') mock_response = '{"ok": true}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=202) db = 'testString' response = _service.post_geo_cleanup( db, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 202 def test_post_geo_cleanup_all_params_with_retries(self): _service.enable_retries() self.test_post_geo_cleanup_all_params() _service.disable_retries() self.test_post_geo_cleanup_all_params() @responses.activate def test_post_geo_cleanup_value_error(self): url = self.preprocess_url(_base_url + '/testString/_geo_cleanup') mock_response = '{"ok": true}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=202) db = 'testString' req_param_dict = { "db": db, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_geo_cleanup(**req_copy) def test_post_geo_cleanup_value_error_with_retries(self): _service.enable_retries() self.test_post_geo_cleanup_value_error() _service.disable_retries() self.test_post_geo_cleanup_value_error() class TestGetGeoIndexInformation(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_geo_index_information_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_geo_info/testString') mock_response = '{"geo_index": {"data_size": 0, "disk_size": 0, "doc_count": 0}, "name": "name"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' # Invoke method response = _service.get_geo_index_information( db, ddoc, index, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_geo_index_information_all_params_with_retries(self): # Enable retries and run test_get_geo_index_information_all_params. _service.enable_retries() self.test_get_geo_index_information_all_params() # Disable retries and run test_get_geo_index_information_all_params. _service.disable_retries() self.test_get_geo_index_information_all_params() @responses.activate def test_get_geo_index_information_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/testString/_design/testString/_geo_info/testString') mock_response = '{"geo_index": {"data_size": 0, "disk_size": 0, "doc_count": 0}, "name": "name"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' ddoc = 'testString' index = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "ddoc": ddoc, "index": index, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_geo_index_information(**req_copy) def test_get_geo_index_information_value_error_with_retries(self): # Enable retries and run test_get_geo_index_information_value_error. _service.enable_retries() self.test_get_geo_index_information_value_error() # Disable retries and run test_get_geo_index_information_value_error. _service.disable_retries() self.test_get_geo_index_information_value_error() # endregion ############################################################################## # End of Service: Geospatial ############################################################################## ############################################################################## # Start of Service: Replication ############################################################################## # region class TestNewInstance(): def test_new_instance(self): os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestHeadReplicationDocument(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_head_replication_document_all_params(self): url = self.preprocess_url(_base_url + '/_replicator/testString') responses.add(responses.HEAD, url, status=200) doc_id = 'testString' if_none_match = 'testString' response = _service.head_replication_document( doc_id, if_none_match=if_none_match, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 def test_head_replication_document_all_params_with_retries(self): _service.enable_retries() self.test_head_replication_document_all_params() _service.disable_retries() self.test_head_replication_document_all_params() @responses.activate def test_head_replication_document_required_params(self): url = self.preprocess_url(_base_url + '/_replicator/testString') responses.add(responses.HEAD, url, status=200) doc_id = 'testString' response = _service.head_replication_document( doc_id, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 def test_head_replication_document_required_params_with_retries(self): _service.enable_retries() self.test_head_replication_document_required_params() _service.disable_retries() self.test_head_replication_document_required_params() @responses.activate def test_head_replication_document_value_error(self): url = self.preprocess_url(_base_url + '/_replicator/testString') responses.add(responses.HEAD, url, status=200) doc_id = 'testString' req_param_dict = { "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.head_replication_document(**req_copy) def test_head_replication_document_value_error_with_retries(self): _service.enable_retries() self.test_head_replication_document_value_error() _service.disable_retries() self.test_head_replication_document_value_error() class TestHeadSchedulerDocument(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_head_scheduler_document_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/_scheduler/docs/_replicator/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values doc_id = 'testString' # Invoke method response = _service.head_scheduler_document( doc_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_head_scheduler_document_all_params_with_retries(self): # Enable retries and run test_head_scheduler_document_all_params. _service.enable_retries() self.test_head_scheduler_document_all_params() # Disable retries and run test_head_scheduler_document_all_params. _service.disable_retries() self.test_head_scheduler_document_all_params() @responses.activate def test_head_scheduler_document_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/_scheduler/docs/_replicator/testString') responses.add(responses.HEAD, url, status=200) # Set up parameter values doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.head_scheduler_document(**req_copy) def test_head_scheduler_document_value_error_with_retries(self): # Enable retries and run test_head_scheduler_document_value_error. _service.enable_retries() self.test_head_scheduler_document_value_error() # Disable retries and run test_head_scheduler_document_value_error. _service.disable_retries() self.test_head_scheduler_document_value_error() class TestHeadSchedulerJob(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_head_scheduler_job_all_params(self): url = self.preprocess_url(_base_url + '/_scheduler/jobs/testString') responses.add(responses.HEAD, url, status=200) job_id = 'testString' response = _service.head_scheduler_job( job_id, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 def test_head_scheduler_job_all_params_with_retries(self): _service.enable_retries() self.test_head_scheduler_job_all_params() _service.disable_retries() self.test_head_scheduler_job_all_params() @responses.activate def test_head_scheduler_job_value_error(self): url = self.preprocess_url(_base_url + '/_scheduler/jobs/testString') responses.add(responses.HEAD, url, status=200) job_id = 'testString' req_param_dict = { "job_id": job_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.head_scheduler_job(**req_copy) def test_head_scheduler_job_value_error_with_retries(self): _service.enable_retries() self.test_head_scheduler_job_value_error() _service.disable_retries() self.test_head_scheduler_job_value_error() class TestDeleteReplicationDocument(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_delete_replication_document_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/_replicator/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=201) # Set up parameter values doc_id = 'testString' if_match = 'testString' batch = 'ok' rev = 'testString' # Invoke method response = _service.delete_replication_document( doc_id, if_match=if_match, batch=batch, rev=rev, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'batch={}'.format(batch) in query_string assert 'rev={}'.format(rev) in query_string def test_delete_replication_document_all_params_with_retries(self): # Enable retries and run test_delete_replication_document_all_params. _service.enable_retries() self.test_delete_replication_document_all_params() # Disable retries and run test_delete_replication_document_all_params. _service.disable_retries() self.test_delete_replication_document_all_params() @responses.activate def test_delete_replication_document_required_params(self): # Set up mock url = self.preprocess_url(_base_url + '/_replicator/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=201) # Set up parameter values doc_id = 'testString' # Invoke method response = _service.delete_replication_document( doc_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 def test_delete_replication_document_required_params_with_retries(self): # Enable retries and run test_delete_replication_document_required_params. _service.enable_retries() self.test_delete_replication_document_required_params() # Disable retries and run test_delete_replication_document_required_params. _service.disable_retries() self.test_delete_replication_document_required_params() @responses.activate def test_delete_replication_document_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/_replicator/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.DELETE, url, body=mock_response, content_type='application/json', status=201) # Set up parameter values doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_replication_document(**req_copy) def test_delete_replication_document_value_error_with_retries(self): # Enable retries and run test_delete_replication_document_value_error. _service.enable_retries() self.test_delete_replication_document_value_error() # Disable retries and run test_delete_replication_document_value_error. _service.disable_retries() self.test_delete_replication_document_value_error() class TestGetReplicationDocument(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_replication_document_all_params(self): url = self.preprocess_url(_base_url + '/_replicator/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}], "cancel": true, "checkpoint_interval": 0, "connection_timeout": 0, "continuous": false, "create_target": false, "create_target_params": {"n": 1, "partitioned": false, "q": 1}, "doc_ids": ["doc_ids"], "filter": "filter", "http_connections": 1, "query_params": {"mapKey": "inner"}, "retries_per_request": 0, "selector": {"mapKey": "anyValue"}, "since_seq": "since_seq", "socket_options": "socket_options", "source": {"auth": {"basic": {"password": "password", "username": "username"}, "iam": {"api_key": "api_key"}}, "headers": {"mapKey": "inner"}, "url": "url"}, "source_proxy": "source_proxy", "target": {"auth": {"basic": {"password": "password", "username": "username"}, "iam": {"api_key": "api_key"}}, "headers": {"mapKey": "inner"}, "url": "url"}, "target_proxy": "target_proxy", "use_checkpoints": true, "user_ctx": {"db": "db", "name": "name", "roles": ["_reader"]}, "worker_batch_size": 1, "worker_processes": 1}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) doc_id = 'testString' if_none_match = 'testString' attachments = False att_encoding_info = False conflicts = False deleted_conflicts = False latest = False local_seq = False meta = False rev = 'testString' revs = False revs_info = False response = _service.get_replication_document( doc_id, if_none_match=if_none_match, attachments=attachments, att_encoding_info=att_encoding_info, conflicts=conflicts, deleted_conflicts=deleted_conflicts, latest=latest, local_seq=local_seq, meta=meta, rev=rev, revs=revs, revs_info=revs_info, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'attachments={}'.format('true' if attachments else 'false') in query_string assert 'att_encoding_info={}'.format('true' if att_encoding_info else 'false') in query_string assert 'conflicts={}'.format('true' if conflicts else 'false') in query_string assert 'deleted_conflicts={}'.format('true' if deleted_conflicts else 'false') in query_string assert 'latest={}'.format('true' if latest else 'false') in query_string assert 'local_seq={}'.format('true' if local_seq else 'false') in query_string assert 'meta={}'.format('true' if meta else 'false') in query_string assert 'rev={}'.format(rev) in query_string assert 'revs={}'.format('true' if revs else 'false') in query_string assert 'revs_info={}'.format('true' if revs_info else 'false') in query_string def test_get_replication_document_all_params_with_retries(self): _service.enable_retries() self.test_get_replication_document_all_params() _service.disable_retries() self.test_get_replication_document_all_params() @responses.activate def test_get_replication_document_required_params(self): url = self.preprocess_url(_base_url + '/_replicator/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}], "cancel": true, "checkpoint_interval": 0, "connection_timeout": 0, "continuous": false, "create_target": false, "create_target_params": {"n": 1, "partitioned": false, "q": 1}, "doc_ids": ["doc_ids"], "filter": "filter", "http_connections": 1, "query_params": {"mapKey": "inner"}, "retries_per_request": 0, "selector": {"mapKey": "anyValue"}, "since_seq": "since_seq", "socket_options": "socket_options", "source": {"auth": {"basic": {"password": "password", "username": "username"}, "iam": {"api_key": "api_key"}}, "headers": {"mapKey": "inner"}, "url": "url"}, "source_proxy": "source_proxy", "target": {"auth": {"basic": {"password": "password", "username": "username"}, "iam": {"api_key": "api_key"}}, "headers": {"mapKey": "inner"}, "url": "url"}, "target_proxy": "target_proxy", "use_checkpoints": true, "user_ctx": {"db": "db", "name": "name", "roles": ["_reader"]}, "worker_batch_size": 1, "worker_processes": 1}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) doc_id = 'testString' response = _service.get_replication_document( doc_id, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_replication_document_required_params_with_retries(self): _service.enable_retries() self.test_get_replication_document_required_params() _service.disable_retries() self.test_get_replication_document_required_params() @responses.activate def test_get_replication_document_value_error(self): url = self.preprocess_url(_base_url + '/_replicator/testString') mock_response = '{"_attachments": {"mapKey": {"content_type": "content_type", "data": "VGhpcyBpcyBhbiBlbmNvZGVkIGJ5dGUgYXJyYXku", "digest": "digest", "encoded_length": 0, "encoding": "encoding", "follows": false, "length": 0, "revpos": 1, "stub": true}}, "_conflicts": ["conflicts"], "_deleted": false, "_deleted_conflicts": ["deleted_conflicts"], "_id": "id", "_local_seq": "local_seq", "_rev": "rev", "_revisions": {"ids": ["ids"], "start": 1}, "_revs_info": [{"rev": "rev", "status": "available"}], "cancel": true, "checkpoint_interval": 0, "connection_timeout": 0, "continuous": false, "create_target": false, "create_target_params": {"n": 1, "partitioned": false, "q": 1}, "doc_ids": ["doc_ids"], "filter": "filter", "http_connections": 1, "query_params": {"mapKey": "inner"}, "retries_per_request": 0, "selector": {"mapKey": "anyValue"}, "since_seq": "since_seq", "socket_options": "socket_options", "source": {"auth": {"basic": {"password": "password", "username": "username"}, "iam": {"api_key": "api_key"}}, "headers": {"mapKey": "inner"}, "url": "url"}, "source_proxy": "source_proxy", "target": {"auth": {"basic": {"password": "password", "username": "username"}, "iam": {"api_key": "api_key"}}, "headers": {"mapKey": "inner"}, "url": "url"}, "target_proxy": "target_proxy", "use_checkpoints": true, "user_ctx": {"db": "db", "name": "name", "roles": ["_reader"]}, "worker_batch_size": 1, "worker_processes": 1}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) doc_id = 'testString' req_param_dict = { "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_replication_document(**req_copy) def test_get_replication_document_value_error_with_retries(self): _service.enable_retries() self.test_get_replication_document_value_error() _service.disable_retries() self.test_get_replication_document_value_error() class TestPutReplicationDocument(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_put_replication_document_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/_replicator/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a ReplicationCreateTargetParameters model replication_create_target_parameters_model = {} replication_create_target_parameters_model['n'] = 1 replication_create_target_parameters_model['partitioned'] = False replication_create_target_parameters_model['q'] = 1 # Construct a dict representation of a ReplicationDatabaseAuthBasic model replication_database_auth_basic_model = {} replication_database_auth_basic_model['password'] = 'testString' replication_database_auth_basic_model['username'] = 'testString' # Construct a dict representation of a ReplicationDatabaseAuthIam model replication_database_auth_iam_model = {} replication_database_auth_iam_model['api_key'] = 'testString' # Construct a dict representation of a ReplicationDatabaseAuth model replication_database_auth_model = {} replication_database_auth_model['basic'] = replication_database_auth_basic_model replication_database_auth_model['iam'] = replication_database_auth_iam_model # Construct a dict representation of a ReplicationDatabase model replication_database_model = {} replication_database_model['auth'] = replication_database_auth_model replication_database_model['headers'] = {} replication_database_model['url'] = 'testString' # Construct a dict representation of a UserContext model user_context_model = {} user_context_model['db'] = 'testString' user_context_model['name'] = 'testString' user_context_model['roles'] = ['_reader'] # Construct a dict representation of a ReplicationDocument model replication_document_model = {} replication_document_model['_attachments'] = {} replication_document_model['_conflicts'] = ['testString'] replication_document_model['_deleted'] = True replication_document_model['_deleted_conflicts'] = ['testString'] replication_document_model['_id'] = 'testString' replication_document_model['_local_seq'] = 'testString' replication_document_model['_rev'] = 'testString' replication_document_model['_revisions'] = revisions_model replication_document_model['_revs_info'] = [document_revision_status_model] replication_document_model['cancel'] = True replication_document_model['checkpoint_interval'] = 0 replication_document_model['connection_timeout'] = 0 replication_document_model['continuous'] = False replication_document_model['create_target'] = False replication_document_model['create_target_params'] = replication_create_target_parameters_model replication_document_model['doc_ids'] = ['testString'] replication_document_model['filter'] = 'testString' replication_document_model['http_connections'] = 1 replication_document_model['query_params'] = {} replication_document_model['retries_per_request'] = 0 replication_document_model['selector'] = {} replication_document_model['since_seq'] = 'testString' replication_document_model['socket_options'] = 'testString' replication_document_model['source'] = replication_database_model replication_document_model['source_proxy'] = 'testString' replication_document_model['target'] = replication_database_model replication_document_model['target_proxy'] = 'testString' replication_document_model['use_checkpoints'] = True replication_document_model['user_ctx'] = user_context_model replication_document_model['worker_batch_size'] = 1 replication_document_model['worker_processes'] = 1 replication_document_model['foo'] = 'testString' # Set up parameter values doc_id = 'testString' replication_document = replication_document_model if_match = 'testString' batch = 'ok' new_edits = False rev = 'testString' # Invoke method response = _service.put_replication_document( doc_id, replication_document, if_match=if_match, batch=batch, new_edits=new_edits, rev=rev, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'batch={}'.format(batch) in query_string assert 'new_edits={}'.format('true' if new_edits else 'false') in query_string assert 'rev={}'.format(rev) in query_string # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body == replication_document def test_put_replication_document_all_params_with_retries(self): # Enable retries and run test_put_replication_document_all_params. _service.enable_retries() self.test_put_replication_document_all_params() # Disable retries and run test_put_replication_document_all_params. _service.disable_retries() self.test_put_replication_document_all_params() @responses.activate def test_put_replication_document_required_params(self): # Set up mock url = self.preprocess_url(_base_url + '/_replicator/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a ReplicationCreateTargetParameters model replication_create_target_parameters_model = {} replication_create_target_parameters_model['n'] = 1 replication_create_target_parameters_model['partitioned'] = False replication_create_target_parameters_model['q'] = 1 # Construct a dict representation of a ReplicationDatabaseAuthBasic model replication_database_auth_basic_model = {} replication_database_auth_basic_model['password'] = 'testString' replication_database_auth_basic_model['username'] = 'testString' # Construct a dict representation of a ReplicationDatabaseAuthIam model replication_database_auth_iam_model = {} replication_database_auth_iam_model['api_key'] = 'testString' # Construct a dict representation of a ReplicationDatabaseAuth model replication_database_auth_model = {} replication_database_auth_model['basic'] = replication_database_auth_basic_model replication_database_auth_model['iam'] = replication_database_auth_iam_model # Construct a dict representation of a ReplicationDatabase model replication_database_model = {} replication_database_model['auth'] = replication_database_auth_model replication_database_model['headers'] = {} replication_database_model['url'] = 'testString' # Construct a dict representation of a UserContext model user_context_model = {} user_context_model['db'] = 'testString' user_context_model['name'] = 'testString' user_context_model['roles'] = ['_reader'] # Construct a dict representation of a ReplicationDocument model replication_document_model = {} replication_document_model['_attachments'] = {} replication_document_model['_conflicts'] = ['testString'] replication_document_model['_deleted'] = True replication_document_model['_deleted_conflicts'] = ['testString'] replication_document_model['_id'] = 'testString' replication_document_model['_local_seq'] = 'testString' replication_document_model['_rev'] = 'testString' replication_document_model['_revisions'] = revisions_model replication_document_model['_revs_info'] = [document_revision_status_model] replication_document_model['cancel'] = True replication_document_model['checkpoint_interval'] = 0 replication_document_model['connection_timeout'] = 0 replication_document_model['continuous'] = False replication_document_model['create_target'] = False replication_document_model['create_target_params'] = replication_create_target_parameters_model replication_document_model['doc_ids'] = ['testString'] replication_document_model['filter'] = 'testString' replication_document_model['http_connections'] = 1 replication_document_model['query_params'] = {} replication_document_model['retries_per_request'] = 0 replication_document_model['selector'] = {} replication_document_model['since_seq'] = 'testString' replication_document_model['socket_options'] = 'testString' replication_document_model['source'] = replication_database_model replication_document_model['source_proxy'] = 'testString' replication_document_model['target'] = replication_database_model replication_document_model['target_proxy'] = 'testString' replication_document_model['use_checkpoints'] = True replication_document_model['user_ctx'] = user_context_model replication_document_model['worker_batch_size'] = 1 replication_document_model['worker_processes'] = 1 replication_document_model['foo'] = 'testString' # Set up parameter values doc_id = 'testString' replication_document = replication_document_model # Invoke method response = _service.put_replication_document( doc_id, replication_document, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # decompress gzip compressed request body responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body == replication_document def test_put_replication_document_required_params_with_retries(self): # Enable retries and run test_put_replication_document_required_params. _service.enable_retries() self.test_put_replication_document_required_params() # Disable retries and run test_put_replication_document_required_params. _service.disable_retries() self.test_put_replication_document_required_params() @responses.activate def test_put_replication_document_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/_replicator/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) # Construct a dict representation of a Attachment model attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True # Construct a dict representation of a Revisions model revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 # Construct a dict representation of a DocumentRevisionStatus model document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a dict representation of a ReplicationCreateTargetParameters model replication_create_target_parameters_model = {} replication_create_target_parameters_model['n'] = 1 replication_create_target_parameters_model['partitioned'] = False replication_create_target_parameters_model['q'] = 1 # Construct a dict representation of a ReplicationDatabaseAuthBasic model replication_database_auth_basic_model = {} replication_database_auth_basic_model['password'] = 'testString' replication_database_auth_basic_model['username'] = 'testString' # Construct a dict representation of a ReplicationDatabaseAuthIam model replication_database_auth_iam_model = {} replication_database_auth_iam_model['api_key'] = 'testString' # Construct a dict representation of a ReplicationDatabaseAuth model replication_database_auth_model = {} replication_database_auth_model['basic'] = replication_database_auth_basic_model replication_database_auth_model['iam'] = replication_database_auth_iam_model # Construct a dict representation of a ReplicationDatabase model replication_database_model = {} replication_database_model['auth'] = replication_database_auth_model replication_database_model['headers'] = {} replication_database_model['url'] = 'testString' # Construct a dict representation of a UserContext model user_context_model = {} user_context_model['db'] = 'testString' user_context_model['name'] = 'testString' user_context_model['roles'] = ['_reader'] # Construct a dict representation of a ReplicationDocument model replication_document_model = {} replication_document_model['_attachments'] = {} replication_document_model['_conflicts'] = ['testString'] replication_document_model['_deleted'] = True replication_document_model['_deleted_conflicts'] = ['testString'] replication_document_model['_id'] = 'testString' replication_document_model['_local_seq'] = 'testString' replication_document_model['_rev'] = 'testString' replication_document_model['_revisions'] = revisions_model replication_document_model['_revs_info'] = [document_revision_status_model] replication_document_model['cancel'] = True replication_document_model['checkpoint_interval'] = 0 replication_document_model['connection_timeout'] = 0 replication_document_model['continuous'] = False replication_document_model['create_target'] = False replication_document_model['create_target_params'] = replication_create_target_parameters_model replication_document_model['doc_ids'] = ['testString'] replication_document_model['filter'] = 'testString' replication_document_model['http_connections'] = 1 replication_document_model['query_params'] = {} replication_document_model['retries_per_request'] = 0 replication_document_model['selector'] = {} replication_document_model['since_seq'] = 'testString' replication_document_model['socket_options'] = 'testString' replication_document_model['source'] = replication_database_model replication_document_model['source_proxy'] = 'testString' replication_document_model['target'] = replication_database_model replication_document_model['target_proxy'] = 'testString' replication_document_model['use_checkpoints'] = True replication_document_model['user_ctx'] = user_context_model replication_document_model['worker_batch_size'] = 1 replication_document_model['worker_processes'] = 1 replication_document_model['foo'] = 'testString' # Set up parameter values doc_id = 'testString' replication_document = replication_document_model # Pass in all but one required param and check for a ValueError req_param_dict = { "doc_id": doc_id, "replication_document": replication_document, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.put_replication_document(**req_copy) def test_put_replication_document_value_error_with_retries(self): # Enable retries and run test_put_replication_document_value_error. _service.enable_retries() self.test_put_replication_document_value_error() # Disable retries and run test_put_replication_document_value_error. _service.disable_retries() self.test_put_replication_document_value_error() class TestGetSchedulerDocs(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_scheduler_docs_all_params(self): url = self.preprocess_url(_base_url + '/_scheduler/docs') mock_response = '{"total_rows": 0, "docs": [{"database": "database", "doc_id": "doc_id", "error_count": 0, "id": "id", "info": {"changes_pending": 0, "checkpointed_source_seq": "checkpointed_source_seq", "doc_write_failures": 0, "docs_read": 0, "docs_written": 0, "error": "error", "missing_revisions_found": 0, "revisions_checked": 0, "source_seq": "source_seq", "through_seq": "through_seq"}, "last_updated": "2019-01-01T12:00:00.000Z", "node": "node", "source": "source", "source_proxy": "source_proxy", "start_time": "2019-01-01T12:00:00.000Z", "state": "initializing", "target": "target", "target_proxy": "target_proxy"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) limit = 0 skip = 0 states = ['initializing'] response = _service.get_scheduler_docs( limit=limit, skip=skip, states=states, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'limit={}'.format(limit) in query_string assert 'skip={}'.format(skip) in query_string assert 'states={}'.format(','.join(states)) in query_string def test_get_scheduler_docs_all_params_with_retries(self): _service.enable_retries() self.test_get_scheduler_docs_all_params() _service.disable_retries() self.test_get_scheduler_docs_all_params() @responses.activate def test_get_scheduler_docs_required_params(self): url = self.preprocess_url(_base_url + '/_scheduler/docs') mock_response = '{"total_rows": 0, "docs": [{"database": "database", "doc_id": "doc_id", "error_count": 0, "id": "id", "info": {"changes_pending": 0, "checkpointed_source_seq": "checkpointed_source_seq", "doc_write_failures": 0, "docs_read": 0, "docs_written": 0, "error": "error", "missing_revisions_found": 0, "revisions_checked": 0, "source_seq": "source_seq", "through_seq": "through_seq"}, "last_updated": "2019-01-01T12:00:00.000Z", "node": "node", "source": "source", "source_proxy": "source_proxy", "start_time": "2019-01-01T12:00:00.000Z", "state": "initializing", "target": "target", "target_proxy": "target_proxy"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) response = _service.get_scheduler_docs() assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_scheduler_docs_required_params_with_retries(self): _service.enable_retries() self.test_get_scheduler_docs_required_params() _service.disable_retries() self.test_get_scheduler_docs_required_params() class TestGetSchedulerDocument(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_scheduler_document_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/_scheduler/docs/_replicator/testString') mock_response = '{"database": "database", "doc_id": "doc_id", "error_count": 0, "id": "id", "info": {"changes_pending": 0, "checkpointed_source_seq": "checkpointed_source_seq", "doc_write_failures": 0, "docs_read": 0, "docs_written": 0, "error": "error", "missing_revisions_found": 0, "revisions_checked": 0, "source_seq": "source_seq", "through_seq": "through_seq"}, "last_updated": "2019-01-01T12:00:00.000Z", "node": "node", "source": "source", "source_proxy": "source_proxy", "start_time": "2019-01-01T12:00:00.000Z", "state": "initializing", "target": "target", "target_proxy": "target_proxy"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values doc_id = 'testString' # Invoke method response = _service.get_scheduler_document( doc_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_scheduler_document_all_params_with_retries(self): # Enable retries and run test_get_scheduler_document_all_params. _service.enable_retries() self.test_get_scheduler_document_all_params() # Disable retries and run test_get_scheduler_document_all_params. _service.disable_retries() self.test_get_scheduler_document_all_params() @responses.activate def test_get_scheduler_document_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/_scheduler/docs/_replicator/testString') mock_response = '{"database": "database", "doc_id": "doc_id", "error_count": 0, "id": "id", "info": {"changes_pending": 0, "checkpointed_source_seq": "checkpointed_source_seq", "doc_write_failures": 0, "docs_read": 0, "docs_written": 0, "error": "error", "missing_revisions_found": 0, "revisions_checked": 0, "source_seq": "source_seq", "through_seq": "through_seq"}, "last_updated": "2019-01-01T12:00:00.000Z", "node": "node", "source": "source", "source_proxy": "source_proxy", "start_time": "2019-01-01T12:00:00.000Z", "state": "initializing", "target": "target", "target_proxy": "target_proxy"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_scheduler_document(**req_copy) def test_get_scheduler_document_value_error_with_retries(self): # Enable retries and run test_get_scheduler_document_value_error. _service.enable_retries() self.test_get_scheduler_document_value_error() # Disable retries and run test_get_scheduler_document_value_error. _service.disable_retries() self.test_get_scheduler_document_value_error() class TestGetSchedulerJobs(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_scheduler_jobs_all_params(self): url = self.preprocess_url(_base_url + '/_scheduler/jobs') mock_response = '{"total_rows": 0, "jobs": [{"database": "database", "doc_id": "doc_id", "history": [{"reason": "reason", "timestamp": "2019-01-01T12:00:00.000Z", "type": "type"}], "id": "id", "info": {"changes_pending": 0, "checkpointed_source_seq": "checkpointed_source_seq", "doc_write_failures": 0, "docs_read": 0, "docs_written": 0, "error": "error", "missing_revisions_found": 0, "revisions_checked": 0, "source_seq": "source_seq", "through_seq": "through_seq"}, "node": "node", "pid": "pid", "source": "source", "start_time": "2019-01-01T12:00:00.000Z", "target": "target", "user": "user"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) limit = 0 skip = 0 response = _service.get_scheduler_jobs( limit=limit, skip=skip, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'limit={}'.format(limit) in query_string assert 'skip={}'.format(skip) in query_string def test_get_scheduler_jobs_all_params_with_retries(self): _service.enable_retries() self.test_get_scheduler_jobs_all_params() _service.disable_retries() self.test_get_scheduler_jobs_all_params() @responses.activate def test_get_scheduler_jobs_required_params(self): url = self.preprocess_url(_base_url + '/_scheduler/jobs') mock_response = '{"total_rows": 0, "jobs": [{"database": "database", "doc_id": "doc_id", "history": [{"reason": "reason", "timestamp": "2019-01-01T12:00:00.000Z", "type": "type"}], "id": "id", "info": {"changes_pending": 0, "checkpointed_source_seq": "checkpointed_source_seq", "doc_write_failures": 0, "docs_read": 0, "docs_written": 0, "error": "error", "missing_revisions_found": 0, "revisions_checked": 0, "source_seq": "source_seq", "through_seq": "through_seq"}, "node": "node", "pid": "pid", "source": "source", "start_time": "2019-01-01T12:00:00.000Z", "target": "target", "user": "user"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) response = _service.get_scheduler_jobs() assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_scheduler_jobs_required_params_with_retries(self): _service.enable_retries() self.test_get_scheduler_jobs_required_params() _service.disable_retries() self.test_get_scheduler_jobs_required_params() class TestGetSchedulerJob(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_scheduler_job_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/_scheduler/jobs/testString') mock_response = '{"database": "database", "doc_id": "doc_id", "history": [{"reason": "reason", "timestamp": "2019-01-01T12:00:00.000Z", "type": "type"}], "id": "id", "info": {"changes_pending": 0, "checkpointed_source_seq": "checkpointed_source_seq", "doc_write_failures": 0, "docs_read": 0, "docs_written": 0, "error": "error", "missing_revisions_found": 0, "revisions_checked": 0, "source_seq": "source_seq", "through_seq": "through_seq"}, "node": "node", "pid": "pid", "source": "source", "start_time": "2019-01-01T12:00:00.000Z", "target": "target", "user": "user"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values job_id = 'testString' # Invoke method response = _service.get_scheduler_job( job_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_scheduler_job_all_params_with_retries(self): # Enable retries and run test_get_scheduler_job_all_params. _service.enable_retries() self.test_get_scheduler_job_all_params() # Disable retries and run test_get_scheduler_job_all_params. _service.disable_retries() self.test_get_scheduler_job_all_params() @responses.activate def test_get_scheduler_job_value_error(self): # Set up mock url = self.preprocess_url(_base_url + '/_scheduler/jobs/testString') mock_response = '{"database": "database", "doc_id": "doc_id", "history": [{"reason": "reason", "timestamp": "2019-01-01T12:00:00.000Z", "type": "type"}], "id": "id", "info": {"changes_pending": 0, "checkpointed_source_seq": "checkpointed_source_seq", "doc_write_failures": 0, "docs_read": 0, "docs_written": 0, "error": "error", "missing_revisions_found": 0, "revisions_checked": 0, "source_seq": "source_seq", "through_seq": "through_seq"}, "node": "node", "pid": "pid", "source": "source", "start_time": "2019-01-01T12:00:00.000Z", "target": "target", "user": "user"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values job_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "job_id": job_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_scheduler_job(**req_copy) def test_get_scheduler_job_value_error_with_retries(self): # Enable retries and run test_get_scheduler_job_value_error. _service.enable_retries() self.test_get_scheduler_job_value_error() # Disable retries and run test_get_scheduler_job_value_error. _service.disable_retries() self.test_get_scheduler_job_value_error() # endregion ############################################################################## # End of Service: Replication ############################################################################## ############################################################################## # Start of Service: Authentication ############################################################################## # region class TestNewInstance(): def test_new_instance(self): os.environ['TEST_SERVICE_AUTH_TYPE'] = 'noAuth' service = CloudantV1.new_instance( service_name='TEST_SERVICE', ) assert service is not None assert isinstance(service, CloudantV1) def test_new_instance_without_authenticator(self): with pytest.raises(ValueError, match='authenticator must be provided'): service = CloudantV1.new_instance( ) class TestGetSessionInformation(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_session_information_all_params(self): url = self.preprocess_url(_base_url + '/_session') mock_response = '{"ok": true, "info": {"authenticated": "authenticated", "authentication_db": "authentication_db", "authentication_handlers": ["authentication_handlers"]}, "userCtx": {"db": "db", "name": "name", "roles": ["_reader"]}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) response = _service.get_session_information() assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_session_information_all_params_with_retries(self): _service.enable_retries() self.test_get_session_information_all_params() _service.disable_retries() self.test_get_session_information_all_params() responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Set up parameter values db = 'testString' doc_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "db": db, "doc_id": doc_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_local_document(**req_copy) def test_get_local_document_value_error_with_retries(self): # Enable retries and run test_get_local_document_value_error. _service.enable_retries() self.test_get_local_document_value_error() # Disable retries and run test_get_local_document_value_error. _service.disable_retries() self.test_get_local_document_value_error() class TestPutLocalDocument(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_put_local_document_all_params(self): url = self.preprocess_url(_base_url + '/testString/_local/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'exampleid' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['brand'] = 'Foo' document_model['colours'] = '["red","green","black","blue"]' document_model['description'] = 'Slim Colourful Design Electronic Cooking Appliance for ...' document_model['image'] = 'assets/img/0gmsnghhew.jpg' document_model['keywords'] = '["Foo","Scales","Weight","Digital","Kitchen"]' document_model['name'] = 'Digital Kitchen Scales' document_model['price'] = '14.99' document_model['productid'] = '1000042' document_model['taxonomy'] = '["Home","Kitchen","Small Appliances"]' document_model['type'] = 'product' db = 'testString' doc_id = 'testString' document = document_model content_type = 'application/json' batch = 'ok' response = _service.put_local_document( db, doc_id, document, content_type=content_type, batch=batch, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 201 query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'batch={}'.format(batch) in query_string responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) def test_put_local_document_all_params_with_retries(self): _service.enable_retries() self.test_put_local_document_all_params() _service.disable_retries() self.test_put_local_document_all_params() @responses.activate def test_put_local_document_required_params(self): url = self.preprocess_url(_base_url + '/testString/_local/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'exampleid' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['brand'] = 'Foo' document_model['colours'] = '["red","green","black","blue"]' document_model['description'] = 'Slim Colourful Design Electronic Cooking Appliance for ...' document_model['image'] = 'assets/img/0gmsnghhew.jpg' document_model['keywords'] = '["Foo","Scales","Weight","Digital","Kitchen"]' document_model['name'] = 'Digital Kitchen Scales' document_model['price'] = '14.99' document_model['productid'] = '1000042' document_model['taxonomy'] = '["Home","Kitchen","Small Appliances"]' document_model['type'] = 'product' db = 'testString' doc_id = 'testString' document = document_model response = _service.put_local_document( db, doc_id, document, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 201 responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) def test_put_local_document_required_params_with_retries(self): _service.enable_retries() self.test_put_local_document_required_params() _service.disable_retries() self.test_put_local_document_required_params() @responses.activate def test_put_local_document_value_error(self): url = self.preprocess_url(_base_url + '/testString/_local/testString') mock_response = '{"id": "id", "rev": "rev", "ok": true, "caused_by": "caused_by", "error": "error", "reason": "reason"}' responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=201) attachment_model = {} attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'exampleid' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['brand'] = 'Foo' document_model['colours'] = '["red","green","black","blue"]' document_model['description'] = 'Slim Colourful Design Electronic Cooking Appliance for ...' document_model['image'] = 'assets/img/0gmsnghhew.jpg' document_model['keywords'] = '["Foo","Scales","Weight","Digital","Kitchen"]' document_model['name'] = 'Digital Kitchen Scales' document_model['price'] = '14.99' document_model['productid'] = '1000042' document_model['taxonomy'] = '["Home","Kitchen","Small Appliances"]' document_model['type'] = 'product' db = 'testString' doc_id = 'testString' document = document_model req_param_dict = { "db": db, "doc_id": doc_id, "document": document, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.put_local_document(**req_copy) def test_put_local_document_value_error_with_retries(self): _service.enable_retries() self.test_put_local_document_value_error() _service.disable_retries() self.test_put_local_document_value_error() nses.calls) == 1 assert response.status_code == 200 def test_get_active_tasks_all_params_with_retries(self): # Enable retries and run test_get_active_tasks_all_params. _service.enable_retries() self.test_get_active_tasks_all_params() # Disable retries and run test_get_active_tasks_all_params. _service.disable_retries() self.test_get_active_tasks_all_params() class TestGetUpInformation(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_up_information_all_params(self): url = self.preprocess_url(_base_url + '/_up') mock_response = '{"seeds": {"anyKey": "anyValue"}, "status": "maintenance_mode"}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) response = _service.get_up_information() assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_up_information_all_params_with_retries(self): _service.enable_retries() self.test_get_up_information_all_params() _service.disable_retries() self.test_get_up_information_all_params() class TestGetActivityTrackerEvents(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_activity_tracker_events_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/_api/v2/user/activity_tracker/events') mock_response = '{"types": ["management"]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Invoke method response = _service.get_activity_tracker_events() # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_activity_tracker_events_all_params_with_retries(self): # Enable retries and run test_get_activity_tracker_events_all_params. _service.enable_retries() self.test_get_activity_tracker_events_all_params() # Disable retries and run test_get_activity_tracker_events_all_params. _service.disable_retries() self.test_get_activity_tracker_events_all_params() class TestPostActivityTrackerEvents(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_post_activity_tracker_events_all_params(self): url = self.preprocess_url(_base_url + '/_api/v2/user/activity_tracker/events') mock_response = '{"ok": true}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) types = ['management'] response = _service.post_activity_tracker_events( types, headers={} ) assert len(responses.calls) == 1 assert response.status_code == 200 responses.calls[0].request.body = gzip.decompress(responses.calls[0].request.body) req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['types'] == ['management'] def test_post_activity_tracker_events_all_params_with_retries(self): _service.enable_retries() self.test_post_activity_tracker_events_all_params() _service.disable_retries() self.test_post_activity_tracker_events_all_params() @responses.activate def test_post_activity_tracker_events_value_error(self): url = self.preprocess_url(_base_url + '/_api/v2/user/activity_tracker/events') mock_response = '{"ok": true}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) types = ['management'] req_param_dict = { "types": types, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.post_activity_tracker_events(**req_copy) def test_post_activity_tracker_events_value_error_with_retries(self): _service.enable_retries() self.test_post_activity_tracker_events_value_error() _service.disable_retries() self.test_post_activity_tracker_events_value_error() class TestGetCurrentThroughputInformation(): def preprocess_url(self, request_url: str): request_url = urllib.parse.unquote(request_url) request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: return re.compile(request_url.rstrip('/') + '/+') @responses.activate def test_get_current_throughput_information_all_params(self): # Set up mock url = self.preprocess_url(_base_url + '/_api/v2/user/current/throughput') mock_response = '{"throughput": {"query": 0, "read": 0, "write": 0}}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) # Invoke method response = _service.get_current_throughput_information() # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 def test_get_current_throughput_information_all_params_with_retries(self): # Enable retries and run test_get_current_throughput_information_all_params. _service.enable_retries() self.test_get_current_throughput_information_all_params() # Disable retries and run test_get_current_throughput_information_all_params. _service.disable_retries() self.test_get_current_throughput_information_all_params() # endregion ############################################################################## # End of Service: Monitoring ############################################################################## ############################################################################## # Start of Model Tests ############################################################################## # region class TestModel_ActiveTask(): def test_active_task_serialization(self): # Construct a json representation of a ActiveTask model active_task_model_json = {} active_task_model_json['changes_done'] = 0 active_task_model_json['database'] = 'testString' active_task_model_json['node'] = 'testString' active_task_model_json['pid'] = 'testString' active_task_model_json['progress'] = 0 active_task_model_json['started_on'] = 0 active_task_model_json['status'] = 'testString' active_task_model_json['task'] = 'testString' active_task_model_json['total_changes'] = 0 active_task_model_json['type'] = 'testString' active_task_model_json['updated_on'] = 0 # Construct a model instance of ActiveTask by calling from_dict on the json representation active_task_model = ActiveTask.from_dict(active_task_model_json) assert active_task_model != False # Construct a model instance of ActiveTask by calling from_dict on the json representation active_task_model_dict = ActiveTask.from_dict(active_task_model_json).__dict__ active_task_model2 = ActiveTask(**active_task_model_dict) # Verify the model instances are equivalent assert active_task_model == active_task_model2 # Convert model instance back to dict and verify no loss of data active_task_model_json2 = active_task_model.to_dict() assert active_task_model_json2 == active_task_model_json class TestModel_ActivityTrackerEvents(): def test_activity_tracker_events_serialization(self): # Construct a json representation of a ActivityTrackerEvents model activity_tracker_events_model_json = {} activity_tracker_events_model_json['types'] = ['management'] # Construct a model instance of ActivityTrackerEvents by calling from_dict on the json representation activity_tracker_events_model = ActivityTrackerEvents.from_dict(activity_tracker_events_model_json) assert activity_tracker_events_model != False # Construct a model instance of ActivityTrackerEvents by calling from_dict on the json representation activity_tracker_events_model_dict = ActivityTrackerEvents.from_dict(activity_tracker_events_model_json).__dict__ activity_tracker_events_model2 = ActivityTrackerEvents(**activity_tracker_events_model_dict) # Verify the model instances are equivalent assert activity_tracker_events_model == activity_tracker_events_model2 # Convert model instance back to dict and verify no loss of data activity_tracker_events_model_json2 = activity_tracker_events_model.to_dict() assert activity_tracker_events_model_json2 == activity_tracker_events_model_json class TestModel_AllDocsQueriesResult(): def test_all_docs_queries_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' docs_result_row_value_model = {} # DocsResultRowValue docs_result_row_value_model['rev'] = 'testString' docs_result_row_model = {} # DocsResultRow docs_result_row_model['caused_by'] = 'testString' docs_result_row_model['error'] = 'testString' docs_result_row_model['reason'] = 'testString' docs_result_row_model['doc'] = document_model docs_result_row_model['id'] = 'testString' docs_result_row_model['key'] = 'testString' docs_result_row_model['value'] = docs_result_row_value_model all_docs_result_model = {} # AllDocsResult all_docs_result_model['total_rows'] = 0 all_docs_result_model['rows'] = [docs_result_row_model] all_docs_result_model['update_seq'] = 'testString' # Construct a json representation of a AllDocsQueriesResult model all_docs_queries_result_model_json = {} all_docs_queries_result_model_json['results'] = [all_docs_result_model] # Construct a model instance of AllDocsQueriesResult by calling from_dict on the json representation all_docs_queries_result_model = AllDocsQueriesResult.from_dict(all_docs_queries_result_model_json) assert all_docs_queries_result_model != False # Construct a model instance of AllDocsQueriesResult by calling from_dict on the json representation all_docs_queries_result_model_dict = AllDocsQueriesResult.from_dict(all_docs_queries_result_model_json).__dict__ all_docs_queries_result_model2 = AllDocsQueriesResult(**all_docs_queries_result_model_dict) # Verify the model instances are equivalent assert all_docs_queries_result_model == all_docs_queries_result_model2 # Convert model instance back to dict and verify no loss of data all_docs_queries_result_model_json2 = all_docs_queries_result_model.to_dict() assert all_docs_queries_result_model_json2 == all_docs_queries_result_model_json class TestModel_AllDocsQuery(): def test_all_docs_query_serialization(self): # Construct a json representation of a AllDocsQuery model all_docs_query_model_json = {} all_docs_query_model_json['att_encoding_info'] = False all_docs_query_model_json['attachments'] = False all_docs_query_model_json['conflicts'] = False all_docs_query_model_json['descending'] = False all_docs_query_model_json['include_docs'] = False all_docs_query_model_json['inclusive_end'] = True all_docs_query_model_json['limit'] = 0 all_docs_query_model_json['skip'] = 0 all_docs_query_model_json['update_seq'] = False all_docs_query_model_json['endkey'] = 'testString' all_docs_query_model_json['key'] = 'testString' all_docs_query_model_json['keys'] = ['testString'] all_docs_query_model_json['startkey'] = 'testString' # Construct a model instance of AllDocsQuery by calling from_dict on the json representation all_docs_query_model = AllDocsQuery.from_dict(all_docs_query_model_json) assert all_docs_query_model != False # Construct a model instance of AllDocsQuery by calling from_dict on the json representation all_docs_query_model_dict = AllDocsQuery.from_dict(all_docs_query_model_json).__dict__ all_docs_query_model2 = AllDocsQuery(**all_docs_query_model_dict) # Verify the model instances are equivalent assert all_docs_query_model == all_docs_query_model2 # Convert model instance back to dict and verify no loss of data all_docs_query_model_json2 = all_docs_query_model.to_dict() assert all_docs_query_model_json2 == all_docs_query_model_json class TestModel_AllDocsResult(): def test_all_docs_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' docs_result_row_value_model = {} # DocsResultRowValue docs_result_row_value_model['rev'] = 'testString' docs_result_row_model = {} # DocsResultRow docs_result_row_model['caused_by'] = 'testString' docs_result_row_model['error'] = 'testString' docs_result_row_model['reason'] = 'testString' docs_result_row_model['doc'] = document_model docs_result_row_model['id'] = 'testString' docs_result_row_model['key'] = 'testString' docs_result_row_model['value'] = docs_result_row_value_model # Construct a json representation of a AllDocsResult model all_docs_result_model_json = {} all_docs_result_model_json['total_rows'] = 0 all_docs_result_model_json['rows'] = [docs_result_row_model] all_docs_result_model_json['update_seq'] = 'testString' # Construct a model instance of AllDocsResult by calling from_dict on the json representation all_docs_result_model = AllDocsResult.from_dict(all_docs_result_model_json) assert all_docs_result_model != False # Construct a model instance of AllDocsResult by calling from_dict on the json representation all_docs_result_model_dict = AllDocsResult.from_dict(all_docs_result_model_json).__dict__ all_docs_result_model2 = AllDocsResult(**all_docs_result_model_dict) # Verify the model instances are equivalent assert all_docs_result_model == all_docs_result_model2 # Convert model instance back to dict and verify no loss of data all_docs_result_model_json2 = all_docs_result_model.to_dict() assert all_docs_result_model_json2 == all_docs_result_model_json class TestModel_Analyzer(): def test_analyzer_serialization(self): # Construct a json representation of a Analyzer model analyzer_model_json = {} analyzer_model_json['name'] = 'classic' analyzer_model_json['stopwords'] = ['testString'] # Construct a model instance of Analyzer by calling from_dict on the json representation analyzer_model = Analyzer.from_dict(analyzer_model_json) assert analyzer_model != False # Construct a model instance of Analyzer by calling from_dict on the json representation analyzer_model_dict = Analyzer.from_dict(analyzer_model_json).__dict__ analyzer_model2 = Analyzer(**analyzer_model_dict) # Verify the model instances are equivalent assert analyzer_model == analyzer_model2 # Convert model instance back to dict and verify no loss of data analyzer_model_json2 = analyzer_model.to_dict() assert analyzer_model_json2 == analyzer_model_json class TestModel_AnalyzerConfiguration(): def test_analyzer_configuration_serialization(self): # Construct dict forms of any model objects needed in order to build this model. analyzer_model = {} # Analyzer analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] # Construct a json representation of a AnalyzerConfiguration model analyzer_configuration_model_json = {} analyzer_configuration_model_json['name'] = 'classic' analyzer_configuration_model_json['stopwords'] = ['testString'] analyzer_configuration_model_json['fields'] = {} # Construct a model instance of AnalyzerConfiguration by calling from_dict on the json representation analyzer_configuration_model = AnalyzerConfiguration.from_dict(analyzer_configuration_model_json) assert analyzer_configuration_model != False # Construct a model instance of AnalyzerConfiguration by calling from_dict on the json representation analyzer_configuration_model_dict = AnalyzerConfiguration.from_dict(analyzer_configuration_model_json).__dict__ analyzer_configuration_model2 = AnalyzerConfiguration(**analyzer_configuration_model_dict) # Verify the model instances are equivalent assert analyzer_configuration_model == analyzer_configuration_model2 # Convert model instance back to dict and verify no loss of data analyzer_configuration_model_json2 = analyzer_configuration_model.to_dict() assert analyzer_configuration_model_json2 == analyzer_configuration_model_json class TestModel_ApiKeysResult(): def test_api_keys_result_serialization(self): # Construct a json representation of a ApiKeysResult model api_keys_result_model_json = {} api_keys_result_model_json['ok'] = True api_keys_result_model_json['key'] = 'testString' api_keys_result_model_json['password'] = 'testString' # Construct a model instance of ApiKeysResult by calling from_dict on the json representation api_keys_result_model = ApiKeysResult.from_dict(api_keys_result_model_json) assert api_keys_result_model != False # Construct a model instance of ApiKeysResult by calling from_dict on the json representation api_keys_result_model_dict = ApiKeysResult.from_dict(api_keys_result_model_json).__dict__ api_keys_result_model2 = ApiKeysResult(**api_keys_result_model_dict) # Verify the model instances are equivalent assert api_keys_result_model == api_keys_result_model2 # Convert model instance back to dict and verify no loss of data api_keys_result_model_json2 = api_keys_result_model.to_dict() assert api_keys_result_model_json2 == api_keys_result_model_json class TestModel_Attachment(): def test_attachment_serialization(self): # Construct a json representation of a Attachment model attachment_model_json = {} attachment_model_json['content_type'] = 'testString' attachment_model_json['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model_json['digest'] = 'testString' attachment_model_json['encoded_length'] = 0 attachment_model_json['encoding'] = 'testString' attachment_model_json['follows'] = True attachment_model_json['length'] = 0 attachment_model_json['revpos'] = 1 attachment_model_json['stub'] = True # Construct a model instance of Attachment by calling from_dict on the json representation attachment_model = Attachment.from_dict(attachment_model_json) assert attachment_model != False # Construct a model instance of Attachment by calling from_dict on the json representation attachment_model_dict = Attachment.from_dict(attachment_model_json).__dict__ attachment_model2 = Attachment(**attachment_model_dict) # Verify the model instances are equivalent assert attachment_model == attachment_model2 # Convert model instance back to dict and verify no loss of data attachment_model_json2 = attachment_model.to_dict() assert attachment_model_json2 == attachment_model_json class TestModel_BulkDocs(): def test_bulk_docs_serialization(self): # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' # Construct a json representation of a BulkDocs model bulk_docs_model_json = {} bulk_docs_model_json['docs'] = [document_model] bulk_docs_model_json['new_edits'] = True # Construct a model instance of BulkDocs by calling from_dict on the json representation bulk_docs_model = BulkDocs.from_dict(bulk_docs_model_json) assert bulk_docs_model != False # Construct a model instance of BulkDocs by calling from_dict on the json representation bulk_docs_model_dict = BulkDocs.from_dict(bulk_docs_model_json).__dict__ bulk_docs_model2 = BulkDocs(**bulk_docs_model_dict) # Verify the model instances are equivalent assert bulk_docs_model == bulk_docs_model2 # Convert model instance back to dict and verify no loss of data bulk_docs_model_json2 = bulk_docs_model.to_dict() assert bulk_docs_model_json2 == bulk_docs_model_json class TestModel_BulkGetQueryDocument(): def test_bulk_get_query_document_serialization(self): # Construct a json representation of a BulkGetQueryDocument model bulk_get_query_document_model_json = {} bulk_get_query_document_model_json['atts_since'] = ['1-99b02e08da151943c2dcb40090160bb8'] bulk_get_query_document_model_json['id'] = 'testString' bulk_get_query_document_model_json['rev'] = 'testString' # Construct a model instance of BulkGetQueryDocument by calling from_dict on the json representation bulk_get_query_document_model = BulkGetQueryDocument.from_dict(bulk_get_query_document_model_json) assert bulk_get_query_document_model != False # Construct a model instance of BulkGetQueryDocument by calling from_dict on the json representation bulk_get_query_document_model_dict = BulkGetQueryDocument.from_dict(bulk_get_query_document_model_json).__dict__ bulk_get_query_document_model2 = BulkGetQueryDocument(**bulk_get_query_document_model_dict) # Verify the model instances are equivalent assert bulk_get_query_document_model == bulk_get_query_document_model2 # Convert model instance back to dict and verify no loss of data bulk_get_query_document_model_json2 = bulk_get_query_document_model.to_dict() assert bulk_get_query_document_model_json2 == bulk_get_query_document_model_json class TestModel_BulkGetResult(): def test_bulk_get_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. document_result_model = {} # DocumentResult document_result_model['id'] = 'testString' document_result_model['rev'] = 'testString' document_result_model['ok'] = True document_result_model['caused_by'] = 'testString' document_result_model['error'] = 'testString' document_result_model['reason'] = 'testString' attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' bulk_get_result_document_model = {} # BulkGetResultDocument bulk_get_result_document_model['error'] = document_result_model bulk_get_result_document_model['ok'] = document_model bulk_get_result_item_model = {} # BulkGetResultItem bulk_get_result_item_model['docs'] = [bulk_get_result_document_model] bulk_get_result_item_model['id'] = 'testString' # Construct a json representation of a BulkGetResult model bulk_get_result_model_json = {} bulk_get_result_model_json['results'] = [bulk_get_result_item_model] # Construct a model instance of BulkGetResult by calling from_dict on the json representation bulk_get_result_model = BulkGetResult.from_dict(bulk_get_result_model_json) assert bulk_get_result_model != False # Construct a model instance of BulkGetResult by calling from_dict on the json representation bulk_get_result_model_dict = BulkGetResult.from_dict(bulk_get_result_model_json).__dict__ bulk_get_result_model2 = BulkGetResult(**bulk_get_result_model_dict) # Verify the model instances are equivalent assert bulk_get_result_model == bulk_get_result_model2 # Convert model instance back to dict and verify no loss of data bulk_get_result_model_json2 = bulk_get_result_model.to_dict() assert bulk_get_result_model_json2 == bulk_get_result_model_json class TestModel_BulkGetResultDocument(): def test_bulk_get_result_document_serialization(self): # Construct dict forms of any model objects needed in order to build this model. document_result_model = {} # DocumentResult document_result_model['id'] = 'testString' document_result_model['rev'] = 'testString' document_result_model['ok'] = True document_result_model['caused_by'] = 'testString' document_result_model['error'] = 'testString' document_result_model['reason'] = 'testString' attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' # Construct a json representation of a BulkGetResultDocument model bulk_get_result_document_model_json = {} bulk_get_result_document_model_json['error'] = document_result_model bulk_get_result_document_model_json['ok'] = document_model # Construct a model instance of BulkGetResultDocument by calling from_dict on the json representation bulk_get_result_document_model = BulkGetResultDocument.from_dict(bulk_get_result_document_model_json) assert bulk_get_result_document_model != False # Construct a model instance of BulkGetResultDocument by calling from_dict on the json representation bulk_get_result_document_model_dict = BulkGetResultDocument.from_dict(bulk_get_result_document_model_json).__dict__ bulk_get_result_document_model2 = BulkGetResultDocument(**bulk_get_result_document_model_dict) # Verify the model instances are equivalent assert bulk_get_result_document_model == bulk_get_result_document_model2 # Convert model instance back to dict and verify no loss of data bulk_get_result_document_model_json2 = bulk_get_result_document_model.to_dict() assert bulk_get_result_document_model_json2 == bulk_get_result_document_model_json class TestModel_BulkGetResultItem(): def test_bulk_get_result_item_serialization(self): # Construct dict forms of any model objects needed in order to build this model. document_result_model = {} # DocumentResult document_result_model['id'] = 'testString' document_result_model['rev'] = 'testString' document_result_model['ok'] = True document_result_model['caused_by'] = 'testString' document_result_model['error'] = 'testString' document_result_model['reason'] = 'testString' attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' bulk_get_result_document_model = {} # BulkGetResultDocument bulk_get_result_document_model['error'] = document_result_model bulk_get_result_document_model['ok'] = document_model # Construct a json representation of a BulkGetResultItem model bulk_get_result_item_model_json = {} bulk_get_result_item_model_json['docs'] = [bulk_get_result_document_model] bulk_get_result_item_model_json['id'] = 'testString' # Construct a model instance of BulkGetResultItem by calling from_dict on the json representation bulk_get_result_item_model = BulkGetResultItem.from_dict(bulk_get_result_item_model_json) assert bulk_get_result_item_model != False # Construct a model instance of BulkGetResultItem by calling from_dict on the json representation bulk_get_result_item_model_dict = BulkGetResultItem.from_dict(bulk_get_result_item_model_json).__dict__ bulk_get_result_item_model2 = BulkGetResultItem(**bulk_get_result_item_model_dict) # Verify the model instances are equivalent assert bulk_get_result_item_model == bulk_get_result_item_model2 # Convert model instance back to dict and verify no loss of data bulk_get_result_item_model_json2 = bulk_get_result_item_model.to_dict() assert bulk_get_result_item_model_json2 == bulk_get_result_item_model_json class TestModel_CapacityThroughputInformation(): def test_capacity_throughput_information_serialization(self): # Construct dict forms of any model objects needed in order to build this model. throughput_information_model = {} # ThroughputInformation throughput_information_model['blocks'] = 0 throughput_information_model['query'] = 0 throughput_information_model['read'] = 0 throughput_information_model['write'] = 0 capacity_throughput_information_current_model = {} # CapacityThroughputInformationCurrent capacity_throughput_information_current_model['throughput'] = throughput_information_model capacity_throughput_information_target_model = {} # CapacityThroughputInformationTarget capacity_throughput_information_target_model['throughput'] = throughput_information_model # Construct a json representation of a CapacityThroughputInformation model capacity_throughput_information_model_json = {} capacity_throughput_information_model_json['current'] = capacity_throughput_information_current_model capacity_throughput_information_model_json['target'] = capacity_throughput_information_target_model # Construct a model instance of CapacityThroughputInformation by calling from_dict on the json representation capacity_throughput_information_model = CapacityThroughputInformation.from_dict(capacity_throughput_information_model_json) assert capacity_throughput_information_model != False # Construct a model instance of CapacityThroughputInformation by calling from_dict on the json representation capacity_throughput_information_model_dict = CapacityThroughputInformation.from_dict(capacity_throughput_information_model_json).__dict__ capacity_throughput_information_model2 = CapacityThroughputInformation(**capacity_throughput_information_model_dict) # Verify the model instances are equivalent assert capacity_throughput_information_model == capacity_throughput_information_model2 # Convert model instance back to dict and verify no loss of data capacity_throughput_information_model_json2 = capacity_throughput_information_model.to_dict() assert capacity_throughput_information_model_json2 == capacity_throughput_information_model_json class TestModel_CapacityThroughputInformationCurrent(): def test_capacity_throughput_information_current_serialization(self): # Construct dict forms of any model objects needed in order to build this model. throughput_information_model = {} # ThroughputInformation throughput_information_model['blocks'] = 0 throughput_information_model['query'] = 0 throughput_information_model['read'] = 0 throughput_information_model['write'] = 0 # Construct a json representation of a CapacityThroughputInformationCurrent model capacity_throughput_information_current_model_json = {} capacity_throughput_information_current_model_json['throughput'] = throughput_information_model # Construct a model instance of CapacityThroughputInformationCurrent by calling from_dict on the json representation capacity_throughput_information_current_model = CapacityThroughputInformationCurrent.from_dict(capacity_throughput_information_current_model_json) assert capacity_throughput_information_current_model != False # Construct a model instance of CapacityThroughputInformationCurrent by calling from_dict on the json representation capacity_throughput_information_current_model_dict = CapacityThroughputInformationCurrent.from_dict(capacity_throughput_information_current_model_json).__dict__ capacity_throughput_information_current_model2 = CapacityThroughputInformationCurrent(**capacity_throughput_information_current_model_dict) # Verify the model instances are equivalent assert capacity_throughput_information_current_model == capacity_throughput_information_current_model2 # Convert model instance back to dict and verify no loss of data capacity_throughput_information_current_model_json2 = capacity_throughput_information_current_model.to_dict() assert capacity_throughput_information_current_model_json2 == capacity_throughput_information_current_model_json class TestModel_CapacityThroughputInformationTarget(): def test_capacity_throughput_information_target_serialization(self): # Construct dict forms of any model objects needed in order to build this model. throughput_information_model = {} # ThroughputInformation throughput_information_model['blocks'] = 0 throughput_information_model['query'] = 0 throughput_information_model['read'] = 0 throughput_information_model['write'] = 0 # Construct a json representation of a CapacityThroughputInformationTarget model capacity_throughput_information_target_model_json = {} capacity_throughput_information_target_model_json['throughput'] = throughput_information_model # Construct a model instance of CapacityThroughputInformationTarget by calling from_dict on the json representation capacity_throughput_information_target_model = CapacityThroughputInformationTarget.from_dict(capacity_throughput_information_target_model_json) assert capacity_throughput_information_target_model != False # Construct a model instance of CapacityThroughputInformationTarget by calling from_dict on the json representation capacity_throughput_information_target_model_dict = CapacityThroughputInformationTarget.from_dict(capacity_throughput_information_target_model_json).__dict__ capacity_throughput_information_target_model2 = CapacityThroughputInformationTarget(**capacity_throughput_information_target_model_dict) # Verify the model instances are equivalent assert capacity_throughput_information_target_model == capacity_throughput_information_target_model2 # Convert model instance back to dict and verify no loss of data capacity_throughput_information_target_model_json2 = capacity_throughput_information_target_model.to_dict() assert capacity_throughput_information_target_model_json2 == capacity_throughput_information_target_model_json class TestModel_Change(): def test_change_serialization(self): # Construct a json representation of a Change model change_model_json = {} change_model_json['rev'] = 'testString' # Construct a model instance of Change by calling from_dict on the json representation change_model = Change.from_dict(change_model_json) assert change_model != False # Construct a model instance of Change by calling from_dict on the json representation change_model_dict = Change.from_dict(change_model_json).__dict__ change_model2 = Change(**change_model_dict) # Verify the model instances are equivalent assert change_model == change_model2 # Convert model instance back to dict and verify no loss of data change_model_json2 = change_model.to_dict() assert change_model_json2 == change_model_json class TestModel_ChangesResult(): def test_changes_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. change_model = {} # Change change_model['rev'] = 'testString' attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' changes_result_item_model = {} # ChangesResultItem changes_result_item_model['changes'] = [change_model] changes_result_item_model['deleted'] = True changes_result_item_model['doc'] = document_model changes_result_item_model['id'] = 'testString' changes_result_item_model['seq'] = 'testString' # Construct a json representation of a ChangesResult model changes_result_model_json = {} changes_result_model_json['last_seq'] = 'testString' changes_result_model_json['pending'] = 26 changes_result_model_json['results'] = [changes_result_item_model] # Construct a model instance of ChangesResult by calling from_dict on the json representation changes_result_model = ChangesResult.from_dict(changes_result_model_json) assert changes_result_model != False # Construct a model instance of ChangesResult by calling from_dict on the json representation changes_result_model_dict = ChangesResult.from_dict(changes_result_model_json).__dict__ changes_result_model2 = ChangesResult(**changes_result_model_dict) # Verify the model instances are equivalent assert changes_result_model == changes_result_model2 # Convert model instance back to dict and verify no loss of data changes_result_model_json2 = changes_result_model.to_dict() assert changes_result_model_json2 == changes_result_model_json class TestModel_ChangesResultItem(): def test_changes_result_item_serialization(self): # Construct dict forms of any model objects needed in order to build this model. change_model = {} # Change change_model['rev'] = 'testString' attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' # Construct a json representation of a ChangesResultItem model changes_result_item_model_json = {} changes_result_item_model_json['changes'] = [change_model] changes_result_item_model_json['deleted'] = True changes_result_item_model_json['doc'] = document_model changes_result_item_model_json['id'] = 'testString' changes_result_item_model_json['seq'] = 'testString' # Construct a model instance of ChangesResultItem by calling from_dict on the json representation changes_result_item_model = ChangesResultItem.from_dict(changes_result_item_model_json) assert changes_result_item_model != False # Construct a model instance of ChangesResultItem by calling from_dict on the json representation changes_result_item_model_dict = ChangesResultItem.from_dict(changes_result_item_model_json).__dict__ changes_result_item_model2 = ChangesResultItem(**changes_result_item_model_dict) # Verify the model instances are equivalent assert changes_result_item_model == changes_result_item_model2 # Convert model instance back to dict and verify no loss of data changes_result_item_model_json2 = changes_result_item_model.to_dict() assert changes_result_item_model_json2 == changes_result_item_model_json class TestModel_ContentInformationSizes(): def test_content_information_sizes_serialization(self): # Construct a json representation of a ContentInformationSizes model content_information_sizes_model_json = {} content_information_sizes_model_json['active'] = 26 content_information_sizes_model_json['external'] = 26 content_information_sizes_model_json['file'] = 26 # Construct a model instance of ContentInformationSizes by calling from_dict on the json representation content_information_sizes_model = ContentInformationSizes.from_dict(content_information_sizes_model_json) assert content_information_sizes_model != False # Construct a model instance of ContentInformationSizes by calling from_dict on the json representation content_information_sizes_model_dict = ContentInformationSizes.from_dict(content_information_sizes_model_json).__dict__ content_information_sizes_model2 = ContentInformationSizes(**content_information_sizes_model_dict) # Verify the model instances are equivalent assert content_information_sizes_model == content_information_sizes_model2 # Convert model instance back to dict and verify no loss of data content_information_sizes_model_json2 = content_information_sizes_model.to_dict() assert content_information_sizes_model_json2 == content_information_sizes_model_json class TestModel_CorsInformation(): def test_cors_information_serialization(self): # Construct a json representation of a CorsInformation model cors_information_model_json = {} cors_information_model_json['allow_credentials'] = True cors_information_model_json['enable_cors'] = True cors_information_model_json['origins'] = ['testString'] # Construct a model instance of CorsInformation by calling from_dict on the json representation cors_information_model = CorsInformation.from_dict(cors_information_model_json) assert cors_information_model != False # Construct a model instance of CorsInformation by calling from_dict on the json representation cors_information_model_dict = CorsInformation.from_dict(cors_information_model_json).__dict__ cors_information_model2 = CorsInformation(**cors_information_model_dict) # Verify the model instances are equivalent assert cors_information_model == cors_information_model2 # Convert model instance back to dict and verify no loss of data cors_information_model_json2 = cors_information_model.to_dict() assert cors_information_model_json2 == cors_information_model_json class TestModel_CurrentThroughputInformation(): def test_current_throughput_information_serialization(self): # Construct dict forms of any model objects needed in order to build this model. current_throughput_information_throughput_model = {} # CurrentThroughputInformationThroughput current_throughput_information_throughput_model['query'] = 0 current_throughput_information_throughput_model['read'] = 0 current_throughput_information_throughput_model['write'] = 0 # Construct a json representation of a CurrentThroughputInformation model current_throughput_information_model_json = {} current_throughput_information_model_json['throughput'] = current_throughput_information_throughput_model # Construct a model instance of CurrentThroughputInformation by calling from_dict on the json representation current_throughput_information_model = CurrentThroughputInformation.from_dict(current_throughput_information_model_json) assert current_throughput_information_model != False # Construct a model instance of CurrentThroughputInformation by calling from_dict on the json representation current_throughput_information_model_dict = CurrentThroughputInformation.from_dict(current_throughput_information_model_json).__dict__ current_throughput_information_model2 = CurrentThroughputInformation(**current_throughput_information_model_dict) # Verify the model instances are equivalent assert current_throughput_information_model == current_throughput_information_model2 # Convert model instance back to dict and verify no loss of data current_throughput_information_model_json2 = current_throughput_information_model.to_dict() assert current_throughput_information_model_json2 == current_throughput_information_model_json class TestModel_CurrentThroughputInformationThroughput(): def test_current_throughput_information_throughput_serialization(self): # Construct a json representation of a CurrentThroughputInformationThroughput model current_throughput_information_throughput_model_json = {} current_throughput_information_throughput_model_json['query'] = 0 current_throughput_information_throughput_model_json['read'] = 0 current_throughput_information_throughput_model_json['write'] = 0 # Construct a model instance of CurrentThroughputInformationThroughput by calling from_dict on the json representation current_throughput_information_throughput_model = CurrentThroughputInformationThroughput.from_dict(current_throughput_information_throughput_model_json) assert current_throughput_information_throughput_model != False # Construct a model instance of CurrentThroughputInformationThroughput by calling from_dict on the json representation current_throughput_information_throughput_model_dict = CurrentThroughputInformationThroughput.from_dict(current_throughput_information_throughput_model_json).__dict__ current_throughput_information_throughput_model2 = CurrentThroughputInformationThroughput(**current_throughput_information_throughput_model_dict) # Verify the model instances are equivalent assert current_throughput_information_throughput_model == current_throughput_information_throughput_model2 # Convert model instance back to dict and verify no loss of data current_throughput_information_throughput_model_json2 = current_throughput_information_throughput_model.to_dict() assert current_throughput_information_throughput_model_json2 == current_throughput_information_throughput_model_json class TestModel_DatabaseInformation(): def test_database_information_serialization(self): # Construct dict forms of any model objects needed in order to build this model. database_information_cluster_model = {} # DatabaseInformationCluster database_information_cluster_model['n'] = 1 database_information_cluster_model['q'] = 1 database_information_cluster_model['r'] = 1 database_information_cluster_model['w'] = 1 database_information_props_model = {} # DatabaseInformationProps database_information_props_model['partitioned'] = True content_information_sizes_model = {} # ContentInformationSizes content_information_sizes_model['active'] = 26 content_information_sizes_model['external'] = 26 content_information_sizes_model['file'] = 26 # Construct a json representation of a DatabaseInformation model database_information_model_json = {} database_information_model_json['cluster'] = database_information_cluster_model database_information_model_json['committed_update_seq'] = 'testString' database_information_model_json['compact_running'] = True database_information_model_json['compacted_seq'] = 'testString' database_information_model_json['db_name'] = 'testString' database_information_model_json['disk_format_version'] = 26 database_information_model_json['doc_count'] = 0 database_information_model_json['doc_del_count'] = 0 database_information_model_json['engine'] = 'testString' database_information_model_json['props'] = database_information_props_model database_information_model_json['sizes'] = content_information_sizes_model database_information_model_json['update_seq'] = 'testString' database_information_model_json['uuid'] = 'testString' # Construct a model instance of DatabaseInformation by calling from_dict on the json representation database_information_model = DatabaseInformation.from_dict(database_information_model_json) assert database_information_model != False # Construct a model instance of DatabaseInformation by calling from_dict on the json representation database_information_model_dict = DatabaseInformation.from_dict(database_information_model_json).__dict__ database_information_model2 = DatabaseInformation(**database_information_model_dict) # Verify the model instances are equivalent assert database_information_model == database_information_model2 # Convert model instance back to dict and verify no loss of data database_information_model_json2 = database_information_model.to_dict() assert database_information_model_json2 == database_information_model_json class TestModel_DatabaseInformationCluster(): def test_database_information_cluster_serialization(self): # Construct a json representation of a DatabaseInformationCluster model database_information_cluster_model_json = {} database_information_cluster_model_json['n'] = 1 database_information_cluster_model_json['q'] = 1 database_information_cluster_model_json['r'] = 1 database_information_cluster_model_json['w'] = 1 # Construct a model instance of DatabaseInformationCluster by calling from_dict on the json representation database_information_cluster_model = DatabaseInformationCluster.from_dict(database_information_cluster_model_json) assert database_information_cluster_model != False # Construct a model instance of DatabaseInformationCluster by calling from_dict on the json representation database_information_cluster_model_dict = DatabaseInformationCluster.from_dict(database_information_cluster_model_json).__dict__ database_information_cluster_model2 = DatabaseInformationCluster(**database_information_cluster_model_dict) # Verify the model instances are equivalent assert database_information_cluster_model == database_information_cluster_model2 # Convert model instance back to dict and verify no loss of data database_information_cluster_model_json2 = database_information_cluster_model.to_dict() assert database_information_cluster_model_json2 == database_information_cluster_model_json class TestModel_DatabaseInformationProps(): def test_database_information_props_serialization(self): # Construct a json representation of a DatabaseInformationProps model database_information_props_model_json = {} database_information_props_model_json['partitioned'] = True # Construct a model instance of DatabaseInformationProps by calling from_dict on the json representation database_information_props_model = DatabaseInformationProps.from_dict(database_information_props_model_json) assert database_information_props_model != False # Construct a model instance of DatabaseInformationProps by calling from_dict on the json representation database_information_props_model_dict = DatabaseInformationProps.from_dict(database_information_props_model_json).__dict__ database_information_props_model2 = DatabaseInformationProps(**database_information_props_model_dict) # Verify the model instances are equivalent assert database_information_props_model == database_information_props_model2 # Convert model instance back to dict and verify no loss of data database_information_props_model_json2 = database_information_props_model.to_dict() assert database_information_props_model_json2 == database_information_props_model_json class TestModel_DbEvent(): def test_db_event_serialization(self): # Construct a json representation of a DbEvent model db_event_model_json = {} db_event_model_json['account'] = 'testString' db_event_model_json['db_name'] = 'testString' db_event_model_json['seq'] = 'testString' db_event_model_json['type'] = 'created' # Construct a model instance of DbEvent by calling from_dict on the json representation db_event_model = DbEvent.from_dict(db_event_model_json) assert db_event_model != False # Construct a model instance of DbEvent by calling from_dict on the json representation db_event_model_dict = DbEvent.from_dict(db_event_model_json).__dict__ db_event_model2 = DbEvent(**db_event_model_dict) # Verify the model instances are equivalent assert db_event_model == db_event_model2 # Convert model instance back to dict and verify no loss of data db_event_model_json2 = db_event_model.to_dict() assert db_event_model_json2 == db_event_model_json class TestModel_DbUpdates(): def test_db_updates_serialization(self): # Construct dict forms of any model objects needed in order to build this model. db_event_model = {} # DbEvent db_event_model['account'] = 'testString' db_event_model['db_name'] = 'testString' db_event_model['seq'] = 'testString' db_event_model['type'] = 'created' # Construct a json representation of a DbUpdates model db_updates_model_json = {} db_updates_model_json['last_seq'] = 'testString' db_updates_model_json['results'] = [db_event_model] # Construct a model instance of DbUpdates by calling from_dict on the json representation db_updates_model = DbUpdates.from_dict(db_updates_model_json) assert db_updates_model != False # Construct a model instance of DbUpdates by calling from_dict on the json representation db_updates_model_dict = DbUpdates.from_dict(db_updates_model_json).__dict__ db_updates_model2 = DbUpdates(**db_updates_model_dict) # Verify the model instances are equivalent assert db_updates_model == db_updates_model2 # Convert model instance back to dict and verify no loss of data db_updates_model_json2 = db_updates_model.to_dict() assert db_updates_model_json2 == db_updates_model_json class TestModel_DbsInfoResult(): def test_dbs_info_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. database_information_cluster_model = {} # DatabaseInformationCluster database_information_cluster_model['n'] = 1 database_information_cluster_model['q'] = 1 database_information_cluster_model['r'] = 1 database_information_cluster_model['w'] = 1 database_information_props_model = {} # DatabaseInformationProps database_information_props_model['partitioned'] = True content_information_sizes_model = {} # ContentInformationSizes content_information_sizes_model['active'] = 26 content_information_sizes_model['external'] = 26 content_information_sizes_model['file'] = 26 database_information_model = {} # DatabaseInformation database_information_model['cluster'] = database_information_cluster_model database_information_model['committed_update_seq'] = 'testString' database_information_model['compact_running'] = True database_information_model['compacted_seq'] = 'testString' database_information_model['db_name'] = 'testString' database_information_model['disk_format_version'] = 26 database_information_model['doc_count'] = 0 database_information_model['doc_del_count'] = 0 database_information_model['engine'] = 'testString' database_information_model['props'] = database_information_props_model database_information_model['sizes'] = content_information_sizes_model database_information_model['update_seq'] = 'testString' database_information_model['uuid'] = 'testString' # Construct a json representation of a DbsInfoResult model dbs_info_result_model_json = {} dbs_info_result_model_json['error'] = 'testString' dbs_info_result_model_json['info'] = database_information_model dbs_info_result_model_json['key'] = 'testString' # Construct a model instance of DbsInfoResult by calling from_dict on the json representation dbs_info_result_model = DbsInfoResult.from_dict(dbs_info_result_model_json) assert dbs_info_result_model != False # Construct a model instance of DbsInfoResult by calling from_dict on the json representation dbs_info_result_model_dict = DbsInfoResult.from_dict(dbs_info_result_model_json).__dict__ dbs_info_result_model2 = DbsInfoResult(**dbs_info_result_model_dict) # Verify the model instances are equivalent assert dbs_info_result_model == dbs_info_result_model2 # Convert model instance back to dict and verify no loss of data dbs_info_result_model_json2 = dbs_info_result_model.to_dict() assert dbs_info_result_model_json2 == dbs_info_result_model_json class TestModel_DesignDocument(): def test_design_document_serialization(self): # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' analyzer_model = {} # Analyzer analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] analyzer_configuration_model = {} # AnalyzerConfiguration analyzer_configuration_model['name'] = 'classic' analyzer_configuration_model['stopwords'] = ['testString'] analyzer_configuration_model['fields'] = {} search_index_definition_model = {} # SearchIndexDefinition search_index_definition_model['analyzer'] = analyzer_configuration_model search_index_definition_model['index'] = 'testString' design_document_options_model = {} # DesignDocumentOptions design_document_options_model['partitioned'] = True design_document_views_map_reduce_model = {} # DesignDocumentViewsMapReduce design_document_views_map_reduce_model['map'] = 'testString' design_document_views_map_reduce_model['reduce'] = 'testString' geo_index_definition_model = {} # GeoIndexDefinition geo_index_definition_model['index'] = 'testString' # Construct a json representation of a DesignDocument model design_document_model_json = {} design_document_model_json['_attachments'] = {} design_document_model_json['_conflicts'] = ['testString'] design_document_model_json['_deleted'] = True design_document_model_json['_deleted_conflicts'] = ['testString'] design_document_model_json['_id'] = 'testString' design_document_model_json['_local_seq'] = 'testString' design_document_model_json['_rev'] = 'testString' design_document_model_json['_revisions'] = revisions_model design_document_model_json['_revs_info'] = [document_revision_status_model] design_document_model_json['autoupdate'] = True design_document_model_json['filters'] = {} design_document_model_json['indexes'] = {} design_document_model_json['language'] = 'javascript' design_document_model_json['options'] = design_document_options_model design_document_model_json['validate_doc_update'] = 'testString' design_document_model_json['views'] = {} design_document_model_json['st_indexes'] = {} design_document_model_json['foo'] = 'testString' # Construct a model instance of DesignDocument by calling from_dict on the json representation design_document_model = DesignDocument.from_dict(design_document_model_json) assert design_document_model != False # Construct a model instance of DesignDocument by calling from_dict on the json representation design_document_model_dict = DesignDocument.from_dict(design_document_model_json).__dict__ design_document_model2 = DesignDocument(**design_document_model_dict) # Verify the model instances are equivalent assert design_document_model == design_document_model2 # Convert model instance back to dict and verify no loss of data design_document_model_json2 = design_document_model.to_dict() assert design_document_model_json2 == design_document_model_json # Test get_properties and set_properties methods. design_document_model.set_properties({}) actual_dict = design_document_model.get_properties() assert actual_dict == {} expected_dict = {'foo': 'testString'} design_document_model.set_properties(expected_dict) actual_dict = design_document_model.get_properties() assert actual_dict == expected_dict class TestModel_DesignDocumentInformation(): def test_design_document_information_serialization(self): # Construct dict forms of any model objects needed in order to build this model. content_information_sizes_model = {} # ContentInformationSizes content_information_sizes_model['active'] = 26 content_information_sizes_model['external'] = 26 content_information_sizes_model['file'] = 26 design_document_view_index_model = {} # DesignDocumentViewIndex design_document_view_index_model['compact_running'] = True design_document_view_index_model['language'] = 'testString' design_document_view_index_model['signature'] = 'testString' design_document_view_index_model['sizes'] = content_information_sizes_model design_document_view_index_model['updater_running'] = True design_document_view_index_model['waiting_clients'] = 0 design_document_view_index_model['waiting_commit'] = True # Construct a json representation of a DesignDocumentInformation model design_document_information_model_json = {} design_document_information_model_json['name'] = 'testString' design_document_information_model_json['view_index'] = design_document_view_index_model # Construct a model instance of DesignDocumentInformation by calling from_dict on the json representation design_document_information_model = DesignDocumentInformation.from_dict(design_document_information_model_json) assert design_document_information_model != False # Construct a model instance of DesignDocumentInformation by calling from_dict on the json representation design_document_information_model_dict = DesignDocumentInformation.from_dict(design_document_information_model_json).__dict__ design_document_information_model2 = DesignDocumentInformation(**design_document_information_model_dict) # Verify the model instances are equivalent assert design_document_information_model == design_document_information_model2 # Convert model instance back to dict and verify no loss of data design_document_information_model_json2 = design_document_information_model.to_dict() assert design_document_information_model_json2 == design_document_information_model_json class TestModel_DesignDocumentOptions(): def test_design_document_options_serialization(self): # Construct a json representation of a DesignDocumentOptions model design_document_options_model_json = {} design_document_options_model_json['partitioned'] = True # Construct a model instance of DesignDocumentOptions by calling from_dict on the json representation design_document_options_model = DesignDocumentOptions.from_dict(design_document_options_model_json) assert design_document_options_model != False # Construct a model instance of DesignDocumentOptions by calling from_dict on the json representation design_document_options_model_dict = DesignDocumentOptions.from_dict(design_document_options_model_json).__dict__ design_document_options_model2 = DesignDocumentOptions(**design_document_options_model_dict) # Verify the model instances are equivalent assert design_document_options_model == design_document_options_model2 # Convert model instance back to dict and verify no loss of data design_document_options_model_json2 = design_document_options_model.to_dict() assert design_document_options_model_json2 == design_document_options_model_json class TestModel_DesignDocumentViewIndex(): def test_design_document_view_index_serialization(self): # Construct dict forms of any model objects needed in order to build this model. content_information_sizes_model = {} # ContentInformationSizes content_information_sizes_model['active'] = 26 content_information_sizes_model['external'] = 26 content_information_sizes_model['file'] = 26 # Construct a json representation of a DesignDocumentViewIndex model design_document_view_index_model_json = {} design_document_view_index_model_json['compact_running'] = True design_document_view_index_model_json['language'] = 'testString' design_document_view_index_model_json['signature'] = 'testString' design_document_view_index_model_json['sizes'] = content_information_sizes_model design_document_view_index_model_json['updater_running'] = True design_document_view_index_model_json['waiting_clients'] = 0 design_document_view_index_model_json['waiting_commit'] = True # Construct a model instance of DesignDocumentViewIndex by calling from_dict on the json representation design_document_view_index_model = DesignDocumentViewIndex.from_dict(design_document_view_index_model_json) assert design_document_view_index_model != False # Construct a model instance of DesignDocumentViewIndex by calling from_dict on the json representation design_document_view_index_model_dict = DesignDocumentViewIndex.from_dict(design_document_view_index_model_json).__dict__ design_document_view_index_model2 = DesignDocumentViewIndex(**design_document_view_index_model_dict) # Verify the model instances are equivalent assert design_document_view_index_model == design_document_view_index_model2 # Convert model instance back to dict and verify no loss of data design_document_view_index_model_json2 = design_document_view_index_model.to_dict() assert design_document_view_index_model_json2 == design_document_view_index_model_json class TestModel_DesignDocumentViewsMapReduce(): def test_design_document_views_map_reduce_serialization(self): # Construct a json representation of a DesignDocumentViewsMapReduce model design_document_views_map_reduce_model_json = {} design_document_views_map_reduce_model_json['map'] = 'testString' design_document_views_map_reduce_model_json['reduce'] = 'testString' # Construct a model instance of DesignDocumentViewsMapReduce by calling from_dict on the json representation design_document_views_map_reduce_model = DesignDocumentViewsMapReduce.from_dict(design_document_views_map_reduce_model_json) assert design_document_views_map_reduce_model != False # Construct a model instance of DesignDocumentViewsMapReduce by calling from_dict on the json representation design_document_views_map_reduce_model_dict = DesignDocumentViewsMapReduce.from_dict(design_document_views_map_reduce_model_json).__dict__ design_document_views_map_reduce_model2 = DesignDocumentViewsMapReduce(**design_document_views_map_reduce_model_dict) # Verify the model instances are equivalent assert design_document_views_map_reduce_model == design_document_views_map_reduce_model2 # Convert model instance back to dict and verify no loss of data design_document_views_map_reduce_model_json2 = design_document_views_map_reduce_model.to_dict() assert design_document_views_map_reduce_model_json2 == design_document_views_map_reduce_model_json class TestModel_DocsResultRow(): def test_docs_result_row_serialization(self): # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' docs_result_row_value_model = {} # DocsResultRowValue docs_result_row_value_model['rev'] = 'testString' # Construct a json representation of a DocsResultRow model docs_result_row_model_json = {} docs_result_row_model_json['caused_by'] = 'testString' docs_result_row_model_json['error'] = 'testString' docs_result_row_model_json['reason'] = 'testString' docs_result_row_model_json['doc'] = document_model docs_result_row_model_json['id'] = 'testString' docs_result_row_model_json['key'] = 'testString' docs_result_row_model_json['value'] = docs_result_row_value_model # Construct a model instance of DocsResultRow by calling from_dict on the json representation docs_result_row_model = DocsResultRow.from_dict(docs_result_row_model_json) assert docs_result_row_model != False # Construct a model instance of DocsResultRow by calling from_dict on the json representation docs_result_row_model_dict = DocsResultRow.from_dict(docs_result_row_model_json).__dict__ docs_result_row_model2 = DocsResultRow(**docs_result_row_model_dict) # Verify the model instances are equivalent assert docs_result_row_model == docs_result_row_model2 # Convert model instance back to dict and verify no loss of data docs_result_row_model_json2 = docs_result_row_model.to_dict() assert docs_result_row_model_json2 == docs_result_row_model_json class TestModel_DocsResultRowValue(): def test_docs_result_row_value_serialization(self): # Construct a json representation of a DocsResultRowValue model docs_result_row_value_model_json = {} docs_result_row_value_model_json['rev'] = 'testString' # Construct a model instance of DocsResultRowValue by calling from_dict on the json representation docs_result_row_value_model = DocsResultRowValue.from_dict(docs_result_row_value_model_json) assert docs_result_row_value_model != False # Construct a model instance of DocsResultRowValue by calling from_dict on the json representation docs_result_row_value_model_dict = DocsResultRowValue.from_dict(docs_result_row_value_model_json).__dict__ docs_result_row_value_model2 = DocsResultRowValue(**docs_result_row_value_model_dict) # Verify the model instances are equivalent assert docs_result_row_value_model == docs_result_row_value_model2 # Convert model instance back to dict and verify no loss of data docs_result_row_value_model_json2 = docs_result_row_value_model.to_dict() assert docs_result_row_value_model_json2 == docs_result_row_value_model_json class TestModel_Document(): def test_document_serialization(self): # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' # Construct a json representation of a Document model document_model_json = {} document_model_json['_attachments'] = {} document_model_json['_conflicts'] = ['testString'] document_model_json['_deleted'] = True document_model_json['_deleted_conflicts'] = ['testString'] document_model_json['_id'] = 'testString' document_model_json['_local_seq'] = 'testString' document_model_json['_rev'] = 'testString' document_model_json['_revisions'] = revisions_model document_model_json['_revs_info'] = [document_revision_status_model] document_model_json['foo'] = 'testString' # Construct a model instance of Document by calling from_dict on the json representation document_model = Document.from_dict(document_model_json) assert document_model != False # Construct a model instance of Document by calling from_dict on the json representation document_model_dict = Document.from_dict(document_model_json).__dict__ document_model2 = Document(**document_model_dict) # Verify the model instances are equivalent assert document_model == document_model2 # Convert model instance back to dict and verify no loss of data document_model_json2 = document_model.to_dict() assert document_model_json2 == document_model_json # Test get_properties and set_properties methods. document_model.set_properties({}) actual_dict = document_model.get_properties() assert actual_dict == {} expected_dict = {'foo': 'testString'} document_model.set_properties(expected_dict) actual_dict = document_model.get_properties() assert actual_dict == expected_dict class TestModel_DocumentResult(): def test_document_result_serialization(self): # Construct a json representation of a DocumentResult model document_result_model_json = {} document_result_model_json['id'] = 'testString' document_result_model_json['rev'] = 'testString' document_result_model_json['ok'] = True document_result_model_json['caused_by'] = 'testString' document_result_model_json['error'] = 'testString' document_result_model_json['reason'] = 'testString' # Construct a model instance of DocumentResult by calling from_dict on the json representation document_result_model = DocumentResult.from_dict(document_result_model_json) assert document_result_model != False # Construct a model instance of DocumentResult by calling from_dict on the json representation document_result_model_dict = DocumentResult.from_dict(document_result_model_json).__dict__ document_result_model2 = DocumentResult(**document_result_model_dict) # Verify the model instances are equivalent assert document_result_model == document_result_model2 # Convert model instance back to dict and verify no loss of data document_result_model_json2 = document_result_model.to_dict() assert document_result_model_json2 == document_result_model_json class TestModel_DocumentRevisionStatus(): def test_document_revision_status_serialization(self): # Construct a json representation of a DocumentRevisionStatus model document_revision_status_model_json = {} document_revision_status_model_json['rev'] = 'testString' document_revision_status_model_json['status'] = 'available' # Construct a model instance of DocumentRevisionStatus by calling from_dict on the json representation document_revision_status_model = DocumentRevisionStatus.from_dict(document_revision_status_model_json) assert document_revision_status_model != False # Construct a model instance of DocumentRevisionStatus by calling from_dict on the json representation document_revision_status_model_dict = DocumentRevisionStatus.from_dict(document_revision_status_model_json).__dict__ document_revision_status_model2 = DocumentRevisionStatus(**document_revision_status_model_dict) # Verify the model instances are equivalent assert document_revision_status_model == document_revision_status_model2 # Convert model instance back to dict and verify no loss of data document_revision_status_model_json2 = document_revision_status_model.to_dict() assert document_revision_status_model_json2 == document_revision_status_model_json class TestModel_DocumentShardInfo(): def test_document_shard_info_serialization(self): # Construct a json representation of a DocumentShardInfo model document_shard_info_model_json = {} document_shard_info_model_json['nodes'] = ['testString'] document_shard_info_model_json['range'] = 'testString' # Construct a model instance of DocumentShardInfo by calling from_dict on the json representation document_shard_info_model = DocumentShardInfo.from_dict(document_shard_info_model_json) assert document_shard_info_model != False # Construct a model instance of DocumentShardInfo by calling from_dict on the json representation document_shard_info_model_dict = DocumentShardInfo.from_dict(document_shard_info_model_json).__dict__ document_shard_info_model2 = DocumentShardInfo(**document_shard_info_model_dict) # Verify the model instances are equivalent assert document_shard_info_model == document_shard_info_model2 # Convert model instance back to dict and verify no loss of data document_shard_info_model_json2 = document_shard_info_model.to_dict() assert document_shard_info_model_json2 == document_shard_info_model_json class TestModel_ExecutionStats(): def test_execution_stats_serialization(self): # Construct a json representation of a ExecutionStats model execution_stats_model_json = {} execution_stats_model_json['execution_time_ms'] = 72.5 execution_stats_model_json['results_returned'] = 0 execution_stats_model_json['total_docs_examined'] = 0 execution_stats_model_json['total_keys_examined'] = 0 execution_stats_model_json['total_quorum_docs_examined'] = 0 # Construct a model instance of ExecutionStats by calling from_dict on the json representation execution_stats_model = ExecutionStats.from_dict(execution_stats_model_json) assert execution_stats_model != False # Construct a model instance of ExecutionStats by calling from_dict on the json representation execution_stats_model_dict = ExecutionStats.from_dict(execution_stats_model_json).__dict__ execution_stats_model2 = ExecutionStats(**execution_stats_model_dict) # Verify the model instances are equivalent assert execution_stats_model == execution_stats_model2 # Convert model instance back to dict and verify no loss of data execution_stats_model_json2 = execution_stats_model.to_dict() assert execution_stats_model_json2 == execution_stats_model_json class TestModel_ExplainResult(): def test_explain_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. analyzer_model = {} # Analyzer analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] index_text_operator_default_field_model = {} # IndexTextOperatorDefaultField index_text_operator_default_field_model['analyzer'] = analyzer_model index_text_operator_default_field_model['enabled'] = True index_field_model = {} # IndexField index_field_model['name'] = 'testString' index_field_model['type'] = 'boolean' index_field_model['foo'] = 'asc' index_definition_model = {} # IndexDefinition index_definition_model['default_analyzer'] = analyzer_model index_definition_model['default_field'] = index_text_operator_default_field_model index_definition_model['fields'] = [index_field_model] index_definition_model['index_array_lengths'] = True index_definition_model['partial_filter_selector'] = {} index_information_model = {} # IndexInformation index_information_model['ddoc'] = 'testString' index_information_model['def'] = index_definition_model index_information_model['name'] = 'testString' index_information_model['type'] = 'json' explain_result_range_model = {} # ExplainResultRange explain_result_range_model['end_key'] = ['testString'] explain_result_range_model['start_key'] = ['testString'] # Construct a json representation of a ExplainResult model explain_result_model_json = {} explain_result_model_json['dbname'] = 'testString' explain_result_model_json['fields'] = ['testString'] explain_result_model_json['index'] = index_information_model explain_result_model_json['limit'] = 0 explain_result_model_json['opts'] = {} explain_result_model_json['range'] = explain_result_range_model explain_result_model_json['selector'] = {} explain_result_model_json['skip'] = 0 # Construct a model instance of ExplainResult by calling from_dict on the json representation explain_result_model = ExplainResult.from_dict(explain_result_model_json) assert explain_result_model != False # Construct a model instance of ExplainResult by calling from_dict on the json representation explain_result_model_dict = ExplainResult.from_dict(explain_result_model_json).__dict__ explain_result_model2 = ExplainResult(**explain_result_model_dict) # Verify the model instances are equivalent assert explain_result_model == explain_result_model2 # Convert model instance back to dict and verify no loss of data explain_result_model_json2 = explain_result_model.to_dict() assert explain_result_model_json2 == explain_result_model_json class TestModel_ExplainResultRange(): def test_explain_result_range_serialization(self): # Construct a json representation of a ExplainResultRange model explain_result_range_model_json = {} explain_result_range_model_json['end_key'] = ['testString'] explain_result_range_model_json['start_key'] = ['testString'] # Construct a model instance of ExplainResultRange by calling from_dict on the json representation explain_result_range_model = ExplainResultRange.from_dict(explain_result_range_model_json) assert explain_result_range_model != False # Construct a model instance of ExplainResultRange by calling from_dict on the json representation explain_result_range_model_dict = ExplainResultRange.from_dict(explain_result_range_model_json).__dict__ explain_result_range_model2 = ExplainResultRange(**explain_result_range_model_dict) # Verify the model instances are equivalent assert explain_result_range_model == explain_result_range_model2 # Convert model instance back to dict and verify no loss of data explain_result_range_model_json2 = explain_result_range_model.to_dict() assert explain_result_range_model_json2 == explain_result_range_model_json class TestModel_FindResult(): def test_find_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' execution_stats_model = {} # ExecutionStats execution_stats_model['execution_time_ms'] = 72.5 execution_stats_model['results_returned'] = 0 execution_stats_model['total_docs_examined'] = 0 execution_stats_model['total_keys_examined'] = 0 execution_stats_model['total_quorum_docs_examined'] = 0 # Construct a json representation of a FindResult model find_result_model_json = {} find_result_model_json['bookmark'] = 'testString' find_result_model_json['docs'] = [document_model] find_result_model_json['execution_stats'] = execution_stats_model find_result_model_json['warning'] = 'testString' # Construct a model instance of FindResult by calling from_dict on the json representation find_result_model = FindResult.from_dict(find_result_model_json) assert find_result_model != False # Construct a model instance of FindResult by calling from_dict on the json representation find_result_model_dict = FindResult.from_dict(find_result_model_json).__dict__ find_result_model2 = FindResult(**find_result_model_dict) # Verify the model instances are equivalent assert find_result_model == find_result_model2 # Convert model instance back to dict and verify no loss of data find_result_model_json2 = find_result_model.to_dict() assert find_result_model_json2 == find_result_model_json class TestModel_GeoIndexDefinition(): def test_geo_index_definition_serialization(self): # Construct a json representation of a GeoIndexDefinition model geo_index_definition_model_json = {} geo_index_definition_model_json['index'] = 'testString' # Construct a model instance of GeoIndexDefinition by calling from_dict on the json representation geo_index_definition_model = GeoIndexDefinition.from_dict(geo_index_definition_model_json) assert geo_index_definition_model != False # Construct a model instance of GeoIndexDefinition by calling from_dict on the json representation geo_index_definition_model_dict = GeoIndexDefinition.from_dict(geo_index_definition_model_json).__dict__ geo_index_definition_model2 = GeoIndexDefinition(**geo_index_definition_model_dict) # Verify the model instances are equivalent assert geo_index_definition_model == geo_index_definition_model2 # Convert model instance back to dict and verify no loss of data geo_index_definition_model_json2 = geo_index_definition_model.to_dict() assert geo_index_definition_model_json2 == geo_index_definition_model_json class TestModel_GeoIndexInformation(): def test_geo_index_information_serialization(self): # Construct dict forms of any model objects needed in order to build this model. geo_index_stats_model = {} # GeoIndexStats geo_index_stats_model['data_size'] = 0 geo_index_stats_model['disk_size'] = 0 geo_index_stats_model['doc_count'] = 0 # Construct a json representation of a GeoIndexInformation model geo_index_information_model_json = {} geo_index_information_model_json['geo_index'] = geo_index_stats_model geo_index_information_model_json['name'] = 'testString' # Construct a model instance of GeoIndexInformation by calling from_dict on the json representation geo_index_information_model = GeoIndexInformation.from_dict(geo_index_information_model_json) assert geo_index_information_model != False # Construct a model instance of GeoIndexInformation by calling from_dict on the json representation geo_index_information_model_dict = GeoIndexInformation.from_dict(geo_index_information_model_json).__dict__ geo_index_information_model2 = GeoIndexInformation(**geo_index_information_model_dict) # Verify the model instances are equivalent assert geo_index_information_model == geo_index_information_model2 # Convert model instance back to dict and verify no loss of data geo_index_information_model_json2 = geo_index_information_model.to_dict() assert geo_index_information_model_json2 == geo_index_information_model_json class TestModel_GeoIndexStats(): def test_geo_index_stats_serialization(self): # Construct a json representation of a GeoIndexStats model geo_index_stats_model_json = {} geo_index_stats_model_json['data_size'] = 0 geo_index_stats_model_json['disk_size'] = 0 geo_index_stats_model_json['doc_count'] = 0 # Construct a model instance of GeoIndexStats by calling from_dict on the json representation geo_index_stats_model = GeoIndexStats.from_dict(geo_index_stats_model_json) assert geo_index_stats_model != False # Construct a model instance of GeoIndexStats by calling from_dict on the json representation geo_index_stats_model_dict = GeoIndexStats.from_dict(geo_index_stats_model_json).__dict__ geo_index_stats_model2 = GeoIndexStats(**geo_index_stats_model_dict) # Verify the model instances are equivalent assert geo_index_stats_model == geo_index_stats_model2 # Convert model instance back to dict and verify no loss of data geo_index_stats_model_json2 = geo_index_stats_model.to_dict() assert geo_index_stats_model_json2 == geo_index_stats_model_json class TestModel_GeoJsonFeature(): def test_geo_json_feature_serialization(self): # Construct dict forms of any model objects needed in order to build this model. geo_json_geometry_object_model = {} # GeoJsonGeometry geo_json_geometry_object_model['type'] = 'Point' geo_json_geometry_object_model['coordinates'] = ['testString'] # Construct a json representation of a GeoJsonFeature model geo_json_feature_model_json = {} geo_json_feature_model_json['_id'] = 'testString' geo_json_feature_model_json['_rev'] = 'testString' geo_json_feature_model_json['bbox'] = [72.5] geo_json_feature_model_json['geometry'] = geo_json_geometry_object_model geo_json_feature_model_json['properties'] = {} geo_json_feature_model_json['type'] = 'Feature' geo_json_feature_model_json['foo'] = 'testString' # Construct a model instance of GeoJsonFeature by calling from_dict on the json representation geo_json_feature_model = GeoJsonFeature.from_dict(geo_json_feature_model_json) assert geo_json_feature_model != False # Construct a model instance of GeoJsonFeature by calling from_dict on the json representation geo_json_feature_model_dict = GeoJsonFeature.from_dict(geo_json_feature_model_json).__dict__ geo_json_feature_model2 = GeoJsonFeature(**geo_json_feature_model_dict) # Verify the model instances are equivalent assert geo_json_feature_model == geo_json_feature_model2 # Convert model instance back to dict and verify no loss of data geo_json_feature_model_json2 = geo_json_feature_model.to_dict() assert geo_json_feature_model_json2 == geo_json_feature_model_json # Test get_properties and set_properties methods. geo_json_feature_model.set_properties({}) actual_dict = geo_json_feature_model.get_properties() assert actual_dict == {} expected_dict = {'foo': 'testString'} geo_json_feature_model.set_properties(expected_dict) actual_dict = geo_json_feature_model.get_properties() assert actual_dict == expected_dict class TestModel_GeoResult(): def test_geo_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. geo_json_geometry_object_model = {} # GeoJsonGeometry geo_json_geometry_object_model['type'] = 'Point' geo_json_geometry_object_model['coordinates'] = ['testString'] geo_json_feature_model = {} # GeoJsonFeature geo_json_feature_model['_id'] = 'testString' geo_json_feature_model['_rev'] = 'testString' geo_json_feature_model['bbox'] = [72.5] geo_json_feature_model['geometry'] = geo_json_geometry_object_model geo_json_feature_model['properties'] = {} geo_json_feature_model['type'] = 'Feature' geo_json_feature_model['foo'] = 'testString' attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' geo_json_geometry_model = {} # GeoJsonGeometry geo_json_geometry_model['type'] = 'Point' geo_json_geometry_model['coordinates'] = ['testString'] geo_result_row_model = {} # GeoResultRow geo_result_row_model['doc'] = document_model geo_result_row_model['geometry'] = geo_json_geometry_model geo_result_row_model['id'] = 'testString' geo_result_row_model['rev'] = 'testString' # Construct a json representation of a GeoResult model geo_result_model_json = {} geo_result_model_json['bookmark'] = 'testString' geo_result_model_json['features'] = [geo_json_feature_model] geo_result_model_json['rows'] = [geo_result_row_model] geo_result_model_json['type'] = 'FeatureCollection' # Construct a model instance of GeoResult by calling from_dict on the json representation geo_result_model = GeoResult.from_dict(geo_result_model_json) assert geo_result_model != False # Construct a model instance of GeoResult by calling from_dict on the json representation geo_result_model_dict = GeoResult.from_dict(geo_result_model_json).__dict__ geo_result_model2 = GeoResult(**geo_result_model_dict) # Verify the model instances are equivalent assert geo_result_model == geo_result_model2 # Convert model instance back to dict and verify no loss of data geo_result_model_json2 = geo_result_model.to_dict() assert geo_result_model_json2 == geo_result_model_json class TestModel_GeoResultRow(): def test_geo_result_row_serialization(self): # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' geo_json_geometry_model = {} # GeoJsonGeometry geo_json_geometry_model['type'] = 'Point' geo_json_geometry_model['coordinates'] = ['testString'] # Construct a json representation of a GeoResultRow model geo_result_row_model_json = {} geo_result_row_model_json['doc'] = document_model geo_result_row_model_json['geometry'] = geo_json_geometry_model geo_result_row_model_json['id'] = 'testString' geo_result_row_model_json['rev'] = 'testString' # Construct a model instance of GeoResultRow by calling from_dict on the json representation geo_result_row_model = GeoResultRow.from_dict(geo_result_row_model_json) assert geo_result_row_model != False # Construct a model instance of GeoResultRow by calling from_dict on the json representation geo_result_row_model_dict = GeoResultRow.from_dict(geo_result_row_model_json).__dict__ geo_result_row_model2 = GeoResultRow(**geo_result_row_model_dict) # Verify the model instances are equivalent assert geo_result_row_model == geo_result_row_model2 # Convert model instance back to dict and verify no loss of data geo_result_row_model_json2 = geo_result_row_model.to_dict() assert geo_result_row_model_json2 == geo_result_row_model_json class TestModel_IndexDefinition(): def test_index_definition_serialization(self): # Construct dict forms of any model objects needed in order to build this model. analyzer_model = {} # Analyzer analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] index_text_operator_default_field_model = {} # IndexTextOperatorDefaultField index_text_operator_default_field_model['analyzer'] = analyzer_model index_text_operator_default_field_model['enabled'] = True index_field_model = {} # IndexField index_field_model['name'] = 'testString' index_field_model['type'] = 'boolean' index_field_model['foo'] = 'asc' # Construct a json representation of a IndexDefinition model index_definition_model_json = {} index_definition_model_json['default_analyzer'] = analyzer_model index_definition_model_json['default_field'] = index_text_operator_default_field_model index_definition_model_json['fields'] = [index_field_model] index_definition_model_json['index_array_lengths'] = True index_definition_model_json['partial_filter_selector'] = {} # Construct a model instance of IndexDefinition by calling from_dict on the json representation index_definition_model = IndexDefinition.from_dict(index_definition_model_json) assert index_definition_model != False # Construct a model instance of IndexDefinition by calling from_dict on the json representation index_definition_model_dict = IndexDefinition.from_dict(index_definition_model_json).__dict__ index_definition_model2 = IndexDefinition(**index_definition_model_dict) # Verify the model instances are equivalent assert index_definition_model == index_definition_model2 # Convert model instance back to dict and verify no loss of data index_definition_model_json2 = index_definition_model.to_dict() assert index_definition_model_json2 == index_definition_model_json class TestModel_IndexField(): def test_index_field_serialization(self): # Construct a json representation of a IndexField model index_field_model_json = {} index_field_model_json['name'] = 'testString' index_field_model_json['type'] = 'boolean' index_field_model_json['foo'] = 'asc' # Construct a model instance of IndexField by calling from_dict on the json representation index_field_model = IndexField.from_dict(index_field_model_json) assert index_field_model != False # Construct a model instance of IndexField by calling from_dict on the json representation index_field_model_dict = IndexField.from_dict(index_field_model_json).__dict__ index_field_model2 = IndexField(**index_field_model_dict) # Verify the model instances are equivalent assert index_field_model == index_field_model2 # Convert model instance back to dict and verify no loss of data index_field_model_json2 = index_field_model.to_dict() assert index_field_model_json2 == index_field_model_json # Test get_properties and set_properties methods. index_field_model.set_properties({}) actual_dict = index_field_model.get_properties() assert actual_dict == {} expected_dict = {'foo': 'asc'} index_field_model.set_properties(expected_dict) actual_dict = index_field_model.get_properties() assert actual_dict == expected_dict class TestModel_IndexInformation(): def test_index_information_serialization(self): # Construct dict forms of any model objects needed in order to build this model. analyzer_model = {} # Analyzer analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] index_text_operator_default_field_model = {} # IndexTextOperatorDefaultField index_text_operator_default_field_model['analyzer'] = analyzer_model index_text_operator_default_field_model['enabled'] = True index_field_model = {} # IndexField index_field_model['name'] = 'testString' index_field_model['type'] = 'boolean' index_field_model['foo'] = 'asc' index_definition_model = {} # IndexDefinition index_definition_model['default_analyzer'] = analyzer_model index_definition_model['default_field'] = index_text_operator_default_field_model index_definition_model['fields'] = [index_field_model] index_definition_model['index_array_lengths'] = True index_definition_model['partial_filter_selector'] = {} # Construct a json representation of a IndexInformation model index_information_model_json = {} index_information_model_json['ddoc'] = 'testString' index_information_model_json['def'] = index_definition_model index_information_model_json['name'] = 'testString' index_information_model_json['type'] = 'json' # Construct a model instance of IndexInformation by calling from_dict on the json representation index_information_model = IndexInformation.from_dict(index_information_model_json) assert index_information_model != False # Construct a model instance of IndexInformation by calling from_dict on the json representation index_information_model_dict = IndexInformation.from_dict(index_information_model_json).__dict__ index_information_model2 = IndexInformation(**index_information_model_dict) # Verify the model instances are equivalent assert index_information_model == index_information_model2 # Convert model instance back to dict and verify no loss of data index_information_model_json2 = index_information_model.to_dict() assert index_information_model_json2 == index_information_model_json class TestModel_IndexResult(): def test_index_result_serialization(self): # Construct a json representation of a IndexResult model index_result_model_json = {} index_result_model_json['id'] = 'testString' index_result_model_json['name'] = 'testString' index_result_model_json['result'] = 'created' # Construct a model instance of IndexResult by calling from_dict on the json representation index_result_model = IndexResult.from_dict(index_result_model_json) assert index_result_model != False # Construct a model instance of IndexResult by calling from_dict on the json representation index_result_model_dict = IndexResult.from_dict(index_result_model_json).__dict__ index_result_model2 = IndexResult(**index_result_model_dict) # Verify the model instances are equivalent assert index_result_model == index_result_model2 # Convert model instance back to dict and verify no loss of data index_result_model_json2 = index_result_model.to_dict() assert index_result_model_json2 == index_result_model_json class TestModel_IndexTextOperatorDefaultField(): def test_index_text_operator_default_field_serialization(self): # Construct dict forms of any model objects needed in order to build this model. analyzer_model = {} # Analyzer analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] # Construct a json representation of a IndexTextOperatorDefaultField model index_text_operator_default_field_model_json = {} index_text_operator_default_field_model_json['analyzer'] = analyzer_model index_text_operator_default_field_model_json['enabled'] = True # Construct a model instance of IndexTextOperatorDefaultField by calling from_dict on the json representation index_text_operator_default_field_model = IndexTextOperatorDefaultField.from_dict(index_text_operator_default_field_model_json) assert index_text_operator_default_field_model != False # Construct a model instance of IndexTextOperatorDefaultField by calling from_dict on the json representation index_text_operator_default_field_model_dict = IndexTextOperatorDefaultField.from_dict(index_text_operator_default_field_model_json).__dict__ index_text_operator_default_field_model2 = IndexTextOperatorDefaultField(**index_text_operator_default_field_model_dict) # Verify the model instances are equivalent assert index_text_operator_default_field_model == index_text_operator_default_field_model2 # Convert model instance back to dict and verify no loss of data index_text_operator_default_field_model_json2 = index_text_operator_default_field_model.to_dict() assert index_text_operator_default_field_model_json2 == index_text_operator_default_field_model_json class TestModel_IndexesInformation(): def test_indexes_information_serialization(self): # Construct dict forms of any model objects needed in order to build this model. analyzer_model = {} # Analyzer analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] index_text_operator_default_field_model = {} # IndexTextOperatorDefaultField index_text_operator_default_field_model['analyzer'] = analyzer_model index_text_operator_default_field_model['enabled'] = True index_field_model = {} # IndexField index_field_model['name'] = 'testString' index_field_model['type'] = 'boolean' index_field_model['foo'] = 'asc' index_definition_model = {} # IndexDefinition index_definition_model['default_analyzer'] = analyzer_model index_definition_model['default_field'] = index_text_operator_default_field_model index_definition_model['fields'] = [index_field_model] index_definition_model['index_array_lengths'] = True index_definition_model['partial_filter_selector'] = {} index_information_model = {} # IndexInformation index_information_model['ddoc'] = 'testString' index_information_model['def'] = index_definition_model index_information_model['name'] = 'testString' index_information_model['type'] = 'json' # Construct a json representation of a IndexesInformation model indexes_information_model_json = {} indexes_information_model_json['total_rows'] = 0 indexes_information_model_json['indexes'] = [index_information_model] # Construct a model instance of IndexesInformation by calling from_dict on the json representation indexes_information_model = IndexesInformation.from_dict(indexes_information_model_json) assert indexes_information_model != False # Construct a model instance of IndexesInformation by calling from_dict on the json representation indexes_information_model_dict = IndexesInformation.from_dict(indexes_information_model_json).__dict__ indexes_information_model2 = IndexesInformation(**indexes_information_model_dict) # Verify the model instances are equivalent assert indexes_information_model == indexes_information_model2 # Convert model instance back to dict and verify no loss of data indexes_information_model_json2 = indexes_information_model.to_dict() assert indexes_information_model_json2 == indexes_information_model_json class TestModel_MembershipInformation(): def test_membership_information_serialization(self): # Construct a json representation of a MembershipInformation model membership_information_model_json = {} membership_information_model_json['all_nodes'] = ['testString'] membership_information_model_json['cluster_nodes'] = ['testString'] # Construct a model instance of MembershipInformation by calling from_dict on the json representation membership_information_model = MembershipInformation.from_dict(membership_information_model_json) assert membership_information_model != False # Construct a model instance of MembershipInformation by calling from_dict on the json representation membership_information_model_dict = MembershipInformation.from_dict(membership_information_model_json).__dict__ membership_information_model2 = MembershipInformation(**membership_information_model_dict) # Verify the model instances are equivalent assert membership_information_model == membership_information_model2 # Convert model instance back to dict and verify no loss of data membership_information_model_json2 = membership_information_model.to_dict() assert membership_information_model_json2 == membership_information_model_json class TestModel_Ok(): def test_ok_serialization(self): # Construct a json representation of a Ok model ok_model_json = {} ok_model_json['ok'] = True # Construct a model instance of Ok by calling from_dict on the json representation ok_model = Ok.from_dict(ok_model_json) assert ok_model != False # Construct a model instance of Ok by calling from_dict on the json representation ok_model_dict = Ok.from_dict(ok_model_json).__dict__ ok_model2 = Ok(**ok_model_dict) # Verify the model instances are equivalent assert ok_model == ok_model2 # Convert model instance back to dict and verify no loss of data ok_model_json2 = ok_model.to_dict() assert ok_model_json2 == ok_model_json class TestModel_PartitionInformation(): def test_partition_information_serialization(self): # Construct dict forms of any model objects needed in order to build this model. partition_information_indexes_indexes_model = {} # PartitionInformationIndexesIndexes partition_information_indexes_indexes_model['search'] = 0 partition_information_indexes_indexes_model['view'] = 0 partition_information_indexes_model = {} # PartitionInformationIndexes partition_information_indexes_model['count'] = 0 partition_information_indexes_model['indexes'] = partition_information_indexes_indexes_model partition_information_indexes_model['limit'] = 0 partition_information_sizes_model = {} # PartitionInformationSizes partition_information_sizes_model['active'] = 0 partition_information_sizes_model['external'] = 0 # Construct a json representation of a PartitionInformation model partition_information_model_json = {} partition_information_model_json['db_name'] = 'testString' partition_information_model_json['doc_count'] = 0 partition_information_model_json['doc_del_count'] = 0 partition_information_model_json['partition'] = 'testString' partition_information_model_json['partitioned_indexes'] = partition_information_indexes_model partition_information_model_json['sizes'] = partition_information_sizes_model # Construct a model instance of PartitionInformation by calling from_dict on the json representation partition_information_model = PartitionInformation.from_dict(partition_information_model_json) assert partition_information_model != False # Construct a model instance of PartitionInformation by calling from_dict on the json representation partition_information_model_dict = PartitionInformation.from_dict(partition_information_model_json).__dict__ partition_information_model2 = PartitionInformation(**partition_information_model_dict) # Verify the model instances are equivalent assert partition_information_model == partition_information_model2 # Convert model instance back to dict and verify no loss of data partition_information_model_json2 = partition_information_model.to_dict() assert partition_information_model_json2 == partition_information_model_json class TestModel_PartitionInformationIndexes(): def test_partition_information_indexes_serialization(self): # Construct dict forms of any model objects needed in order to build this model. partition_information_indexes_indexes_model = {} # PartitionInformationIndexesIndexes partition_information_indexes_indexes_model['search'] = 0 partition_information_indexes_indexes_model['view'] = 0 # Construct a json representation of a PartitionInformationIndexes model partition_information_indexes_model_json = {} partition_information_indexes_model_json['count'] = 0 partition_information_indexes_model_json['indexes'] = partition_information_indexes_indexes_model partition_information_indexes_model_json['limit'] = 0 # Construct a model instance of PartitionInformationIndexes by calling from_dict on the json representation partition_information_indexes_model = PartitionInformationIndexes.from_dict(partition_information_indexes_model_json) assert partition_information_indexes_model != False # Construct a model instance of PartitionInformationIndexes by calling from_dict on the json representation partition_information_indexes_model_dict = PartitionInformationIndexes.from_dict(partition_information_indexes_model_json).__dict__ partition_information_indexes_model2 = PartitionInformationIndexes(**partition_information_indexes_model_dict) # Verify the model instances are equivalent assert partition_information_indexes_model == partition_information_indexes_model2 # Convert model instance back to dict and verify no loss of data partition_information_indexes_model_json2 = partition_information_indexes_model.to_dict() assert partition_information_indexes_model_json2 == partition_information_indexes_model_json class TestModel_PartitionInformationIndexesIndexes(): def test_partition_information_indexes_indexes_serialization(self): # Construct a json representation of a PartitionInformationIndexesIndexes model partition_information_indexes_indexes_model_json = {} partition_information_indexes_indexes_model_json['search'] = 0 partition_information_indexes_indexes_model_json['view'] = 0 # Construct a model instance of PartitionInformationIndexesIndexes by calling from_dict on the json representation partition_information_indexes_indexes_model = PartitionInformationIndexesIndexes.from_dict(partition_information_indexes_indexes_model_json) assert partition_information_indexes_indexes_model != False # Construct a model instance of PartitionInformationIndexesIndexes by calling from_dict on the json representation partition_information_indexes_indexes_model_dict = PartitionInformationIndexesIndexes.from_dict(partition_information_indexes_indexes_model_json).__dict__ partition_information_indexes_indexes_model2 = PartitionInformationIndexesIndexes(**partition_information_indexes_indexes_model_dict) # Verify the model instances are equivalent assert partition_information_indexes_indexes_model == partition_information_indexes_indexes_model2 # Convert model instance back to dict and verify no loss of data partition_information_indexes_indexes_model_json2 = partition_information_indexes_indexes_model.to_dict() assert partition_information_indexes_indexes_model_json2 == partition_information_indexes_indexes_model_json class TestModel_PartitionInformationSizes(): def test_partition_information_sizes_serialization(self): # Construct a json representation of a PartitionInformationSizes model partition_information_sizes_model_json = {} partition_information_sizes_model_json['active'] = 0 partition_information_sizes_model_json['external'] = 0 # Construct a model instance of PartitionInformationSizes by calling from_dict on the json representation partition_information_sizes_model = PartitionInformationSizes.from_dict(partition_information_sizes_model_json) assert partition_information_sizes_model != False # Construct a model instance of PartitionInformationSizes by calling from_dict on the json representation partition_information_sizes_model_dict = PartitionInformationSizes.from_dict(partition_information_sizes_model_json).__dict__ partition_information_sizes_model2 = PartitionInformationSizes(**partition_information_sizes_model_dict) # Verify the model instances are equivalent assert partition_information_sizes_model == partition_information_sizes_model2 # Convert model instance back to dict and verify no loss of data partition_information_sizes_model_json2 = partition_information_sizes_model.to_dict() assert partition_information_sizes_model_json2 == partition_information_sizes_model_json class TestModel_ReplicationCreateTargetParameters(): def test_replication_create_target_parameters_serialization(self): # Construct a json representation of a ReplicationCreateTargetParameters model replication_create_target_parameters_model_json = {} replication_create_target_parameters_model_json['n'] = 1 replication_create_target_parameters_model_json['partitioned'] = False replication_create_target_parameters_model_json['q'] = 1 # Construct a model instance of ReplicationCreateTargetParameters by calling from_dict on the json representation replication_create_target_parameters_model = ReplicationCreateTargetParameters.from_dict(replication_create_target_parameters_model_json) assert replication_create_target_parameters_model != False # Construct a model instance of ReplicationCreateTargetParameters by calling from_dict on the json representation replication_create_target_parameters_model_dict = ReplicationCreateTargetParameters.from_dict(replication_create_target_parameters_model_json).__dict__ replication_create_target_parameters_model2 = ReplicationCreateTargetParameters(**replication_create_target_parameters_model_dict) # Verify the model instances are equivalent assert replication_create_target_parameters_model == replication_create_target_parameters_model2 # Convert model instance back to dict and verify no loss of data replication_create_target_parameters_model_json2 = replication_create_target_parameters_model.to_dict() assert replication_create_target_parameters_model_json2 == replication_create_target_parameters_model_json class TestModel_ReplicationDatabase(): def test_replication_database_serialization(self): # Construct dict forms of any model objects needed in order to build this model. replication_database_auth_basic_model = {} # ReplicationDatabaseAuthBasic replication_database_auth_basic_model['password'] = 'testString' replication_database_auth_basic_model['username'] = 'testString' replication_database_auth_iam_model = {} # ReplicationDatabaseAuthIam replication_database_auth_iam_model['api_key'] = 'testString' replication_database_auth_model = {} # ReplicationDatabaseAuth replication_database_auth_model['basic'] = replication_database_auth_basic_model replication_database_auth_model['iam'] = replication_database_auth_iam_model # Construct a json representation of a ReplicationDatabase model replication_database_model_json = {} replication_database_model_json['auth'] = replication_database_auth_model replication_database_model_json['headers'] = {} replication_database_model_json['url'] = 'testString' # Construct a model instance of ReplicationDatabase by calling from_dict on the json representation replication_database_model = ReplicationDatabase.from_dict(replication_database_model_json) assert replication_database_model != False # Construct a model instance of ReplicationDatabase by calling from_dict on the json representation replication_database_model_dict = ReplicationDatabase.from_dict(replication_database_model_json).__dict__ replication_database_model2 = ReplicationDatabase(**replication_database_model_dict) # Verify the model instances are equivalent assert replication_database_model == replication_database_model2 # Convert model instance back to dict and verify no loss of data replication_database_model_json2 = replication_database_model.to_dict() assert replication_database_model_json2 == replication_database_model_json class TestModel_ReplicationDatabaseAuth(): def test_replication_database_auth_serialization(self): # Construct dict forms of any model objects needed in order to build this model. replication_database_auth_basic_model = {} # ReplicationDatabaseAuthBasic replication_database_auth_basic_model['password'] = 'testString' replication_database_auth_basic_model['username'] = 'testString' replication_database_auth_iam_model = {} # ReplicationDatabaseAuthIam replication_database_auth_iam_model['api_key'] = 'testString' # Construct a json representation of a ReplicationDatabaseAuth model replication_database_auth_model_json = {} replication_database_auth_model_json['basic'] = replication_database_auth_basic_model replication_database_auth_model_json['iam'] = replication_database_auth_iam_model # Construct a model instance of ReplicationDatabaseAuth by calling from_dict on the json representation replication_database_auth_model = ReplicationDatabaseAuth.from_dict(replication_database_auth_model_json) assert replication_database_auth_model != False # Construct a model instance of ReplicationDatabaseAuth by calling from_dict on the json representation replication_database_auth_model_dict = ReplicationDatabaseAuth.from_dict(replication_database_auth_model_json).__dict__ replication_database_auth_model2 = ReplicationDatabaseAuth(**replication_database_auth_model_dict) # Verify the model instances are equivalent assert replication_database_auth_model == replication_database_auth_model2 # Convert model instance back to dict and verify no loss of data replication_database_auth_model_json2 = replication_database_auth_model.to_dict() assert replication_database_auth_model_json2 == replication_database_auth_model_json class TestModel_ReplicationDatabaseAuthBasic(): def test_replication_database_auth_basic_serialization(self): # Construct a json representation of a ReplicationDatabaseAuthBasic model replication_database_auth_basic_model_json = {} replication_database_auth_basic_model_json['password'] = 'testString' replication_database_auth_basic_model_json['username'] = 'testString' # Construct a model instance of ReplicationDatabaseAuthBasic by calling from_dict on the json representation replication_database_auth_basic_model = ReplicationDatabaseAuthBasic.from_dict(replication_database_auth_basic_model_json) assert replication_database_auth_basic_model != False # Construct a model instance of ReplicationDatabaseAuthBasic by calling from_dict on the json representation replication_database_auth_basic_model_dict = ReplicationDatabaseAuthBasic.from_dict(replication_database_auth_basic_model_json).__dict__ replication_database_auth_basic_model2 = ReplicationDatabaseAuthBasic(**replication_database_auth_basic_model_dict) # Verify the model instances are equivalent assert replication_database_auth_basic_model == replication_database_auth_basic_model2 # Convert model instance back to dict and verify no loss of data replication_database_auth_basic_model_json2 = replication_database_auth_basic_model.to_dict() assert replication_database_auth_basic_model_json2 == replication_database_auth_basic_model_json class TestModel_ReplicationDatabaseAuthIam(): def test_replication_database_auth_iam_serialization(self): # Construct a json representation of a ReplicationDatabaseAuthIam model replication_database_auth_iam_model_json = {} replication_database_auth_iam_model_json['api_key'] = 'testString' # Construct a model instance of ReplicationDatabaseAuthIam by calling from_dict on the json representation replication_database_auth_iam_model = ReplicationDatabaseAuthIam.from_dict(replication_database_auth_iam_model_json) assert replication_database_auth_iam_model != False # Construct a model instance of ReplicationDatabaseAuthIam by calling from_dict on the json representation replication_database_auth_iam_model_dict = ReplicationDatabaseAuthIam.from_dict(replication_database_auth_iam_model_json).__dict__ replication_database_auth_iam_model2 = ReplicationDatabaseAuthIam(**replication_database_auth_iam_model_dict) # Verify the model instances are equivalent assert replication_database_auth_iam_model == replication_database_auth_iam_model2 # Convert model instance back to dict and verify no loss of data replication_database_auth_iam_model_json2 = replication_database_auth_iam_model.to_dict() assert replication_database_auth_iam_model_json2 == replication_database_auth_iam_model_json class TestModel_ReplicationDocument(): def test_replication_document_serialization(self): # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' replication_create_target_parameters_model = {} # ReplicationCreateTargetParameters replication_create_target_parameters_model['n'] = 1 replication_create_target_parameters_model['partitioned'] = False replication_create_target_parameters_model['q'] = 1 replication_database_auth_basic_model = {} # ReplicationDatabaseAuthBasic replication_database_auth_basic_model['password'] = 'testString' replication_database_auth_basic_model['username'] = 'testString' replication_database_auth_iam_model = {} # ReplicationDatabaseAuthIam replication_database_auth_iam_model['api_key'] = 'testString' replication_database_auth_model = {} # ReplicationDatabaseAuth replication_database_auth_model['basic'] = replication_database_auth_basic_model replication_database_auth_model['iam'] = replication_database_auth_iam_model replication_database_model = {} # ReplicationDatabase replication_database_model['auth'] = replication_database_auth_model replication_database_model['headers'] = {} replication_database_model['url'] = 'testString' user_context_model = {} # UserContext user_context_model['db'] = 'testString' user_context_model['name'] = 'testString' user_context_model['roles'] = ['_reader'] # Construct a json representation of a ReplicationDocument model replication_document_model_json = {} replication_document_model_json['_attachments'] = {} replication_document_model_json['_conflicts'] = ['testString'] replication_document_model_json['_deleted'] = True replication_document_model_json['_deleted_conflicts'] = ['testString'] replication_document_model_json['_id'] = 'testString' replication_document_model_json['_local_seq'] = 'testString' replication_document_model_json['_rev'] = 'testString' replication_document_model_json['_revisions'] = revisions_model replication_document_model_json['_revs_info'] = [document_revision_status_model] replication_document_model_json['cancel'] = True replication_document_model_json['checkpoint_interval'] = 0 replication_document_model_json['connection_timeout'] = 0 replication_document_model_json['continuous'] = False replication_document_model_json['create_target'] = False replication_document_model_json['create_target_params'] = replication_create_target_parameters_model replication_document_model_json['doc_ids'] = ['testString'] replication_document_model_json['filter'] = 'testString' replication_document_model_json['http_connections'] = 1 replication_document_model_json['query_params'] = {} replication_document_model_json['retries_per_request'] = 0 replication_document_model_json['selector'] = {} replication_document_model_json['since_seq'] = 'testString' replication_document_model_json['socket_options'] = 'testString' replication_document_model_json['source'] = replication_database_model replication_document_model_json['source_proxy'] = 'testString' replication_document_model_json['target'] = replication_database_model replication_document_model_json['target_proxy'] = 'testString' replication_document_model_json['use_checkpoints'] = True replication_document_model_json['user_ctx'] = user_context_model replication_document_model_json['worker_batch_size'] = 1 replication_document_model_json['worker_processes'] = 1 replication_document_model_json['foo'] = 'testString' # Construct a model instance of ReplicationDocument by calling from_dict on the json representation replication_document_model = ReplicationDocument.from_dict(replication_document_model_json) assert replication_document_model != False # Construct a model instance of ReplicationDocument by calling from_dict on the json representation replication_document_model_dict = ReplicationDocument.from_dict(replication_document_model_json).__dict__ replication_document_model2 = ReplicationDocument(**replication_document_model_dict) # Verify the model instances are equivalent assert replication_document_model == replication_document_model2 # Convert model instance back to dict and verify no loss of data replication_document_model_json2 = replication_document_model.to_dict() assert replication_document_model_json2 == replication_document_model_json # Test get_properties and set_properties methods. replication_document_model.set_properties({}) actual_dict = replication_document_model.get_properties() assert actual_dict == {} expected_dict = {'foo': 'testString'} replication_document_model.set_properties(expected_dict) actual_dict = replication_document_model.get_properties() assert actual_dict == expected_dict class TestModel_Revisions(): def test_revisions_serialization(self): # Construct a json representation of a Revisions model revisions_model_json = {} revisions_model_json['ids'] = ['testString'] revisions_model_json['start'] = 1 # Construct a model instance of Revisions by calling from_dict on the json representation revisions_model = Revisions.from_dict(revisions_model_json) assert revisions_model != False # Construct a model instance of Revisions by calling from_dict on the json representation revisions_model_dict = Revisions.from_dict(revisions_model_json).__dict__ revisions_model2 = Revisions(**revisions_model_dict) # Verify the model instances are equivalent assert revisions_model == revisions_model2 # Convert model instance back to dict and verify no loss of data revisions_model_json2 = revisions_model.to_dict() assert revisions_model_json2 == revisions_model_json class TestModel_RevsDiff(): def test_revs_diff_serialization(self): # Construct a json representation of a RevsDiff model revs_diff_model_json = {} revs_diff_model_json['missing'] = ['testString'] revs_diff_model_json['possible_ancestors'] = ['testString'] # Construct a model instance of RevsDiff by calling from_dict on the json representation revs_diff_model = RevsDiff.from_dict(revs_diff_model_json) assert revs_diff_model != False # Construct a model instance of RevsDiff by calling from_dict on the json representation revs_diff_model_dict = RevsDiff.from_dict(revs_diff_model_json).__dict__ revs_diff_model2 = RevsDiff(**revs_diff_model_dict) # Verify the model instances are equivalent assert revs_diff_model == revs_diff_model2 # Convert model instance back to dict and verify no loss of data revs_diff_model_json2 = revs_diff_model.to_dict() assert revs_diff_model_json2 == revs_diff_model_json class TestModel_SchedulerDocsResult(): def test_scheduler_docs_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. scheduler_info_model = {} # SchedulerInfo scheduler_info_model['changes_pending'] = 0 scheduler_info_model['checkpointed_source_seq'] = 'testString' scheduler_info_model['doc_write_failures'] = 0 scheduler_info_model['docs_read'] = 0 scheduler_info_model['docs_written'] = 0 scheduler_info_model['error'] = 'testString' scheduler_info_model['missing_revisions_found'] = 0 scheduler_info_model['revisions_checked'] = 0 scheduler_info_model['source_seq'] = 'testString' scheduler_info_model['through_seq'] = 'testString' scheduler_document_model = {} # SchedulerDocument scheduler_document_model['database'] = 'testString' scheduler_document_model['doc_id'] = 'testString' scheduler_document_model['error_count'] = 0 scheduler_document_model['id'] = 'testString' scheduler_document_model['info'] = scheduler_info_model scheduler_document_model['last_updated'] = "2019-01-01T12:00:00Z" scheduler_document_model['node'] = 'testString' scheduler_document_model['source'] = 'testString' scheduler_document_model['source_proxy'] = 'testString' scheduler_document_model['start_time'] = "2019-01-01T12:00:00Z" scheduler_document_model['state'] = 'initializing' scheduler_document_model['target'] = 'testString' scheduler_document_model['target_proxy'] = 'testString' # Construct a json representation of a SchedulerDocsResult model scheduler_docs_result_model_json = {} scheduler_docs_result_model_json['total_rows'] = 0 scheduler_docs_result_model_json['docs'] = [scheduler_document_model] # Construct a model instance of SchedulerDocsResult by calling from_dict on the json representation scheduler_docs_result_model = SchedulerDocsResult.from_dict(scheduler_docs_result_model_json) assert scheduler_docs_result_model != False # Construct a model instance of SchedulerDocsResult by calling from_dict on the json representation scheduler_docs_result_model_dict = SchedulerDocsResult.from_dict(scheduler_docs_result_model_json).__dict__ scheduler_docs_result_model2 = SchedulerDocsResult(**scheduler_docs_result_model_dict) # Verify the model instances are equivalent assert scheduler_docs_result_model == scheduler_docs_result_model2 # Convert model instance back to dict and verify no loss of data scheduler_docs_result_model_json2 = scheduler_docs_result_model.to_dict() assert scheduler_docs_result_model_json2 == scheduler_docs_result_model_json class TestModel_SchedulerDocument(): def test_scheduler_document_serialization(self): # Construct dict forms of any model objects needed in order to build this model. scheduler_info_model = {} # SchedulerInfo scheduler_info_model['changes_pending'] = 0 scheduler_info_model['checkpointed_source_seq'] = 'testString' scheduler_info_model['doc_write_failures'] = 0 scheduler_info_model['docs_read'] = 0 scheduler_info_model['docs_written'] = 0 scheduler_info_model['error'] = 'testString' scheduler_info_model['missing_revisions_found'] = 0 scheduler_info_model['revisions_checked'] = 0 scheduler_info_model['source_seq'] = 'testString' scheduler_info_model['through_seq'] = 'testString' # Construct a json representation of a SchedulerDocument model scheduler_document_model_json = {} scheduler_document_model_json['database'] = 'testString' scheduler_document_model_json['doc_id'] = 'testString' scheduler_document_model_json['error_count'] = 0 scheduler_document_model_json['id'] = 'testString' scheduler_document_model_json['info'] = scheduler_info_model scheduler_document_model_json['last_updated'] = "2019-01-01T12:00:00Z" scheduler_document_model_json['node'] = 'testString' scheduler_document_model_json['source'] = 'testString' scheduler_document_model_json['source_proxy'] = 'testString' scheduler_document_model_json['start_time'] = "2019-01-01T12:00:00Z" scheduler_document_model_json['state'] = 'initializing' scheduler_document_model_json['target'] = 'testString' scheduler_document_model_json['target_proxy'] = 'testString' # Construct a model instance of SchedulerDocument by calling from_dict on the json representation scheduler_document_model = SchedulerDocument.from_dict(scheduler_document_model_json) assert scheduler_document_model != False # Construct a model instance of SchedulerDocument by calling from_dict on the json representation scheduler_document_model_dict = SchedulerDocument.from_dict(scheduler_document_model_json).__dict__ scheduler_document_model2 = SchedulerDocument(**scheduler_document_model_dict) # Verify the model instances are equivalent assert scheduler_document_model == scheduler_document_model2 # Convert model instance back to dict and verify no loss of data scheduler_document_model_json2 = scheduler_document_model.to_dict() assert scheduler_document_model_json2 == scheduler_document_model_json class TestModel_SchedulerInfo(): def test_scheduler_info_serialization(self): # Construct a json representation of a SchedulerInfo model scheduler_info_model_json = {} scheduler_info_model_json['changes_pending'] = 0 scheduler_info_model_json['checkpointed_source_seq'] = 'testString' scheduler_info_model_json['doc_write_failures'] = 0 scheduler_info_model_json['docs_read'] = 0 scheduler_info_model_json['docs_written'] = 0 scheduler_info_model_json['error'] = 'testString' scheduler_info_model_json['missing_revisions_found'] = 0 scheduler_info_model_json['revisions_checked'] = 0 scheduler_info_model_json['source_seq'] = 'testString' scheduler_info_model_json['through_seq'] = 'testString' # Construct a model instance of SchedulerInfo by calling from_dict on the json representation scheduler_info_model = SchedulerInfo.from_dict(scheduler_info_model_json) assert scheduler_info_model != False # Construct a model instance of SchedulerInfo by calling from_dict on the json representation scheduler_info_model_dict = SchedulerInfo.from_dict(scheduler_info_model_json).__dict__ scheduler_info_model2 = SchedulerInfo(**scheduler_info_model_dict) # Verify the model instances are equivalent assert scheduler_info_model == scheduler_info_model2 # Convert model instance back to dict and verify no loss of data scheduler_info_model_json2 = scheduler_info_model.to_dict() assert scheduler_info_model_json2 == scheduler_info_model_json class TestModel_SchedulerJob(): def test_scheduler_job_serialization(self): # Construct dict forms of any model objects needed in order to build this model. scheduler_job_event_model = {} # SchedulerJobEvent scheduler_job_event_model['reason'] = 'testString' scheduler_job_event_model['timestamp'] = "2019-01-01T12:00:00Z" scheduler_job_event_model['type'] = 'testString' scheduler_info_model = {} # SchedulerInfo scheduler_info_model['changes_pending'] = 0 scheduler_info_model['checkpointed_source_seq'] = 'testString' scheduler_info_model['doc_write_failures'] = 0 scheduler_info_model['docs_read'] = 0 scheduler_info_model['docs_written'] = 0 scheduler_info_model['error'] = 'testString' scheduler_info_model['missing_revisions_found'] = 0 scheduler_info_model['revisions_checked'] = 0 scheduler_info_model['source_seq'] = 'testString' scheduler_info_model['through_seq'] = 'testString' # Construct a json representation of a SchedulerJob model scheduler_job_model_json = {} scheduler_job_model_json['database'] = 'testString' scheduler_job_model_json['doc_id'] = 'testString' scheduler_job_model_json['history'] = [scheduler_job_event_model] scheduler_job_model_json['id'] = 'testString' scheduler_job_model_json['info'] = scheduler_info_model scheduler_job_model_json['node'] = 'testString' scheduler_job_model_json['pid'] = 'testString' scheduler_job_model_json['source'] = 'testString' scheduler_job_model_json['start_time'] = "2019-01-01T12:00:00Z" scheduler_job_model_json['target'] = 'testString' scheduler_job_model_json['user'] = 'testString' # Construct a model instance of SchedulerJob by calling from_dict on the json representation scheduler_job_model = SchedulerJob.from_dict(scheduler_job_model_json) assert scheduler_job_model != False # Construct a model instance of SchedulerJob by calling from_dict on the json representation scheduler_job_model_dict = SchedulerJob.from_dict(scheduler_job_model_json).__dict__ scheduler_job_model2 = SchedulerJob(**scheduler_job_model_dict) # Verify the model instances are equivalent assert scheduler_job_model == scheduler_job_model2 # Convert model instance back to dict and verify no loss of data scheduler_job_model_json2 = scheduler_job_model.to_dict() assert scheduler_job_model_json2 == scheduler_job_model_json class TestModel_SchedulerJobEvent(): def test_scheduler_job_event_serialization(self): # Construct a json representation of a SchedulerJobEvent model scheduler_job_event_model_json = {} scheduler_job_event_model_json['reason'] = 'testString' scheduler_job_event_model_json['timestamp'] = "2019-01-01T12:00:00Z" scheduler_job_event_model_json['type'] = 'testString' # Construct a model instance of SchedulerJobEvent by calling from_dict on the json representation scheduler_job_event_model = SchedulerJobEvent.from_dict(scheduler_job_event_model_json) assert scheduler_job_event_model != False # Construct a model instance of SchedulerJobEvent by calling from_dict on the json representation scheduler_job_event_model_dict = SchedulerJobEvent.from_dict(scheduler_job_event_model_json).__dict__ scheduler_job_event_model2 = SchedulerJobEvent(**scheduler_job_event_model_dict) # Verify the model instances are equivalent assert scheduler_job_event_model == scheduler_job_event_model2 # Convert model instance back to dict and verify no loss of data scheduler_job_event_model_json2 = scheduler_job_event_model.to_dict() assert scheduler_job_event_model_json2 == scheduler_job_event_model_json class TestModel_SchedulerJobsResult(): def test_scheduler_jobs_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. scheduler_job_event_model = {} # SchedulerJobEvent scheduler_job_event_model['reason'] = 'testString' scheduler_job_event_model['timestamp'] = "2019-01-01T12:00:00Z" scheduler_job_event_model['type'] = 'testString' scheduler_info_model = {} # SchedulerInfo scheduler_info_model['changes_pending'] = 0 scheduler_info_model['checkpointed_source_seq'] = 'testString' scheduler_info_model['doc_write_failures'] = 0 scheduler_info_model['docs_read'] = 0 scheduler_info_model['docs_written'] = 0 scheduler_info_model['error'] = 'testString' scheduler_info_model['missing_revisions_found'] = 0 scheduler_info_model['revisions_checked'] = 0 scheduler_info_model['source_seq'] = 'testString' scheduler_info_model['through_seq'] = 'testString' scheduler_job_model = {} # SchedulerJob scheduler_job_model['database'] = 'testString' scheduler_job_model['doc_id'] = 'testString' scheduler_job_model['history'] = [scheduler_job_event_model] scheduler_job_model['id'] = 'testString' scheduler_job_model['info'] = scheduler_info_model scheduler_job_model['node'] = 'testString' scheduler_job_model['pid'] = 'testString' scheduler_job_model['source'] = 'testString' scheduler_job_model['start_time'] = "2019-01-01T12:00:00Z" scheduler_job_model['target'] = 'testString' scheduler_job_model['user'] = 'testString' # Construct a json representation of a SchedulerJobsResult model scheduler_jobs_result_model_json = {} scheduler_jobs_result_model_json['total_rows'] = 0 scheduler_jobs_result_model_json['jobs'] = [scheduler_job_model] # Construct a model instance of SchedulerJobsResult by calling from_dict on the json representation scheduler_jobs_result_model = SchedulerJobsResult.from_dict(scheduler_jobs_result_model_json) assert scheduler_jobs_result_model != False # Construct a model instance of SchedulerJobsResult by calling from_dict on the json representation scheduler_jobs_result_model_dict = SchedulerJobsResult.from_dict(scheduler_jobs_result_model_json).__dict__ scheduler_jobs_result_model2 = SchedulerJobsResult(**scheduler_jobs_result_model_dict) # Verify the model instances are equivalent assert scheduler_jobs_result_model == scheduler_jobs_result_model2 # Convert model instance back to dict and verify no loss of data scheduler_jobs_result_model_json2 = scheduler_jobs_result_model.to_dict() assert scheduler_jobs_result_model_json2 == scheduler_jobs_result_model_json class TestModel_SearchAnalyzeResult(): def test_search_analyze_result_serialization(self): # Construct a json representation of a SearchAnalyzeResult model search_analyze_result_model_json = {} search_analyze_result_model_json['tokens'] = ['testString'] # Construct a model instance of SearchAnalyzeResult by calling from_dict on the json representation search_analyze_result_model = SearchAnalyzeResult.from_dict(search_analyze_result_model_json) assert search_analyze_result_model != False # Construct a model instance of SearchAnalyzeResult by calling from_dict on the json representation search_analyze_result_model_dict = SearchAnalyzeResult.from_dict(search_analyze_result_model_json).__dict__ search_analyze_result_model2 = SearchAnalyzeResult(**search_analyze_result_model_dict) # Verify the model instances are equivalent assert search_analyze_result_model == search_analyze_result_model2 # Convert model instance back to dict and verify no loss of data search_analyze_result_model_json2 = search_analyze_result_model.to_dict() assert search_analyze_result_model_json2 == search_analyze_result_model_json class TestModel_SearchIndexDefinition(): def test_search_index_definition_serialization(self): # Construct dict forms of any model objects needed in order to build this model. analyzer_model = {} # Analyzer analyzer_model['name'] = 'classic' analyzer_model['stopwords'] = ['testString'] analyzer_configuration_model = {} # AnalyzerConfiguration analyzer_configuration_model['name'] = 'classic' analyzer_configuration_model['stopwords'] = ['testString'] analyzer_configuration_model['fields'] = {} # Construct a json representation of a SearchIndexDefinition model search_index_definition_model_json = {} search_index_definition_model_json['analyzer'] = analyzer_configuration_model search_index_definition_model_json['index'] = 'testString' # Construct a model instance of SearchIndexDefinition by calling from_dict on the json representation search_index_definition_model = SearchIndexDefinition.from_dict(search_index_definition_model_json) assert search_index_definition_model != False # Construct a model instance of SearchIndexDefinition by calling from_dict on the json representation search_index_definition_model_dict = SearchIndexDefinition.from_dict(search_index_definition_model_json).__dict__ search_index_definition_model2 = SearchIndexDefinition(**search_index_definition_model_dict) # Verify the model instances are equivalent assert search_index_definition_model == search_index_definition_model2 # Convert model instance back to dict and verify no loss of data search_index_definition_model_json2 = search_index_definition_model.to_dict() assert search_index_definition_model_json2 == search_index_definition_model_json class TestModel_SearchIndexInfo(): def test_search_index_info_serialization(self): # Construct a json representation of a SearchIndexInfo model search_index_info_model_json = {} search_index_info_model_json['committed_seq'] = 26 search_index_info_model_json['disk_size'] = 0 search_index_info_model_json['doc_count'] = 0 search_index_info_model_json['doc_del_count'] = 0 search_index_info_model_json['pending_seq'] = 26 # Construct a model instance of SearchIndexInfo by calling from_dict on the json representation search_index_info_model = SearchIndexInfo.from_dict(search_index_info_model_json) assert search_index_info_model != False # Construct a model instance of SearchIndexInfo by calling from_dict on the json representation search_index_info_model_dict = SearchIndexInfo.from_dict(search_index_info_model_json).__dict__ search_index_info_model2 = SearchIndexInfo(**search_index_info_model_dict) # Verify the model instances are equivalent assert search_index_info_model == search_index_info_model2 # Convert model instance back to dict and verify no loss of data search_index_info_model_json2 = search_index_info_model.to_dict() assert search_index_info_model_json2 == search_index_info_model_json class TestModel_SearchInfoResult(): def test_search_info_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. search_index_info_model = {} # SearchIndexInfo search_index_info_model['committed_seq'] = 26 search_index_info_model['disk_size'] = 0 search_index_info_model['doc_count'] = 0 search_index_info_model['doc_del_count'] = 0 search_index_info_model['pending_seq'] = 26 # Construct a json representation of a SearchInfoResult model search_info_result_model_json = {} search_info_result_model_json['name'] = 'testString' search_info_result_model_json['search_index'] = search_index_info_model # Construct a model instance of SearchInfoResult by calling from_dict on the json representation search_info_result_model = SearchInfoResult.from_dict(search_info_result_model_json) assert search_info_result_model != False # Construct a model instance of SearchInfoResult by calling from_dict on the json representation search_info_result_model_dict = SearchInfoResult.from_dict(search_info_result_model_json).__dict__ search_info_result_model2 = SearchInfoResult(**search_info_result_model_dict) # Verify the model instances are equivalent assert search_info_result_model == search_info_result_model2 # Convert model instance back to dict and verify no loss of data search_info_result_model_json2 = search_info_result_model.to_dict() assert search_info_result_model_json2 == search_info_result_model_json class TestModel_SearchResult(): def test_search_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' search_result_row_model = {} # SearchResultRow search_result_row_model['doc'] = document_model search_result_row_model['fields'] = {} search_result_row_model['highlights'] = {} search_result_row_model['id'] = 'testString' search_result_properties_model = {} # SearchResultProperties search_result_properties_model['total_rows'] = 0 search_result_properties_model['bookmark'] = 'testString' search_result_properties_model['by'] = 'testString' search_result_properties_model['counts'] = {} search_result_properties_model['ranges'] = {} search_result_properties_model['rows'] = [search_result_row_model] # Construct a json representation of a SearchResult model search_result_model_json = {} search_result_model_json['total_rows'] = 0 search_result_model_json['bookmark'] = 'testString' search_result_model_json['by'] = 'testString' search_result_model_json['counts'] = {} search_result_model_json['ranges'] = {} search_result_model_json['rows'] = [search_result_row_model] search_result_model_json['groups'] = [search_result_properties_model] # Construct a model instance of SearchResult by calling from_dict on the json representation search_result_model = SearchResult.from_dict(search_result_model_json) assert search_result_model != False # Construct a model instance of SearchResult by calling from_dict on the json representation search_result_model_dict = SearchResult.from_dict(search_result_model_json).__dict__ search_result_model2 = SearchResult(**search_result_model_dict) # Verify the model instances are equivalent assert search_result_model == search_result_model2 # Convert model instance back to dict and verify no loss of data search_result_model_json2 = search_result_model.to_dict() assert search_result_model_json2 == search_result_model_json class TestModel_SearchResultProperties(): def test_search_result_properties_serialization(self): # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' search_result_row_model = {} # SearchResultRow search_result_row_model['doc'] = document_model search_result_row_model['fields'] = {} search_result_row_model['highlights'] = {} search_result_row_model['id'] = 'testString' # Construct a json representation of a SearchResultProperties model search_result_properties_model_json = {} search_result_properties_model_json['total_rows'] = 0 search_result_properties_model_json['bookmark'] = 'testString' search_result_properties_model_json['by'] = 'testString' search_result_properties_model_json['counts'] = {} search_result_properties_model_json['ranges'] = {} search_result_properties_model_json['rows'] = [search_result_row_model] # Construct a model instance of SearchResultProperties by calling from_dict on the json representation search_result_properties_model = SearchResultProperties.from_dict(search_result_properties_model_json) assert search_result_properties_model != False # Construct a model instance of SearchResultProperties by calling from_dict on the json representation search_result_properties_model_dict = SearchResultProperties.from_dict(search_result_properties_model_json).__dict__ search_result_properties_model2 = SearchResultProperties(**search_result_properties_model_dict) # Verify the model instances are equivalent assert search_result_properties_model == search_result_properties_model2 # Convert model instance back to dict and verify no loss of data search_result_properties_model_json2 = search_result_properties_model.to_dict() assert search_result_properties_model_json2 == search_result_properties_model_json class TestModel_SearchResultRow(): def test_search_result_row_serialization(self): # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' # Construct a json representation of a SearchResultRow model search_result_row_model_json = {} search_result_row_model_json['doc'] = document_model search_result_row_model_json['fields'] = {} search_result_row_model_json['highlights'] = {} search_result_row_model_json['id'] = 'testString' # Construct a model instance of SearchResultRow by calling from_dict on the json representation search_result_row_model = SearchResultRow.from_dict(search_result_row_model_json) assert search_result_row_model != False # Construct a model instance of SearchResultRow by calling from_dict on the json representation search_result_row_model_dict = SearchResultRow.from_dict(search_result_row_model_json).__dict__ search_result_row_model2 = SearchResultRow(**search_result_row_model_dict) # Verify the model instances are equivalent assert search_result_row_model == search_result_row_model2 # Convert model instance back to dict and verify no loss of data search_result_row_model_json2 = search_result_row_model.to_dict() assert search_result_row_model_json2 == search_result_row_model_json class TestModel_Security(): def test_security_serialization(self): # Construct dict forms of any model objects needed in order to build this model. security_object_model = {} # SecurityObject security_object_model['names'] = ['testString'] security_object_model['roles'] = ['testString'] # Construct a json representation of a Security model security_model_json = {} security_model_json['admins'] = security_object_model security_model_json['members'] = security_object_model security_model_json['cloudant'] = {} security_model_json['couchdb_auth_only'] = True # Construct a model instance of Security by calling from_dict on the json representation security_model = Security.from_dict(security_model_json) assert security_model != False # Construct a model instance of Security by calling from_dict on the json representation security_model_dict = Security.from_dict(security_model_json).__dict__ security_model2 = Security(**security_model_dict) # Verify the model instances are equivalent assert security_model == security_model2 # Convert model instance back to dict and verify no loss of data security_model_json2 = security_model.to_dict() assert security_model_json2 == security_model_json class TestModel_SecurityObject(): def test_security_object_serialization(self): # Construct a json representation of a SecurityObject model security_object_model_json = {} security_object_model_json['names'] = ['testString'] security_object_model_json['roles'] = ['testString'] # Construct a model instance of SecurityObject by calling from_dict on the json representation security_object_model = SecurityObject.from_dict(security_object_model_json) assert security_object_model != False # Construct a model instance of SecurityObject by calling from_dict on the json representation security_object_model_dict = SecurityObject.from_dict(security_object_model_json).__dict__ security_object_model2 = SecurityObject(**security_object_model_dict) # Verify the model instances are equivalent assert security_object_model == security_object_model2 # Convert model instance back to dict and verify no loss of data security_object_model_json2 = security_object_model.to_dict() assert security_object_model_json2 == security_object_model_json class TestModel_ServerInformation(): def test_server_information_serialization(self): # Construct dict forms of any model objects needed in order to build this model. server_vendor_model = {} # ServerVendor server_vendor_model['name'] = 'testString' server_vendor_model['variant'] = 'testString' server_vendor_model['version'] = 'testString' # Construct a json representation of a ServerInformation model server_information_model_json = {} server_information_model_json['couchdb'] = 'testString' server_information_model_json['features'] = ['testString'] server_information_model_json['vendor'] = server_vendor_model server_information_model_json['version'] = 'testString' server_information_model_json['features_flags'] = ['testString'] # Construct a model instance of ServerInformation by calling from_dict on the json representation server_information_model = ServerInformation.from_dict(server_information_model_json) assert server_information_model != False # Construct a model instance of ServerInformation by calling from_dict on the json representation server_information_model_dict = ServerInformation.from_dict(server_information_model_json).__dict__ server_information_model2 = ServerInformation(**server_information_model_dict) # Verify the model instances are equivalent assert server_information_model == server_information_model2 # Convert model instance back to dict and verify no loss of data server_information_model_json2 = server_information_model.to_dict() assert server_information_model_json2 == server_information_model_json class TestModel_ServerVendor(): def test_server_vendor_serialization(self): # Construct a json representation of a ServerVendor model server_vendor_model_json = {} server_vendor_model_json['name'] = 'testString' server_vendor_model_json['variant'] = 'testString' server_vendor_model_json['version'] = 'testString' # Construct a model instance of ServerVendor by calling from_dict on the json representation server_vendor_model = ServerVendor.from_dict(server_vendor_model_json) assert server_vendor_model != False # Construct a model instance of ServerVendor by calling from_dict on the json representation server_vendor_model_dict = ServerVendor.from_dict(server_vendor_model_json).__dict__ server_vendor_model2 = ServerVendor(**server_vendor_model_dict) # Verify the model instances are equivalent assert server_vendor_model == server_vendor_model2 # Convert model instance back to dict and verify no loss of data server_vendor_model_json2 = server_vendor_model.to_dict() assert server_vendor_model_json2 == server_vendor_model_json class TestModel_SessionAuthentication(): def test_session_authentication_serialization(self): # Construct a json representation of a SessionAuthentication model session_authentication_model_json = {} session_authentication_model_json['authenticated'] = 'testString' session_authentication_model_json['authentication_db'] = 'testString' session_authentication_model_json['authentication_handlers'] = ['testString'] # Construct a model instance of SessionAuthentication by calling from_dict on the json representation session_authentication_model = SessionAuthentication.from_dict(session_authentication_model_json) assert session_authentication_model != False # Construct a model instance of SessionAuthentication by calling from_dict on the json representation session_authentication_model_dict = SessionAuthentication.from_dict(session_authentication_model_json).__dict__ session_authentication_model2 = SessionAuthentication(**session_authentication_model_dict) # Verify the model instances are equivalent assert session_authentication_model == session_authentication_model2 # Convert model instance back to dict and verify no loss of data session_authentication_model_json2 = session_authentication_model.to_dict() assert session_authentication_model_json2 == session_authentication_model_json class TestModel_SessionInformation(): def test_session_information_serialization(self): # Construct dict forms of any model objects needed in order to build this model. session_authentication_model = {} # SessionAuthentication session_authentication_model['authenticated'] = 'testString' session_authentication_model['authentication_db'] = 'testString' session_authentication_model['authentication_handlers'] = ['testString'] user_context_model = {} # UserContext user_context_model['db'] = 'testString' user_context_model['name'] = 'testString' user_context_model['roles'] = ['_reader'] # Construct a json representation of a SessionInformation model session_information_model_json = {} session_information_model_json['ok'] = True session_information_model_json['info'] = session_authentication_model session_information_model_json['userCtx'] = user_context_model # Construct a model instance of SessionInformation by calling from_dict on the json representation session_information_model = SessionInformation.from_dict(session_information_model_json) assert session_information_model != False # Construct a model instance of SessionInformation by calling from_dict on the json representation session_information_model_dict = SessionInformation.from_dict(session_information_model_json).__dict__ session_information_model2 = SessionInformation(**session_information_model_dict) # Verify the model instances are equivalent assert session_information_model == session_information_model2 # Convert model instance back to dict and verify no loss of data session_information_model_json2 = session_information_model.to_dict() assert session_information_model_json2 == session_information_model_json class TestModel_ShardsInformation(): def test_shards_information_serialization(self): # Construct a json representation of a ShardsInformation model shards_information_model_json = {} shards_information_model_json['shards'] = {} # Construct a model instance of ShardsInformation by calling from_dict on the json representation shards_information_model = ShardsInformation.from_dict(shards_information_model_json) assert shards_information_model != False # Construct a model instance of ShardsInformation by calling from_dict on the json representation shards_information_model_dict = ShardsInformation.from_dict(shards_information_model_json).__dict__ shards_information_model2 = ShardsInformation(**shards_information_model_dict) # Verify the model instances are equivalent assert shards_information_model == shards_information_model2 # Convert model instance back to dict and verify no loss of data shards_information_model_json2 = shards_information_model.to_dict() assert shards_information_model_json2 == shards_information_model_json class TestModel_ThroughputInformation(): def test_throughput_information_serialization(self): # Construct a json representation of a ThroughputInformation model throughput_information_model_json = {} throughput_information_model_json['blocks'] = 0 throughput_information_model_json['query'] = 0 throughput_information_model_json['read'] = 0 throughput_information_model_json['write'] = 0 # Construct a model instance of ThroughputInformation by calling from_dict on the json representation throughput_information_model = ThroughputInformation.from_dict(throughput_information_model_json) assert throughput_information_model != False # Construct a model instance of ThroughputInformation by calling from_dict on the json representation throughput_information_model_dict = ThroughputInformation.from_dict(throughput_information_model_json).__dict__ throughput_information_model2 = ThroughputInformation(**throughput_information_model_dict) # Verify the model instances are equivalent assert throughput_information_model == throughput_information_model2 # Convert model instance back to dict and verify no loss of data throughput_information_model_json2 = throughput_information_model.to_dict() assert throughput_information_model_json2 == throughput_information_model_json class TestModel_UpInformation(): def test_up_information_serialization(self): # Construct a json representation of a UpInformation model up_information_model_json = {} up_information_model_json['seeds'] = { 'foo': 'bar' } up_information_model_json['status'] = 'maintenance_mode' # Construct a model instance of UpInformation by calling from_dict on the json representation up_information_model = UpInformation.from_dict(up_information_model_json) assert up_information_model != False # Construct a model instance of UpInformation by calling from_dict on the json representation up_information_model_dict = UpInformation.from_dict(up_information_model_json).__dict__ up_information_model2 = UpInformation(**up_information_model_dict) # Verify the model instances are equivalent assert up_information_model == up_information_model2 # Convert model instance back to dict and verify no loss of data up_information_model_json2 = up_information_model.to_dict() assert up_information_model_json2 == up_information_model_json class TestModel_UserContext(): def test_user_context_serialization(self): # Construct a json representation of a UserContext model user_context_model_json = {} user_context_model_json['db'] = 'testString' user_context_model_json['name'] = 'testString' user_context_model_json['roles'] = ['_reader'] # Construct a model instance of UserContext by calling from_dict on the json representation user_context_model = UserContext.from_dict(user_context_model_json) assert user_context_model != False # Construct a model instance of UserContext by calling from_dict on the json representation user_context_model_dict = UserContext.from_dict(user_context_model_json).__dict__ user_context_model2 = UserContext(**user_context_model_dict) # Verify the model instances are equivalent assert user_context_model == user_context_model2 # Convert model instance back to dict and verify no loss of data user_context_model_json2 = user_context_model.to_dict() assert user_context_model_json2 == user_context_model_json class TestModel_UuidsResult(): def test_uuids_result_serialization(self): # Construct a json representation of a UuidsResult model uuids_result_model_json = {} uuids_result_model_json['uuids'] = ['testString'] # Construct a model instance of UuidsResult by calling from_dict on the json representation uuids_result_model = UuidsResult.from_dict(uuids_result_model_json) assert uuids_result_model != False # Construct a model instance of UuidsResult by calling from_dict on the json representation uuids_result_model_dict = UuidsResult.from_dict(uuids_result_model_json).__dict__ uuids_result_model2 = UuidsResult(**uuids_result_model_dict) # Verify the model instances are equivalent assert uuids_result_model == uuids_result_model2 # Convert model instance back to dict and verify no loss of data uuids_result_model_json2 = uuids_result_model.to_dict() assert uuids_result_model_json2 == uuids_result_model_json class TestModel_ViewQueriesResult(): def test_view_queries_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' view_result_row_model = {} # ViewResultRow view_result_row_model['caused_by'] = 'testString' view_result_row_model['error'] = 'testString' view_result_row_model['reason'] = 'testString' view_result_row_model['doc'] = document_model view_result_row_model['id'] = 'testString' view_result_row_model['key'] = 'testString' view_result_row_model['value'] = 'testString' view_result_model = {} # ViewResult view_result_model['total_rows'] = 0 view_result_model['update_seq'] = 'testString' view_result_model['rows'] = [view_result_row_model] # Construct a json representation of a ViewQueriesResult model view_queries_result_model_json = {} view_queries_result_model_json['results'] = [view_result_model] # Construct a model instance of ViewQueriesResult by calling from_dict on the json representation view_queries_result_model = ViewQueriesResult.from_dict(view_queries_result_model_json) assert view_queries_result_model != False # Construct a model instance of ViewQueriesResult by calling from_dict on the json representation view_queries_result_model_dict = ViewQueriesResult.from_dict(view_queries_result_model_json).__dict__ view_queries_result_model2 = ViewQueriesResult(**view_queries_result_model_dict) # Verify the model instances are equivalent assert view_queries_result_model == view_queries_result_model2 # Convert model instance back to dict and verify no loss of data view_queries_result_model_json2 = view_queries_result_model.to_dict() assert view_queries_result_model_json2 == view_queries_result_model_json class TestModel_ViewQuery(): def test_view_query_serialization(self): # Construct a json representation of a ViewQuery model view_query_model_json = {} view_query_model_json['att_encoding_info'] = False view_query_model_json['attachments'] = False view_query_model_json['conflicts'] = False view_query_model_json['descending'] = False view_query_model_json['include_docs'] = False view_query_model_json['inclusive_end'] = True view_query_model_json['limit'] = 0 view_query_model_json['skip'] = 0 view_query_model_json['update_seq'] = False view_query_model_json['endkey'] = 'testString' view_query_model_json['endkey_docid'] = 'testString' view_query_model_json['group'] = False view_query_model_json['group_level'] = 1 view_query_model_json['key'] = 'testString' view_query_model_json['keys'] = ['testString'] view_query_model_json['reduce'] = True view_query_model_json['stable'] = False view_query_model_json['startkey'] = 'testString' view_query_model_json['startkey_docid'] = 'testString' view_query_model_json['update'] = 'true' # Construct a model instance of ViewQuery by calling from_dict on the json representation view_query_model = ViewQuery.from_dict(view_query_model_json) assert view_query_model != False # Construct a model instance of ViewQuery by calling from_dict on the json representation view_query_model_dict = ViewQuery.from_dict(view_query_model_json).__dict__ view_query_model2 = ViewQuery(**view_query_model_dict) # Verify the model instances are equivalent assert view_query_model == view_query_model2 # Convert model instance back to dict and verify no loss of data view_query_model_json2 = view_query_model.to_dict() assert view_query_model_json2 == view_query_model_json class TestModel_ViewResult(): def test_view_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' view_result_row_model = {} # ViewResultRow view_result_row_model['caused_by'] = 'testString' view_result_row_model['error'] = 'testString' view_result_row_model['reason'] = 'testString' view_result_row_model['doc'] = document_model view_result_row_model['id'] = 'testString' view_result_row_model['key'] = 'testString' view_result_row_model['value'] = 'testString' # Construct a json representation of a ViewResult model view_result_model_json = {} view_result_model_json['total_rows'] = 0 view_result_model_json['update_seq'] = 'testString' view_result_model_json['rows'] = [view_result_row_model] # Construct a model instance of ViewResult by calling from_dict on the json representation view_result_model = ViewResult.from_dict(view_result_model_json) assert view_result_model != False # Construct a model instance of ViewResult by calling from_dict on the json representation view_result_model_dict = ViewResult.from_dict(view_result_model_json).__dict__ view_result_model2 = ViewResult(**view_result_model_dict) # Verify the model instances are equivalent assert view_result_model == view_result_model2 # Convert model instance back to dict and verify no loss of data view_result_model_json2 = view_result_model.to_dict() assert view_result_model_json2 == view_result_model_json class TestModel_ViewResultRow(): def test_view_result_row_serialization(self): # Construct dict forms of any model objects needed in order to build this model. attachment_model = {} # Attachment attachment_model['content_type'] = 'testString' attachment_model['data'] = 'VGhpcyBpcyBhIG1vY2sgYnl0ZSBhcnJheSB2YWx1ZS4=' attachment_model['digest'] = 'testString' attachment_model['encoded_length'] = 0 attachment_model['encoding'] = 'testString' attachment_model['follows'] = True attachment_model['length'] = 0 attachment_model['revpos'] = 1 attachment_model['stub'] = True revisions_model = {} # Revisions revisions_model['ids'] = ['testString'] revisions_model['start'] = 1 document_revision_status_model = {} # DocumentRevisionStatus document_revision_status_model['rev'] = 'testString' document_revision_status_model['status'] = 'available' document_model = {} # Document document_model['_attachments'] = {} document_model['_conflicts'] = ['testString'] document_model['_deleted'] = True document_model['_deleted_conflicts'] = ['testString'] document_model['_id'] = 'testString' document_model['_local_seq'] = 'testString' document_model['_rev'] = 'testString' document_model['_revisions'] = revisions_model document_model['_revs_info'] = [document_revision_status_model] document_model['foo'] = 'testString' # Construct a json representation of a ViewResultRow model view_result_row_model_json = {} view_result_row_model_json['caused_by'] = 'testString' view_result_row_model_json['error'] = 'testString' view_result_row_model_json['reason'] = 'testString' view_result_row_model_json['doc'] = document_model view_result_row_model_json['id'] = 'testString' view_result_row_model_json['key'] = 'testString' view_result_row_model_json['value'] = 'testString' # Construct a model instance of ViewResultRow by calling from_dict on the json representation view_result_row_model = ViewResultRow.from_dict(view_result_row_model_json) assert view_result_row_model != False # Construct a model instance of ViewResultRow by calling from_dict on the json representation view_result_row_model_dict = ViewResultRow.from_dict(view_result_row_model_json).__dict__ view_result_row_model2 = ViewResultRow(**view_result_row_model_dict) # Verify the model instances are equivalent assert view_result_row_model == view_result_row_model2 # Convert model instance back to dict and verify no loss of data view_result_row_model_json2 = view_result_row_model.to_dict() assert view_result_row_model_json2 == view_result_row_model_json class TestModel_GeoJsonGeometry(): def test_geo_json_geometry_serialization(self): # Construct a json representation of a GeoJsonGeometry model geo_json_geometry_model_json = {} geo_json_geometry_model_json['type'] = 'Point' geo_json_geometry_model_json['coordinates'] = ['testString'] # Construct a model instance of GeoJsonGeometry by calling from_dict on the json representation geo_json_geometry_model = GeoJsonGeometry.from_dict(geo_json_geometry_model_json) assert geo_json_geometry_model != False # Construct a model instance of GeoJsonGeometry by calling from_dict on the json representation geo_json_geometry_model_dict = GeoJsonGeometry.from_dict(geo_json_geometry_model_json).__dict__ geo_json_geometry_model2 = GeoJsonGeometry(**geo_json_geometry_model_dict) # Verify the model instances are equivalent assert geo_json_geometry_model == geo_json_geometry_model2 # Convert model instance back to dict and verify no loss of data geo_json_geometry_model_json2 = geo_json_geometry_model.to_dict() assert geo_json_geometry_model_json2 == geo_json_geometry_model_json class TestModel_GeoJsonGeometryCollection(): def test_geo_json_geometry_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. geo_json_geometry_model = {} # GeoJsonGeometry geo_json_geometry_model['type'] = 'Point' geo_json_geometry_model['coordinates'] = ['testString'] # Construct a json representation of a GeoJsonGeometryCollection model geo_json_geometry_collection_model_json = {} geo_json_geometry_collection_model_json['type'] = 'Point' geo_json_geometry_collection_model_json['geometries'] = [geo_json_geometry_model] # Construct a model instance of GeoJsonGeometryCollection by calling from_dict on the json representation geo_json_geometry_collection_model = GeoJsonGeometryCollection.from_dict(geo_json_geometry_collection_model_json) assert geo_json_geometry_collection_model != False # Construct a model instance of GeoJsonGeometryCollection by calling from_dict on the json representation geo_json_geometry_collection_model_dict = GeoJsonGeometryCollection.from_dict(geo_json_geometry_collection_model_json).__dict__ geo_json_geometry_collection_model2 = GeoJsonGeometryCollection(**geo_json_geometry_collection_model_dict) # Verify the model instances are equivalent assert geo_json_geometry_collection_model == geo_json_geometry_collection_model2 # Convert model instance back to dict and verify no loss of data geo_json_geometry_collection_model_json2 = geo_json_geometry_collection_model.to_dict() assert geo_json_geometry_collection_model_json2 == geo_json_geometry_collection_model_json # endregion ############################################################################## # End of Model Tests ##############################################################################
true
true
f7fe5ce54a5974d8e0a1765d3a0ffae24c2b3014
352
py
Python
galaa/migrations/0002_rename_image_name_photos_name.py
lizgi/photo-gala
67647314577afbf9174ab715be32ac86047f8fb0
[ "MIT" ]
null
null
null
galaa/migrations/0002_rename_image_name_photos_name.py
lizgi/photo-gala
67647314577afbf9174ab715be32ac86047f8fb0
[ "MIT" ]
null
null
null
galaa/migrations/0002_rename_image_name_photos_name.py
lizgi/photo-gala
67647314577afbf9174ab715be32ac86047f8fb0
[ "MIT" ]
null
null
null
# Generated by Django 3.2.8 on 2021-11-26 22:19 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('galaa', '0001_initial'), ] operations = [ migrations.RenameField( model_name='photos', old_name='image_name', new_name='name', ), ]
18.526316
47
0.571023
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('galaa', '0001_initial'), ] operations = [ migrations.RenameField( model_name='photos', old_name='image_name', new_name='name', ), ]
true
true
f7fe5cfdd9ca84f74da4f55e7e6ee327870acbad
3,091
py
Python
airbyte-integrations/connectors/source-chargebee/source_chargebee/source.py
jinnig/airbyte
1ccd21867b7908380b941ac4aa7737b59d18d4a9
[ "MIT" ]
2
2021-08-04T03:17:38.000Z
2021-11-15T10:16:08.000Z
airbyte-integrations/connectors/source-chargebee/source_chargebee/source.py
jinnig/airbyte
1ccd21867b7908380b941ac4aa7737b59d18d4a9
[ "MIT" ]
null
null
null
airbyte-integrations/connectors/source-chargebee/source_chargebee/source.py
jinnig/airbyte
1ccd21867b7908380b941ac4aa7737b59d18d4a9
[ "MIT" ]
1
2021-08-04T03:25:02.000Z
2021-08-04T03:25:02.000Z
# # MIT License # # Copyright (c) 2020 Airbyte # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # from typing import Any, List, Mapping, Tuple import chargebee from airbyte_cdk.models import SyncMode from airbyte_cdk.sources import AbstractSource from airbyte_cdk.sources.streams import Stream from .streams import Addon, Customer, Invoice, Order, Plan, Subscription class SourceChargebee(AbstractSource): def check_connection(self, logger, config: Mapping[str, Any]) -> Tuple[bool, any]: # Configure the Chargebee Python SDK chargebee.configure(api_key=config["site_api_key"], site=config["site"]) try: subscription_stream = Subscription(start_date=config["start_date"]) next(subscription_stream.read_records(sync_mode=SyncMode.full_refresh)) return True, None except Exception as err: # Should catch all exceptions which are already handled by Chargebee Python wrapper. # https://github.com/chargebee/chargebee-python/blob/5346d833781de78a9eedbf9d12502f52c617c2d2/chargebee/http_request.py return False, repr(err) def streams(self, config) -> List[Stream]: # Configure the Chargebee Python SDK chargebee.configure(api_key=config["site_api_key"], site=config["site"]) kwargs = {"start_date": config["start_date"]} product_catalog_version = config["product_catalog"] # Below streams are suitable for both `Product Catalog 1.0` and `Product Catalog 2.0`. common_streams = [ Customer(**kwargs), Invoice(**kwargs), Order(**kwargs), Subscription(**kwargs), ] if product_catalog_version == "1.0": # Below streams are suitable only for `Product Catalog 1.0`. product_catalog_v1_streams = [ Addon(**kwargs), Plan(**kwargs), ] return common_streams + product_catalog_v1_streams # Below streams are suitable only for `Product Catalog 2.0`. return common_streams
42.342466
131
0.703656
from typing import Any, List, Mapping, Tuple import chargebee from airbyte_cdk.models import SyncMode from airbyte_cdk.sources import AbstractSource from airbyte_cdk.sources.streams import Stream from .streams import Addon, Customer, Invoice, Order, Plan, Subscription class SourceChargebee(AbstractSource): def check_connection(self, logger, config: Mapping[str, Any]) -> Tuple[bool, any]: chargebee.configure(api_key=config["site_api_key"], site=config["site"]) try: subscription_stream = Subscription(start_date=config["start_date"]) next(subscription_stream.read_records(sync_mode=SyncMode.full_refresh)) return True, None except Exception as err: return False, repr(err) def streams(self, config) -> List[Stream]: chargebee.configure(api_key=config["site_api_key"], site=config["site"]) kwargs = {"start_date": config["start_date"]} product_catalog_version = config["product_catalog"] common_streams = [ Customer(**kwargs), Invoice(**kwargs), Order(**kwargs), Subscription(**kwargs), ] if product_catalog_version == "1.0": product_catalog_v1_streams = [ Addon(**kwargs), Plan(**kwargs), ] return common_streams + product_catalog_v1_streams return common_streams
true
true
f7fe5d2291f6b08338083a0d398fa1269dbe65cf
220
py
Python
playground_env/.playground/connectors/passthrough/__init__.py
kandarpck/networksecurity2018
dafe2ee8d39bd9596b1ce3fbc8b50ca645bcd626
[ "MIT" ]
3
2018-10-25T16:03:53.000Z
2019-06-13T15:24:41.000Z
playground_env/.playground/connectors/passthrough/__init__.py
kandarpck/networksecurity2018
dafe2ee8d39bd9596b1ce3fbc8b50ca645bcd626
[ "MIT" ]
null
null
null
playground_env/.playground/connectors/passthrough/__init__.py
kandarpck/networksecurity2018
dafe2ee8d39bd9596b1ce3fbc8b50ca645bcd626
[ "MIT" ]
null
null
null
import playground from .passthrough import pt_client, pt_server passthrough_connector = playground.Connector(protocolStack=( pt_client, pt_server)) playground.setConnector('passthrough', passthrough_connector)
24.444444
61
0.818182
import playground from .passthrough import pt_client, pt_server passthrough_connector = playground.Connector(protocolStack=( pt_client, pt_server)) playground.setConnector('passthrough', passthrough_connector)
true
true
f7fe5d3f1f2b914ef8863e51f4ff8041918b0ffa
6,250
py
Python
sunpy/map/sources/stereo.py
fluxtransport/sunpy
351d3edca97e779179f367670292c95574c7a222
[ "BSD-2-Clause" ]
null
null
null
sunpy/map/sources/stereo.py
fluxtransport/sunpy
351d3edca97e779179f367670292c95574c7a222
[ "BSD-2-Clause" ]
1
2019-08-13T15:29:13.000Z
2019-08-13T15:29:13.000Z
sunpy/map/sources/stereo.py
fluxtransport/sunpy
351d3edca97e779179f367670292c95574c7a222
[ "BSD-2-Clause" ]
6
2017-03-15T07:17:05.000Z
2020-09-30T18:36:49.000Z
"""STEREO Map subclass definitions""" __author__ = "Keith Hughitt" __email__ = "keith.hughitt@nasa.gov" import astropy.units as u from astropy.visualization import PowerStretch from astropy.visualization.mpl_normalize import ImageNormalize from sunpy import log from sunpy.map import GenericMap from sunpy.map.sources.source_type import source_stretch __all__ = ['EUVIMap', 'CORMap', 'HIMap'] class EUVIMap(GenericMap): """STEREO-SECCHI EUVI Image Map EUVI is an extreme ultraviolet (EUV) imager. Part of the STEREO-SECCHI suite it observes the Sun from 1 to 1.7 solar radii. It is capable of observing at 304 (He II), 171 (Fe IX), 195 (Fe XII), and 284 (Fe XV) Angstroms. References ---------- * `STEREO Mission Page <https://stereo.gsfc.nasa.gov/>`_ * `STEREO SECCHI <http://secchi.nrl.navy.mil>`_ * `Instrument Page <http://secchi.lmsal.com/EUVI/>`_ """ def __init__(self, data, header, **kwargs): GenericMap.__init__(self, data, header, **kwargs) self._nickname = "{}-{}".format(self.detector, self.observatory[-1]) self.plot_settings['cmap'] = 'euvi{wl:d}'.format(wl=int(self.wavelength.value)) self.plot_settings['norm'] = ImageNormalize( stretch=source_stretch(self.meta, PowerStretch(0.25)), clip=False) self.meta['waveunit'] = self.meta.get('waveunit', 'Angstrom') # Try to identify when the FITS meta data does not have the correct # date FITS keyword if ('date_obs' in self.meta) and not('date-obs' in self.meta): self.meta['date-obs'] = self.meta['date_obs'] # fix CROTA to CROTAn if "crota" in self.meta and "crota2" not in self.meta: log.debug("EUVIMap: Changing the CROTA keyword to CROTA2") self.meta["crota2"] = self.meta.pop("crota") @property def rsun_arcseconds(self): """ Radius of the sun in arcseconds. References ---------- https://sohowww.nascom.nasa.gov/solarsoft/stereo/secchi/doc/FITS_keywords.pdf """ return self.meta.get('rsun', None) @property def rsun_obs(self): """ Radius of the sun in arcseconds as a quantity. References ---------- https://sohowww.nascom.nasa.gov/solarsoft/stereo/secchi/doc/FITS_keywords.pdf """ rsun_arcseconds = self.meta.get('rsun', None) if rsun_arcseconds is None: rsun_arcseconds = super().rsun_obs return u.Quantity(rsun_arcseconds, 'arcsec') @classmethod def is_datasource_for(cls, data, header, **kwargs): """Determines if header corresponds to an EUVI image""" return header.get('detector') == 'EUVI' class CORMap(GenericMap): """STEREO-SECCHI CORonograph Image Map. Part of the STEREO-SECCHI suite of remote sensing telescopes, COR is a set of two coronographs (COR1, COR2) onboard STEREO. They are both traditional Lyot coronagraphs. The COR1 detectors observes from 1.3 to 4 solar radii while the COR2 detectors observe a range from 2 to 15 solar radii. References ---------- * `STEREO Mission Page <https://stereo.gsfc.nasa.gov/>`_ * `STEREO SECCHI <http://secchi.nrl.navy.mil>`_ * `COR1 Instrument Page <https://cor1.gsfc.nasa.gov>`_ * `COR2 Instrument Page <http://secchi.nrl.navy.mil/index.php?p=cor2>`_ * `COR1 User Guide <https://cor1.gsfc.nasa.gov/guide/>`_ """ def __init__(self, data, header, **kwargs): GenericMap.__init__(self, data, header, **kwargs) self._nickname = "{}-{}".format(self.detector, self.observatory[-1]) self.plot_settings['cmap'] = 'stereocor{det!s}'.format(det=self.detector[-1]) self.plot_settings['norm'] = ImageNormalize( stretch=source_stretch(self.meta, PowerStretch(0.5)), clip=False) # Try to identify when the FITS meta data does not have the correct # date FITS keyword if ('date_obs' in self.meta) and not('date-obs' in self.meta): self.meta['date-obs'] = self.meta['date_obs'] @property def measurement(self): """ Returns the type of data observed. """ # TODO: This needs to do more than white-light. Should give B, pB, etc. return "white-light" @classmethod def is_datasource_for(cls, data, header, **kwargs): """Determines if header corresponds to an COR image""" return str(header.get('detector', '')).startswith('COR') class HIMap(GenericMap): """STEREO-SECCHI Heliospheric Imager (HI) Map. The HI is a wide-angle visible-light imaging system for the detection of coronal mass ejection (CME) events in interplanetary space and, in particular, of events directed towards the Earth. The Heliospheric imager consists of two instruments, the HI-1 and HI-2. The HI1 observes from 15-80 solar radii while HI2 observes from 80-215 solar radii. References ---------- * `STEREO Mission Page <https://stereo.gsfc.nasa.gov/>`_ * `STEREO SECCHI <https://secchi.nrl.navy.mil>`_ * `HI Instrument Page <http://www.stereo.rl.ac.uk>`_ """ def __init__(self, data, header, **kwargs): GenericMap.__init__(self, data, header, **kwargs) self._nickname = "{}-{}".format(self.detector, self.observatory[-1]) self.plot_settings['cmap'] = 'stereohi{det!s}'.format(det=self.detector[-1]) self.plot_settings['norm'] = ImageNormalize( stretch=source_stretch(self.meta, PowerStretch(0.25)), clip=False) # Try to identify when the FITS meta data does not have the correct # date FITS keyword if ('date_obs' in self.meta) and not('date-obs' in self.meta): self.meta['date-obs'] = self.meta['date_obs'] @property def measurement(self): """ Returns the type of data observed. """ # TODO: This needs to do more than white-light. Should give B, pB, etc. return "white-light" @classmethod def is_datasource_for(cls, data, header, **kwargs): """Determines if header corresponds to an COR image""" return str(header.get('detector', '')).startswith('HI')
35.714286
87
0.64128
__author__ = "Keith Hughitt" __email__ = "keith.hughitt@nasa.gov" import astropy.units as u from astropy.visualization import PowerStretch from astropy.visualization.mpl_normalize import ImageNormalize from sunpy import log from sunpy.map import GenericMap from sunpy.map.sources.source_type import source_stretch __all__ = ['EUVIMap', 'CORMap', 'HIMap'] class EUVIMap(GenericMap): def __init__(self, data, header, **kwargs): GenericMap.__init__(self, data, header, **kwargs) self._nickname = "{}-{}".format(self.detector, self.observatory[-1]) self.plot_settings['cmap'] = 'euvi{wl:d}'.format(wl=int(self.wavelength.value)) self.plot_settings['norm'] = ImageNormalize( stretch=source_stretch(self.meta, PowerStretch(0.25)), clip=False) self.meta['waveunit'] = self.meta.get('waveunit', 'Angstrom') if ('date_obs' in self.meta) and not('date-obs' in self.meta): self.meta['date-obs'] = self.meta['date_obs'] if "crota" in self.meta and "crota2" not in self.meta: log.debug("EUVIMap: Changing the CROTA keyword to CROTA2") self.meta["crota2"] = self.meta.pop("crota") @property def rsun_arcseconds(self): return self.meta.get('rsun', None) @property def rsun_obs(self): rsun_arcseconds = self.meta.get('rsun', None) if rsun_arcseconds is None: rsun_arcseconds = super().rsun_obs return u.Quantity(rsun_arcseconds, 'arcsec') @classmethod def is_datasource_for(cls, data, header, **kwargs): return header.get('detector') == 'EUVI' class CORMap(GenericMap): def __init__(self, data, header, **kwargs): GenericMap.__init__(self, data, header, **kwargs) self._nickname = "{}-{}".format(self.detector, self.observatory[-1]) self.plot_settings['cmap'] = 'stereocor{det!s}'.format(det=self.detector[-1]) self.plot_settings['norm'] = ImageNormalize( stretch=source_stretch(self.meta, PowerStretch(0.5)), clip=False) if ('date_obs' in self.meta) and not('date-obs' in self.meta): self.meta['date-obs'] = self.meta['date_obs'] @property def measurement(self): return "white-light" @classmethod def is_datasource_for(cls, data, header, **kwargs): return str(header.get('detector', '')).startswith('COR') class HIMap(GenericMap): def __init__(self, data, header, **kwargs): GenericMap.__init__(self, data, header, **kwargs) self._nickname = "{}-{}".format(self.detector, self.observatory[-1]) self.plot_settings['cmap'] = 'stereohi{det!s}'.format(det=self.detector[-1]) self.plot_settings['norm'] = ImageNormalize( stretch=source_stretch(self.meta, PowerStretch(0.25)), clip=False) if ('date_obs' in self.meta) and not('date-obs' in self.meta): self.meta['date-obs'] = self.meta['date_obs'] @property def measurement(self): return "white-light" @classmethod def is_datasource_for(cls, data, header, **kwargs): return str(header.get('detector', '')).startswith('HI')
true
true
f7fe5e550e01e609505d8cf74bc3c4e468c94e54
367
py
Python
demo/app/controller/main.py
shiroyuki/Tori
143b99075bf9e8d469d117f056516ab847234c8c
[ "MIT" ]
null
null
null
demo/app/controller/main.py
shiroyuki/Tori
143b99075bf9e8d469d117f056516ab847234c8c
[ "MIT" ]
6
2015-01-19T20:21:40.000Z
2015-01-19T20:28:42.000Z
demo/app/controller/main.py
shiroyuki/Tori
143b99075bf9e8d469d117f056516ab847234c8c
[ "MIT" ]
null
null
null
from tori import Controller from tori.decorator.controller import renderer from tori.exception import * @renderer('demo.app.views') class MainController(Controller): def get(self): try: self.render('index.html', title="Testing Ground", uri=self.request.uri) except Exception as e: print(e)
30.583333
83
0.621253
from tori import Controller from tori.decorator.controller import renderer from tori.exception import * @renderer('demo.app.views') class MainController(Controller): def get(self): try: self.render('index.html', title="Testing Ground", uri=self.request.uri) except Exception as e: print(e)
true
true
f7fe5effe3c45f615f137cee01e9cd7dced4fd2b
29,587
py
Python
sqlparse/keywords.py
testtctc/sqlparse
d30bb97efee15e3c84cd436ad10991183fc4ffe7
[ "BSD-3-Clause" ]
null
null
null
sqlparse/keywords.py
testtctc/sqlparse
d30bb97efee15e3c84cd436ad10991183fc4ffe7
[ "BSD-3-Clause" ]
null
null
null
sqlparse/keywords.py
testtctc/sqlparse
d30bb97efee15e3c84cd436ad10991183fc4ffe7
[ "BSD-3-Clause" ]
null
null
null
# # Copyright (C) 2009-2020 the sqlparse authors and contributors # <see AUTHORS file> # # This module is part of python-sqlparse and is released under # the BSD License: https://opensource.org/licenses/BSD-3-Clause import re from sqlparse import tokens def is_keyword(value): #是否是关键字 val = value.upper() return (KEYWORDS_COMMON.get(val) or KEYWORDS_ORACLE.get(val) or KEYWORDS_PLPGSQL.get(val) or KEYWORDS_HQL.get(val) or KEYWORDS.get(val, tokens.Name)), value #sql语法 SQL_REGEX = { 'root': [ (r'(--|# )\+.*?(\r\n|\r|\n|$)', tokens.Comment.Single.Hint), (r'/\*\+[\s\S]*?\*/', tokens.Comment.Multiline.Hint), (r'(--|# ).*?(\r\n|\r|\n|$)', tokens.Comment.Single), (r'/\*[\s\S]*?\*/', tokens.Comment.Multiline), (r'(\r\n|\r|\n)', tokens.Newline), (r'\s+?', tokens.Whitespace), (r':=', tokens.Assignment), (r'::', tokens.Punctuation), (r'\*', tokens.Wildcard), (r"`(``|[^`])*`", tokens.Name), (r"´(´´|[^´])*´", tokens.Name), (r'((?<!\S)\$(?:[_A-ZÀ-Ü]\w*)?\$)[\s\S]*?\1', tokens.Literal), (r'\?', tokens.Name.Placeholder), (r'%(\(\w+\))?s', tokens.Name.Placeholder), (r'(?<!\w)[$:?]\w+', tokens.Name.Placeholder), (r'\\\w+', tokens.Command), (r'(NOT\s+)?(IN)\b', tokens.Operator.Comparison), # FIXME(andi): VALUES shouldn't be listed here # see https://github.com/andialbrecht/sqlparse/pull/64 # AS and IN are special, it may be followed by a parenthesis, but # are never functions, see issue183 and issue507 (r'(CASE|IN|VALUES|USING|FROM|AS)\b', tokens.Keyword), (r'(@|##|#)[A-ZÀ-Ü]\w+', tokens.Name), # see issue #39 # Spaces around period `schema . name` are valid identifier # TODO: Spaces before period not implemented (r'[A-ZÀ-Ü]\w*(?=\s*\.)', tokens.Name), # 'Name' . # FIXME(atronah): never match, # because `re.match` doesn't work with look-behind regexp feature (r'(?<=\.)[A-ZÀ-Ü]\w*', tokens.Name), # .'Name' (r'[A-ZÀ-Ü]\w*(?=\()', tokens.Name), # side effect: change kw to func (r'-?0x[\dA-F]+', tokens.Number.Hexadecimal), (r'-?\d*(\.\d+)?E-?\d+', tokens.Number.Float), (r'(?![_A-ZÀ-Ü])-?(\d+(\.\d*)|\.\d+)(?![_A-ZÀ-Ü])', tokens.Number.Float), (r'(?![_A-ZÀ-Ü])-?\d+(?![_A-ZÀ-Ü])', tokens.Number.Integer), (r"'(''|\\\\|\\'|[^'])*'", tokens.String.Single), # not a real string literal in ANSI SQL: (r'"(""|\\\\|\\"|[^"])*"', tokens.String.Symbol), (r'(""|".*?[^\\]")', tokens.String.Symbol), # sqlite names can be escaped with [square brackets]. left bracket # cannot be preceded by word character or a right bracket -- # otherwise it's probably an array index (r'(?<![\w\])])(\[[^\]\[]+\])', tokens.Name), (r'((LEFT\s+|RIGHT\s+|FULL\s+)?(INNER\s+|OUTER\s+|STRAIGHT\s+)?' r'|(CROSS\s+|NATURAL\s+)?)?JOIN\b', tokens.Keyword), (r'END(\s+IF|\s+LOOP|\s+WHILE)?\b', tokens.Keyword), (r'NOT\s+NULL\b', tokens.Keyword), (r'NULLS\s+(FIRST|LAST)\b', tokens.Keyword), (r'UNION\s+ALL\b', tokens.Keyword), (r'CREATE(\s+OR\s+REPLACE)?\b', tokens.Keyword.DDL), (r'DOUBLE\s+PRECISION\b', tokens.Name.Builtin), (r'GROUP\s+BY\b', tokens.Keyword), (r'ORDER\s+BY\b', tokens.Keyword), (r'HANDLER\s+FOR\b', tokens.Keyword), (r'(LATERAL\s+VIEW\s+)' r'(EXPLODE|INLINE|PARSE_URL_TUPLE|POSEXPLODE|STACK)\b', tokens.Keyword), (r"(AT|WITH')\s+TIME\s+ZONE\s+'[^']+'", tokens.Keyword.TZCast), (r'(NOT\s+)?(LIKE|ILIKE|RLIKE)\b', tokens.Operator.Comparison), (r'[0-9_A-ZÀ-Ü][_$#\w]*', is_keyword), (r'[;:()\[\],\.]', tokens.Punctuation), (r'[<>=~!]+', tokens.Operator.Comparison), (r'[+/@#%^&|^-]+', tokens.Operator), ]} #标签 FLAGS = re.IGNORECASE | re.UNICODE SQL_REGEX = [(re.compile(rx, FLAGS).match, tt) for rx, tt in SQL_REGEX['root']] # 通用关键字 KEYWORDS = { 'ABORT': tokens.Keyword, 'ABS': tokens.Keyword, 'ABSOLUTE': tokens.Keyword, 'ACCESS': tokens.Keyword, 'ADA': tokens.Keyword, 'ADD': tokens.Keyword, 'ADMIN': tokens.Keyword, 'AFTER': tokens.Keyword, 'AGGREGATE': tokens.Keyword, 'ALIAS': tokens.Keyword, 'ALL': tokens.Keyword, 'ALLOCATE': tokens.Keyword, 'ANALYSE': tokens.Keyword, 'ANALYZE': tokens.Keyword, 'ANY': tokens.Keyword, 'ARRAYLEN': tokens.Keyword, 'ARE': tokens.Keyword, 'ASC': tokens.Keyword.Order, 'ASENSITIVE': tokens.Keyword, 'ASSERTION': tokens.Keyword, 'ASSIGNMENT': tokens.Keyword, 'ASYMMETRIC': tokens.Keyword, 'AT': tokens.Keyword, 'ATOMIC': tokens.Keyword, 'AUDIT': tokens.Keyword, 'AUTHORIZATION': tokens.Keyword, 'AUTO_INCREMENT': tokens.Keyword, 'AVG': tokens.Keyword, 'BACKWARD': tokens.Keyword, 'BEFORE': tokens.Keyword, 'BEGIN': tokens.Keyword, 'BETWEEN': tokens.Keyword, 'BITVAR': tokens.Keyword, 'BIT_LENGTH': tokens.Keyword, 'BOTH': tokens.Keyword, 'BREADTH': tokens.Keyword, # 'C': tokens.Keyword, # most likely this is an alias 'CACHE': tokens.Keyword, 'CALL': tokens.Keyword, 'CALLED': tokens.Keyword, 'CARDINALITY': tokens.Keyword, 'CASCADE': tokens.Keyword, 'CASCADED': tokens.Keyword, 'CAST': tokens.Keyword, 'CATALOG': tokens.Keyword, 'CATALOG_NAME': tokens.Keyword, 'CHAIN': tokens.Keyword, 'CHARACTERISTICS': tokens.Keyword, 'CHARACTER_LENGTH': tokens.Keyword, 'CHARACTER_SET_CATALOG': tokens.Keyword, 'CHARACTER_SET_NAME': tokens.Keyword, 'CHARACTER_SET_SCHEMA': tokens.Keyword, 'CHAR_LENGTH': tokens.Keyword, 'CHARSET': tokens.Keyword, 'CHECK': tokens.Keyword, 'CHECKED': tokens.Keyword, 'CHECKPOINT': tokens.Keyword, 'CLASS': tokens.Keyword, 'CLASS_ORIGIN': tokens.Keyword, 'CLOB': tokens.Keyword, 'CLOSE': tokens.Keyword, 'CLUSTER': tokens.Keyword, 'COALESCE': tokens.Keyword, 'COBOL': tokens.Keyword, 'COLLATE': tokens.Keyword, 'COLLATION': tokens.Keyword, 'COLLATION_CATALOG': tokens.Keyword, 'COLLATION_NAME': tokens.Keyword, 'COLLATION_SCHEMA': tokens.Keyword, 'COLLECT': tokens.Keyword, 'COLUMN': tokens.Keyword, 'COLUMN_NAME': tokens.Keyword, 'COMPRESS': tokens.Keyword, 'COMMAND_FUNCTION': tokens.Keyword, 'COMMAND_FUNCTION_CODE': tokens.Keyword, 'COMMENT': tokens.Keyword, 'COMMIT': tokens.Keyword.DML, 'COMMITTED': tokens.Keyword, 'COMPLETION': tokens.Keyword, 'CONCURRENTLY': tokens.Keyword, 'CONDITION_NUMBER': tokens.Keyword, 'CONNECT': tokens.Keyword, 'CONNECTION': tokens.Keyword, 'CONNECTION_NAME': tokens.Keyword, 'CONSTRAINT': tokens.Keyword, 'CONSTRAINTS': tokens.Keyword, 'CONSTRAINT_CATALOG': tokens.Keyword, 'CONSTRAINT_NAME': tokens.Keyword, 'CONSTRAINT_SCHEMA': tokens.Keyword, 'CONSTRUCTOR': tokens.Keyword, 'CONTAINS': tokens.Keyword, 'CONTINUE': tokens.Keyword, 'CONVERSION': tokens.Keyword, 'CONVERT': tokens.Keyword, 'COPY': tokens.Keyword, 'CORRESPONDING': tokens.Keyword, 'COUNT': tokens.Keyword, 'CREATEDB': tokens.Keyword, 'CREATEUSER': tokens.Keyword, 'CROSS': tokens.Keyword, 'CUBE': tokens.Keyword, 'CURRENT': tokens.Keyword, 'CURRENT_DATE': tokens.Keyword, 'CURRENT_PATH': tokens.Keyword, 'CURRENT_ROLE': tokens.Keyword, 'CURRENT_TIME': tokens.Keyword, 'CURRENT_TIMESTAMP': tokens.Keyword, 'CURRENT_USER': tokens.Keyword, 'CURSOR': tokens.Keyword, 'CURSOR_NAME': tokens.Keyword, 'CYCLE': tokens.Keyword, 'DATA': tokens.Keyword, 'DATABASE': tokens.Keyword, 'DATETIME_INTERVAL_CODE': tokens.Keyword, 'DATETIME_INTERVAL_PRECISION': tokens.Keyword, 'DAY': tokens.Keyword, 'DEALLOCATE': tokens.Keyword, 'DECLARE': tokens.Keyword, 'DEFAULT': tokens.Keyword, 'DEFAULTS': tokens.Keyword, 'DEFERRABLE': tokens.Keyword, 'DEFERRED': tokens.Keyword, 'DEFINED': tokens.Keyword, 'DEFINER': tokens.Keyword, 'DELIMITER': tokens.Keyword, 'DELIMITERS': tokens.Keyword, 'DEREF': tokens.Keyword, 'DESC': tokens.Keyword.Order, 'DESCRIBE': tokens.Keyword, 'DESCRIPTOR': tokens.Keyword, 'DESTROY': tokens.Keyword, 'DESTRUCTOR': tokens.Keyword, 'DETERMINISTIC': tokens.Keyword, 'DIAGNOSTICS': tokens.Keyword, 'DICTIONARY': tokens.Keyword, 'DISABLE': tokens.Keyword, 'DISCONNECT': tokens.Keyword, 'DISPATCH': tokens.Keyword, 'DO': tokens.Keyword, 'DOMAIN': tokens.Keyword, 'DYNAMIC': tokens.Keyword, 'DYNAMIC_FUNCTION': tokens.Keyword, 'DYNAMIC_FUNCTION_CODE': tokens.Keyword, 'EACH': tokens.Keyword, 'ENABLE': tokens.Keyword, 'ENCODING': tokens.Keyword, 'ENCRYPTED': tokens.Keyword, 'END-EXEC': tokens.Keyword, 'ENGINE': tokens.Keyword, 'EQUALS': tokens.Keyword, 'ESCAPE': tokens.Keyword, 'EVERY': tokens.Keyword, 'EXCEPT': tokens.Keyword, 'EXCEPTION': tokens.Keyword, 'EXCLUDING': tokens.Keyword, 'EXCLUSIVE': tokens.Keyword, 'EXEC': tokens.Keyword, 'EXECUTE': tokens.Keyword, 'EXISTING': tokens.Keyword, 'EXISTS': tokens.Keyword, 'EXPLAIN': tokens.Keyword, 'EXTERNAL': tokens.Keyword, 'EXTRACT': tokens.Keyword, 'FALSE': tokens.Keyword, 'FETCH': tokens.Keyword, 'FILE': tokens.Keyword, 'FINAL': tokens.Keyword, 'FIRST': tokens.Keyword, 'FORCE': tokens.Keyword, 'FOREACH': tokens.Keyword, 'FOREIGN': tokens.Keyword, 'FORTRAN': tokens.Keyword, 'FORWARD': tokens.Keyword, 'FOUND': tokens.Keyword, 'FREE': tokens.Keyword, 'FREEZE': tokens.Keyword, 'FULL': tokens.Keyword, 'FUNCTION': tokens.Keyword, # 'G': tokens.Keyword, 'GENERAL': tokens.Keyword, 'GENERATED': tokens.Keyword, 'GET': tokens.Keyword, 'GLOBAL': tokens.Keyword, 'GO': tokens.Keyword, 'GOTO': tokens.Keyword, 'GRANT': tokens.Keyword, 'GRANTED': tokens.Keyword, 'GROUPING': tokens.Keyword, 'HAVING': tokens.Keyword, 'HIERARCHY': tokens.Keyword, 'HOLD': tokens.Keyword, 'HOUR': tokens.Keyword, 'HOST': tokens.Keyword, 'IDENTIFIED': tokens.Keyword, 'IDENTITY': tokens.Keyword, 'IGNORE': tokens.Keyword, 'ILIKE': tokens.Keyword, 'IMMEDIATE': tokens.Keyword, 'IMMUTABLE': tokens.Keyword, 'IMPLEMENTATION': tokens.Keyword, 'IMPLICIT': tokens.Keyword, 'INCLUDING': tokens.Keyword, 'INCREMENT': tokens.Keyword, 'INDEX': tokens.Keyword, 'INDITCATOR': tokens.Keyword, 'INFIX': tokens.Keyword, 'INHERITS': tokens.Keyword, 'INITIAL': tokens.Keyword, 'INITIALIZE': tokens.Keyword, 'INITIALLY': tokens.Keyword, 'INOUT': tokens.Keyword, 'INPUT': tokens.Keyword, 'INSENSITIVE': tokens.Keyword, 'INSTANTIABLE': tokens.Keyword, 'INSTEAD': tokens.Keyword, 'INTERSECT': tokens.Keyword, 'INTO': tokens.Keyword, 'INVOKER': tokens.Keyword, 'IS': tokens.Keyword, 'ISNULL': tokens.Keyword, 'ISOLATION': tokens.Keyword, 'ITERATE': tokens.Keyword, # 'K': tokens.Keyword, 'KEY': tokens.Keyword, 'KEY_MEMBER': tokens.Keyword, 'KEY_TYPE': tokens.Keyword, 'LANCOMPILER': tokens.Keyword, 'LANGUAGE': tokens.Keyword, 'LARGE': tokens.Keyword, 'LAST': tokens.Keyword, 'LATERAL': tokens.Keyword, 'LEADING': tokens.Keyword, 'LENGTH': tokens.Keyword, 'LESS': tokens.Keyword, 'LEVEL': tokens.Keyword, 'LIMIT': tokens.Keyword, 'LISTEN': tokens.Keyword, 'LOAD': tokens.Keyword, 'LOCAL': tokens.Keyword, 'LOCALTIME': tokens.Keyword, 'LOCALTIMESTAMP': tokens.Keyword, 'LOCATION': tokens.Keyword, 'LOCATOR': tokens.Keyword, 'LOCK': tokens.Keyword, 'LOWER': tokens.Keyword, # 'M': tokens.Keyword, 'MAP': tokens.Keyword, 'MATCH': tokens.Keyword, 'MAXEXTENTS': tokens.Keyword, 'MAXVALUE': tokens.Keyword, 'MESSAGE_LENGTH': tokens.Keyword, 'MESSAGE_OCTET_LENGTH': tokens.Keyword, 'MESSAGE_TEXT': tokens.Keyword, 'METHOD': tokens.Keyword, 'MINUTE': tokens.Keyword, 'MINUS': tokens.Keyword, 'MINVALUE': tokens.Keyword, 'MOD': tokens.Keyword, 'MODE': tokens.Keyword, 'MODIFIES': tokens.Keyword, 'MODIFY': tokens.Keyword, 'MONTH': tokens.Keyword, 'MORE': tokens.Keyword, 'MOVE': tokens.Keyword, 'MUMPS': tokens.Keyword, 'NAMES': tokens.Keyword, 'NATIONAL': tokens.Keyword, 'NATURAL': tokens.Keyword, 'NCHAR': tokens.Keyword, 'NCLOB': tokens.Keyword, 'NEW': tokens.Keyword, 'NEXT': tokens.Keyword, 'NO': tokens.Keyword, 'NOAUDIT': tokens.Keyword, 'NOCOMPRESS': tokens.Keyword, 'NOCREATEDB': tokens.Keyword, 'NOCREATEUSER': tokens.Keyword, 'NONE': tokens.Keyword, 'NOT': tokens.Keyword, 'NOTFOUND': tokens.Keyword, 'NOTHING': tokens.Keyword, 'NOTIFY': tokens.Keyword, 'NOTNULL': tokens.Keyword, 'NOWAIT': tokens.Keyword, 'NULL': tokens.Keyword, 'NULLABLE': tokens.Keyword, 'NULLIF': tokens.Keyword, 'OBJECT': tokens.Keyword, 'OCTET_LENGTH': tokens.Keyword, 'OF': tokens.Keyword, 'OFF': tokens.Keyword, 'OFFLINE': tokens.Keyword, 'OFFSET': tokens.Keyword, 'OIDS': tokens.Keyword, 'OLD': tokens.Keyword, 'ONLINE': tokens.Keyword, 'ONLY': tokens.Keyword, 'OPEN': tokens.Keyword, 'OPERATION': tokens.Keyword, 'OPERATOR': tokens.Keyword, 'OPTION': tokens.Keyword, 'OPTIONS': tokens.Keyword, 'ORDINALITY': tokens.Keyword, 'OUT': tokens.Keyword, 'OUTPUT': tokens.Keyword, 'OVERLAPS': tokens.Keyword, 'OVERLAY': tokens.Keyword, 'OVERRIDING': tokens.Keyword, 'OWNER': tokens.Keyword, 'QUARTER': tokens.Keyword, 'PAD': tokens.Keyword, 'PARAMETER': tokens.Keyword, 'PARAMETERS': tokens.Keyword, 'PARAMETER_MODE': tokens.Keyword, 'PARAMETER_NAME': tokens.Keyword, 'PARAMETER_ORDINAL_POSITION': tokens.Keyword, 'PARAMETER_SPECIFIC_CATALOG': tokens.Keyword, 'PARAMETER_SPECIFIC_NAME': tokens.Keyword, 'PARAMETER_SPECIFIC_SCHEMA': tokens.Keyword, 'PARTIAL': tokens.Keyword, 'PASCAL': tokens.Keyword, 'PCTFREE': tokens.Keyword, 'PENDANT': tokens.Keyword, 'PLACING': tokens.Keyword, 'PLI': tokens.Keyword, 'POSITION': tokens.Keyword, 'POSTFIX': tokens.Keyword, 'PRECISION': tokens.Keyword, 'PREFIX': tokens.Keyword, 'PREORDER': tokens.Keyword, 'PREPARE': tokens.Keyword, 'PRESERVE': tokens.Keyword, 'PRIMARY': tokens.Keyword, 'PRIOR': tokens.Keyword, 'PRIVILEGES': tokens.Keyword, 'PROCEDURAL': tokens.Keyword, 'PROCEDURE': tokens.Keyword, 'PUBLIC': tokens.Keyword, 'RAISE': tokens.Keyword, 'RAW': tokens.Keyword, 'READ': tokens.Keyword, 'READS': tokens.Keyword, 'RECHECK': tokens.Keyword, 'RECURSIVE': tokens.Keyword, 'REF': tokens.Keyword, 'REFERENCES': tokens.Keyword, 'REFERENCING': tokens.Keyword, 'REINDEX': tokens.Keyword, 'RELATIVE': tokens.Keyword, 'RENAME': tokens.Keyword, 'REPEATABLE': tokens.Keyword, 'RESET': tokens.Keyword, 'RESOURCE': tokens.Keyword, 'RESTART': tokens.Keyword, 'RESTRICT': tokens.Keyword, 'RESULT': tokens.Keyword, 'RETURN': tokens.Keyword, 'RETURNED_LENGTH': tokens.Keyword, 'RETURNED_OCTET_LENGTH': tokens.Keyword, 'RETURNED_SQLSTATE': tokens.Keyword, 'RETURNING': tokens.Keyword, 'RETURNS': tokens.Keyword, 'REVOKE': tokens.Keyword, 'RIGHT': tokens.Keyword, 'ROLE': tokens.Keyword, 'ROLLBACK': tokens.Keyword.DML, 'ROLLUP': tokens.Keyword, 'ROUTINE': tokens.Keyword, 'ROUTINE_CATALOG': tokens.Keyword, 'ROUTINE_NAME': tokens.Keyword, 'ROUTINE_SCHEMA': tokens.Keyword, 'ROW': tokens.Keyword, 'ROWS': tokens.Keyword, 'ROW_COUNT': tokens.Keyword, 'RULE': tokens.Keyword, 'SAVE_POINT': tokens.Keyword, 'SCALE': tokens.Keyword, 'SCHEMA': tokens.Keyword, 'SCHEMA_NAME': tokens.Keyword, 'SCOPE': tokens.Keyword, 'SCROLL': tokens.Keyword, 'SEARCH': tokens.Keyword, 'SECOND': tokens.Keyword, 'SECURITY': tokens.Keyword, 'SELF': tokens.Keyword, 'SENSITIVE': tokens.Keyword, 'SEQUENCE': tokens.Keyword, 'SERIALIZABLE': tokens.Keyword, 'SERVER_NAME': tokens.Keyword, 'SESSION': tokens.Keyword, 'SESSION_USER': tokens.Keyword, 'SETOF': tokens.Keyword, 'SETS': tokens.Keyword, 'SHARE': tokens.Keyword, 'SHOW': tokens.Keyword, 'SIMILAR': tokens.Keyword, 'SIMPLE': tokens.Keyword, 'SIZE': tokens.Keyword, 'SOME': tokens.Keyword, 'SOURCE': tokens.Keyword, 'SPACE': tokens.Keyword, 'SPECIFIC': tokens.Keyword, 'SPECIFICTYPE': tokens.Keyword, 'SPECIFIC_NAME': tokens.Keyword, 'SQL': tokens.Keyword, 'SQLBUF': tokens.Keyword, 'SQLCODE': tokens.Keyword, 'SQLERROR': tokens.Keyword, 'SQLEXCEPTION': tokens.Keyword, 'SQLSTATE': tokens.Keyword, 'SQLWARNING': tokens.Keyword, 'STABLE': tokens.Keyword, 'START': tokens.Keyword.DML, # 'STATE': tokens.Keyword, 'STATEMENT': tokens.Keyword, 'STATIC': tokens.Keyword, 'STATISTICS': tokens.Keyword, 'STDIN': tokens.Keyword, 'STDOUT': tokens.Keyword, 'STORAGE': tokens.Keyword, 'STRICT': tokens.Keyword, 'STRUCTURE': tokens.Keyword, 'STYPE': tokens.Keyword, 'SUBCLASS_ORIGIN': tokens.Keyword, 'SUBLIST': tokens.Keyword, 'SUBSTRING': tokens.Keyword, 'SUCCESSFUL': tokens.Keyword, 'SUM': tokens.Keyword, 'SYMMETRIC': tokens.Keyword, 'SYNONYM': tokens.Keyword, 'SYSID': tokens.Keyword, 'SYSTEM': tokens.Keyword, 'SYSTEM_USER': tokens.Keyword, 'TABLE': tokens.Keyword, 'TABLE_NAME': tokens.Keyword, 'TEMP': tokens.Keyword, 'TEMPLATE': tokens.Keyword, 'TEMPORARY': tokens.Keyword, 'TERMINATE': tokens.Keyword, 'THAN': tokens.Keyword, 'TIMESTAMP': tokens.Keyword, 'TIMEZONE_HOUR': tokens.Keyword, 'TIMEZONE_MINUTE': tokens.Keyword, 'TO': tokens.Keyword, 'TOAST': tokens.Keyword, 'TRAILING': tokens.Keyword, 'TRANSATION': tokens.Keyword, 'TRANSACTIONS_COMMITTED': tokens.Keyword, 'TRANSACTIONS_ROLLED_BACK': tokens.Keyword, 'TRANSATION_ACTIVE': tokens.Keyword, 'TRANSFORM': tokens.Keyword, 'TRANSFORMS': tokens.Keyword, 'TRANSLATE': tokens.Keyword, 'TRANSLATION': tokens.Keyword, 'TREAT': tokens.Keyword, 'TRIGGER': tokens.Keyword, 'TRIGGER_CATALOG': tokens.Keyword, 'TRIGGER_NAME': tokens.Keyword, 'TRIGGER_SCHEMA': tokens.Keyword, 'TRIM': tokens.Keyword, 'TRUE': tokens.Keyword, 'TRUNCATE': tokens.Keyword, 'TRUSTED': tokens.Keyword, 'TYPE': tokens.Keyword, 'UID': tokens.Keyword, 'UNCOMMITTED': tokens.Keyword, 'UNDER': tokens.Keyword, 'UNENCRYPTED': tokens.Keyword, 'UNION': tokens.Keyword, 'UNIQUE': tokens.Keyword, 'UNKNOWN': tokens.Keyword, 'UNLISTEN': tokens.Keyword, 'UNNAMED': tokens.Keyword, 'UNNEST': tokens.Keyword, 'UNTIL': tokens.Keyword, 'UPPER': tokens.Keyword, 'USAGE': tokens.Keyword, 'USE': tokens.Keyword, 'USER': tokens.Keyword, 'USER_DEFINED_TYPE_CATALOG': tokens.Keyword, 'USER_DEFINED_TYPE_NAME': tokens.Keyword, 'USER_DEFINED_TYPE_SCHEMA': tokens.Keyword, 'USING': tokens.Keyword, 'VACUUM': tokens.Keyword, 'VALID': tokens.Keyword, 'VALIDATE': tokens.Keyword, 'VALIDATOR': tokens.Keyword, 'VALUES': tokens.Keyword, 'VARIABLE': tokens.Keyword, 'VERBOSE': tokens.Keyword, 'VERSION': tokens.Keyword, 'VIEW': tokens.Keyword, 'VOLATILE': tokens.Keyword, 'WEEK': tokens.Keyword, 'WHENEVER': tokens.Keyword, 'WITH': tokens.Keyword.CTE, 'WITHOUT': tokens.Keyword, 'WORK': tokens.Keyword, 'WRITE': tokens.Keyword, 'YEAR': tokens.Keyword, 'ZONE': tokens.Keyword, # Name.Builtin 'ARRAY': tokens.Name.Builtin, 'BIGINT': tokens.Name.Builtin, 'BINARY': tokens.Name.Builtin, 'BIT': tokens.Name.Builtin, 'BLOB': tokens.Name.Builtin, 'BOOLEAN': tokens.Name.Builtin, 'CHAR': tokens.Name.Builtin, 'CHARACTER': tokens.Name.Builtin, 'DATE': tokens.Name.Builtin, 'DEC': tokens.Name.Builtin, 'DECIMAL': tokens.Name.Builtin, 'FILE_TYPE': tokens.Name.Builtin, 'FLOAT': tokens.Name.Builtin, 'INT': tokens.Name.Builtin, 'INT8': tokens.Name.Builtin, 'INTEGER': tokens.Name.Builtin, 'INTERVAL': tokens.Name.Builtin, 'LONG': tokens.Name.Builtin, 'NATURALN': tokens.Name.Builtin, 'NVARCHAR': tokens.Name.Builtin, 'NUMBER': tokens.Name.Builtin, 'NUMERIC': tokens.Name.Builtin, 'PLS_INTEGER': tokens.Name.Builtin, 'POSITIVE': tokens.Name.Builtin, 'POSITIVEN': tokens.Name.Builtin, 'REAL': tokens.Name.Builtin, 'ROWID': tokens.Name.Builtin, 'ROWLABEL': tokens.Name.Builtin, 'ROWNUM': tokens.Name.Builtin, 'SERIAL': tokens.Name.Builtin, 'SERIAL8': tokens.Name.Builtin, 'SIGNED': tokens.Name.Builtin, 'SIGNTYPE': tokens.Name.Builtin, 'SIMPLE_DOUBLE': tokens.Name.Builtin, 'SIMPLE_FLOAT': tokens.Name.Builtin, 'SIMPLE_INTEGER': tokens.Name.Builtin, 'SMALLINT': tokens.Name.Builtin, 'SYS_REFCURSOR': tokens.Name.Builtin, 'SYSDATE': tokens.Name, 'TEXT': tokens.Name.Builtin, 'TINYINT': tokens.Name.Builtin, 'UNSIGNED': tokens.Name.Builtin, 'UROWID': tokens.Name.Builtin, 'UTL_FILE': tokens.Name.Builtin, 'VARCHAR': tokens.Name.Builtin, 'VARCHAR2': tokens.Name.Builtin, 'VARYING': tokens.Name.Builtin, } KEYWORDS_COMMON = { 'SELECT': tokens.Keyword.DML, 'INSERT': tokens.Keyword.DML, 'DELETE': tokens.Keyword.DML, 'UPDATE': tokens.Keyword.DML, 'UPSERT': tokens.Keyword.DML, 'REPLACE': tokens.Keyword.DML, 'MERGE': tokens.Keyword.DML, 'DROP': tokens.Keyword.DDL, 'CREATE': tokens.Keyword.DDL, 'ALTER': tokens.Keyword.DDL, 'WHERE': tokens.Keyword, 'FROM': tokens.Keyword, 'INNER': tokens.Keyword, 'JOIN': tokens.Keyword, 'STRAIGHT_JOIN': tokens.Keyword, 'AND': tokens.Keyword, 'OR': tokens.Keyword, 'LIKE': tokens.Keyword, 'ON': tokens.Keyword, 'IN': tokens.Keyword, 'SET': tokens.Keyword, 'BY': tokens.Keyword, 'GROUP': tokens.Keyword, 'ORDER': tokens.Keyword, 'LEFT': tokens.Keyword, 'OUTER': tokens.Keyword, 'FULL': tokens.Keyword, 'IF': tokens.Keyword, 'END': tokens.Keyword, 'THEN': tokens.Keyword, 'LOOP': tokens.Keyword, 'AS': tokens.Keyword, 'ELSE': tokens.Keyword, 'FOR': tokens.Keyword, 'WHILE': tokens.Keyword, 'CASE': tokens.Keyword, 'WHEN': tokens.Keyword, 'MIN': tokens.Keyword, 'MAX': tokens.Keyword, 'DISTINCT': tokens.Keyword, } # oracle 关键字 KEYWORDS_ORACLE = { 'ARCHIVE': tokens.Keyword, 'ARCHIVELOG': tokens.Keyword, 'BACKUP': tokens.Keyword, 'BECOME': tokens.Keyword, 'BLOCK': tokens.Keyword, 'BODY': tokens.Keyword, 'CANCEL': tokens.Keyword, 'CHANGE': tokens.Keyword, 'COMPILE': tokens.Keyword, 'CONTENTS': tokens.Keyword, 'CONTROLFILE': tokens.Keyword, 'DATAFILE': tokens.Keyword, 'DBA': tokens.Keyword, 'DISMOUNT': tokens.Keyword, 'DOUBLE': tokens.Keyword, 'DUMP': tokens.Keyword, 'ELSIF': tokens.Keyword, 'EVENTS': tokens.Keyword, 'EXCEPTIONS': tokens.Keyword, 'EXPLAIN': tokens.Keyword, 'EXTENT': tokens.Keyword, 'EXTERNALLY': tokens.Keyword, 'FLUSH': tokens.Keyword, 'FREELIST': tokens.Keyword, 'FREELISTS': tokens.Keyword, # groups seems too common as table name # 'GROUPS': tokens.Keyword, 'INDICATOR': tokens.Keyword, 'INITRANS': tokens.Keyword, 'INSTANCE': tokens.Keyword, 'LAYER': tokens.Keyword, 'LINK': tokens.Keyword, 'LISTS': tokens.Keyword, 'LOGFILE': tokens.Keyword, 'MANAGE': tokens.Keyword, 'MANUAL': tokens.Keyword, 'MAXDATAFILES': tokens.Keyword, 'MAXINSTANCES': tokens.Keyword, 'MAXLOGFILES': tokens.Keyword, 'MAXLOGHISTORY': tokens.Keyword, 'MAXLOGMEMBERS': tokens.Keyword, 'MAXTRANS': tokens.Keyword, 'MINEXTENTS': tokens.Keyword, 'MODULE': tokens.Keyword, 'MOUNT': tokens.Keyword, 'NOARCHIVELOG': tokens.Keyword, 'NOCACHE': tokens.Keyword, 'NOCYCLE': tokens.Keyword, 'NOMAXVALUE': tokens.Keyword, 'NOMINVALUE': tokens.Keyword, 'NOORDER': tokens.Keyword, 'NORESETLOGS': tokens.Keyword, 'NORMAL': tokens.Keyword, 'NOSORT': tokens.Keyword, 'OPTIMAL': tokens.Keyword, 'OWN': tokens.Keyword, 'PACKAGE': tokens.Keyword, 'PARALLEL': tokens.Keyword, 'PCTINCREASE': tokens.Keyword, 'PCTUSED': tokens.Keyword, 'PLAN': tokens.Keyword, 'PRIVATE': tokens.Keyword, 'PROFILE': tokens.Keyword, 'QUOTA': tokens.Keyword, 'RECOVER': tokens.Keyword, 'RESETLOGS': tokens.Keyword, 'RESTRICTED': tokens.Keyword, 'REUSE': tokens.Keyword, 'ROLES': tokens.Keyword, 'SAVEPOINT': tokens.Keyword, 'SCN': tokens.Keyword, 'SECTION': tokens.Keyword, 'SEGMENT': tokens.Keyword, 'SHARED': tokens.Keyword, 'SNAPSHOT': tokens.Keyword, 'SORT': tokens.Keyword, 'STATEMENT_ID': tokens.Keyword, 'STOP': tokens.Keyword, 'SWITCH': tokens.Keyword, 'TABLES': tokens.Keyword, 'TABLESPACE': tokens.Keyword, 'THREAD': tokens.Keyword, 'TIME': tokens.Keyword, 'TRACING': tokens.Keyword, 'TRANSACTION': tokens.Keyword, 'TRIGGERS': tokens.Keyword, 'UNLIMITED': tokens.Keyword, 'UNLOCK': tokens.Keyword, } # PostgreSQL Syntax KEYWORDS_PLPGSQL = { 'CONFLICT': tokens.Keyword, 'WINDOW': tokens.Keyword, 'PARTITION': tokens.Keyword, 'OVER': tokens.Keyword, 'PERFORM': tokens.Keyword, 'NOTICE': tokens.Keyword, 'PLPGSQL': tokens.Keyword, 'INHERIT': tokens.Keyword, 'INDEXES': tokens.Keyword, 'ON_ERROR_STOP': tokens.Keyword, 'BYTEA': tokens.Keyword, 'BIGSERIAL': tokens.Keyword, 'BIT VARYING': tokens.Keyword, 'BOX': tokens.Keyword, 'CHARACTER': tokens.Keyword, 'CHARACTER VARYING': tokens.Keyword, 'CIDR': tokens.Keyword, 'CIRCLE': tokens.Keyword, 'DOUBLE PRECISION': tokens.Keyword, 'INET': tokens.Keyword, 'JSON': tokens.Keyword, 'JSONB': tokens.Keyword, 'LINE': tokens.Keyword, 'LSEG': tokens.Keyword, 'MACADDR': tokens.Keyword, 'MONEY': tokens.Keyword, 'PATH': tokens.Keyword, 'PG_LSN': tokens.Keyword, 'POINT': tokens.Keyword, 'POLYGON': tokens.Keyword, 'SMALLSERIAL': tokens.Keyword, 'TSQUERY': tokens.Keyword, 'TSVECTOR': tokens.Keyword, 'TXID_SNAPSHOT': tokens.Keyword, 'UUID': tokens.Keyword, 'XML': tokens.Keyword, 'FOR': tokens.Keyword, 'IN': tokens.Keyword, 'LOOP': tokens.Keyword, } # Hive Syntax # hive 语法 KEYWORDS_HQL = { 'EXPLODE': tokens.Keyword, 'DIRECTORY': tokens.Keyword, 'DISTRIBUTE': tokens.Keyword, 'INCLUDE': tokens.Keyword, 'LOCATE': tokens.Keyword, 'OVERWRITE': tokens.Keyword, 'POSEXPLODE': tokens.Keyword, 'ARRAY_CONTAINS': tokens.Keyword, 'CMP': tokens.Keyword, 'COLLECT_LIST': tokens.Keyword, 'CONCAT': tokens.Keyword, 'CONDITION': tokens.Keyword, 'DATE_ADD': tokens.Keyword, 'DATE_SUB': tokens.Keyword, 'DECODE': tokens.Keyword, 'DBMS_OUTPUT': tokens.Keyword, 'ELEMENTS': tokens.Keyword, 'EXCHANGE': tokens.Keyword, 'EXTENDED': tokens.Keyword, 'FLOOR': tokens.Keyword, 'FOLLOWING': tokens.Keyword, 'FROM_UNIXTIME': tokens.Keyword, 'FTP': tokens.Keyword, 'HOUR': tokens.Keyword, 'INLINE': tokens.Keyword, 'INSTR': tokens.Keyword, 'LEN': tokens.Keyword, 'MAXELEMENT': tokens.Keyword, 'MAXINDEX': tokens.Keyword, 'MAX_PART_DATE': tokens.Keyword, 'MAX_PART_INT': tokens.Keyword, 'MAX_PART_STRING': tokens.Keyword, 'MINELEMENT': tokens.Keyword, 'MININDEX': tokens.Keyword, 'MIN_PART_DATE': tokens.Keyword, 'MIN_PART_INT': tokens.Keyword, 'MIN_PART_STRING': tokens.Keyword, 'NOW': tokens.Keyword, 'NVL': tokens.Keyword, 'NVL2': tokens.Keyword, 'PARSE_URL_TUPLE': tokens.Keyword, 'PART_LOC': tokens.Keyword, 'PART_COUNT': tokens.Keyword, 'PART_COUNT_BY': tokens.Keyword, 'PRINT': tokens.Keyword, 'PUT_LINE': tokens.Keyword, 'RANGE': tokens.Keyword, 'REDUCE': tokens.Keyword, 'REGEXP_REPLACE': tokens.Keyword, 'RESIGNAL': tokens.Keyword, 'RTRIM': tokens.Keyword, 'SIGN': tokens.Keyword, 'SIGNAL': tokens.Keyword, 'SIN': tokens.Keyword, 'SPLIT': tokens.Keyword, 'SQRT': tokens.Keyword, 'STACK': tokens.Keyword, 'STR': tokens.Keyword, 'SUBSTR': tokens.Keyword, 'SUMMARY': tokens.Keyword, 'TBLPROPERTIES': tokens.Keyword, 'TIMESTAMP_ISO': tokens.Keyword, 'TO_CHAR': tokens.Keyword, 'TO_DATE': tokens.Keyword, 'TO_TIMESTAMP': tokens.Keyword, 'TRUNC': tokens.Keyword, 'UNBOUNDED': tokens.Keyword, 'UNIQUEJOIN': tokens.Keyword, 'UNIX_TIMESTAMP': tokens.Keyword, 'UTC_TIMESTAMP': tokens.Keyword, 'VIEWS': tokens.Keyword, 'EXIT': tokens.Keyword, 'BREAK': tokens.Keyword, 'LEAVE': tokens.Keyword, }
30.72378
79
0.633961
import re from sqlparse import tokens def is_keyword(value): val = value.upper() return (KEYWORDS_COMMON.get(val) or KEYWORDS_ORACLE.get(val) or KEYWORDS_PLPGSQL.get(val) or KEYWORDS_HQL.get(val) or KEYWORDS.get(val, tokens.Name)), value SQL_REGEX = { 'root': [ (r'(--|# )\+.*?(\r\n|\r|\n|$)', tokens.Comment.Single.Hint), (r'/\*\+[\s\S]*?\*/', tokens.Comment.Multiline.Hint), (r'(--|# ).*?(\r\n|\r|\n|$)', tokens.Comment.Single), (r'/\*[\s\S]*?\*/', tokens.Comment.Multiline), (r'(\r\n|\r|\n)', tokens.Newline), (r'\s+?', tokens.Whitespace), (r':=', tokens.Assignment), (r'::', tokens.Punctuation), (r'\*', tokens.Wildcard), (r"`(``|[^`])*`", tokens.Name), (r"´(´´|[^´])*´", tokens.Name), (r'((?<!\S)\$(?:[_A-ZÀ-Ü]\w*)?\$)[\s\S]*?\1', tokens.Literal), (r'\?', tokens.Name.Placeholder), (r'%(\(\w+\))?s', tokens.Name.Placeholder), (r'(?<!\w)[$:?]\w+', tokens.Name.Placeholder), (r'\\\w+', tokens.Command), (r'(NOT\s+)?(IN)\b', tokens.Operator.Comparison), # see https://github.com/andialbrecht/sqlparse/pull/64 # AS and IN are special, it may be followed by a parenthesis, but # are never functions, see issue183 and issue507 (r'(CASE|IN|VALUES|USING|FROM|AS)\b', tokens.Keyword), (r'(@|hema . name` are valid identifier # TODO: Spaces before period not implemented (r'[A-ZÀ-Ü]\w*(?=\s*\.)', tokens.Name), # 'Name' . # FIXME(atronah): never match, # because `re.match` doesn't work with look-behind regexp feature (r'(?<=\.)[A-ZÀ-Ü]\w*', tokens.Name), (r'[A-ZÀ-Ü]\w*(?=\()', tokens.Name), (r'-?0x[\dA-F]+', tokens.Number.Hexadecimal), (r'-?\d*(\.\d+)?E-?\d+', tokens.Number.Float), (r'(?![_A-ZÀ-Ü])-?(\d+(\.\d*)|\.\d+)(?![_A-ZÀ-Ü])', tokens.Number.Float), (r'(?![_A-ZÀ-Ü])-?\d+(?![_A-ZÀ-Ü])', tokens.Number.Integer), (r"'(''|\\\\|\\'|[^'])*'", tokens.String.Single), (r'"(""|\\\\|\\"|[^"])*"', tokens.String.Symbol), (r'(""|".*?[^\\]")', tokens.String.Symbol), (r'(?<![\w\])])(\[[^\]\[]+\])', tokens.Name), (r'((LEFT\s+|RIGHT\s+|FULL\s+)?(INNER\s+|OUTER\s+|STRAIGHT\s+)?' r'|(CROSS\s+|NATURAL\s+)?)?JOIN\b', tokens.Keyword), (r'END(\s+IF|\s+LOOP|\s+WHILE)?\b', tokens.Keyword), (r'NOT\s+NULL\b', tokens.Keyword), (r'NULLS\s+(FIRST|LAST)\b', tokens.Keyword), (r'UNION\s+ALL\b', tokens.Keyword), (r'CREATE(\s+OR\s+REPLACE)?\b', tokens.Keyword.DDL), (r'DOUBLE\s+PRECISION\b', tokens.Name.Builtin), (r'GROUP\s+BY\b', tokens.Keyword), (r'ORDER\s+BY\b', tokens.Keyword), (r'HANDLER\s+FOR\b', tokens.Keyword), (r'(LATERAL\s+VIEW\s+)' r'(EXPLODE|INLINE|PARSE_URL_TUPLE|POSEXPLODE|STACK)\b', tokens.Keyword), (r"(AT|WITH')\s+TIME\s+ZONE\s+'[^']+'", tokens.Keyword.TZCast), (r'(NOT\s+)?(LIKE|ILIKE|RLIKE)\b', tokens.Operator.Comparison), (r'[0-9_A-ZÀ-Ü][_$ (r'[;:()\[\],\.]', tokens.Punctuation), (r'[<>=~!]+', tokens.Operator.Comparison), (r'[+/@ ]} #标签 FLAGS = re.IGNORECASE | re.UNICODE SQL_REGEX = [(re.compile(rx, FLAGS).match, tt) for rx, tt in SQL_REGEX['root']] # 通用关键字 KEYWORDS = { 'ABORT': tokens.Keyword, 'ABS': tokens.Keyword, 'ABSOLUTE': tokens.Keyword, 'ACCESS': tokens.Keyword, 'ADA': tokens.Keyword, 'ADD': tokens.Keyword, 'ADMIN': tokens.Keyword, 'AFTER': tokens.Keyword, 'AGGREGATE': tokens.Keyword, 'ALIAS': tokens.Keyword, 'ALL': tokens.Keyword, 'ALLOCATE': tokens.Keyword, 'ANALYSE': tokens.Keyword, 'ANALYZE': tokens.Keyword, 'ANY': tokens.Keyword, 'ARRAYLEN': tokens.Keyword, 'ARE': tokens.Keyword, 'ASC': tokens.Keyword.Order, 'ASENSITIVE': tokens.Keyword, 'ASSERTION': tokens.Keyword, 'ASSIGNMENT': tokens.Keyword, 'ASYMMETRIC': tokens.Keyword, 'AT': tokens.Keyword, 'ATOMIC': tokens.Keyword, 'AUDIT': tokens.Keyword, 'AUTHORIZATION': tokens.Keyword, 'AUTO_INCREMENT': tokens.Keyword, 'AVG': tokens.Keyword, 'BACKWARD': tokens.Keyword, 'BEFORE': tokens.Keyword, 'BEGIN': tokens.Keyword, 'BETWEEN': tokens.Keyword, 'BITVAR': tokens.Keyword, 'BIT_LENGTH': tokens.Keyword, 'BOTH': tokens.Keyword, 'BREADTH': tokens.Keyword, # 'C': tokens.Keyword, # most likely this is an alias 'CACHE': tokens.Keyword, 'CALL': tokens.Keyword, 'CALLED': tokens.Keyword, 'CARDINALITY': tokens.Keyword, 'CASCADE': tokens.Keyword, 'CASCADED': tokens.Keyword, 'CAST': tokens.Keyword, 'CATALOG': tokens.Keyword, 'CATALOG_NAME': tokens.Keyword, 'CHAIN': tokens.Keyword, 'CHARACTERISTICS': tokens.Keyword, 'CHARACTER_LENGTH': tokens.Keyword, 'CHARACTER_SET_CATALOG': tokens.Keyword, 'CHARACTER_SET_NAME': tokens.Keyword, 'CHARACTER_SET_SCHEMA': tokens.Keyword, 'CHAR_LENGTH': tokens.Keyword, 'CHARSET': tokens.Keyword, 'CHECK': tokens.Keyword, 'CHECKED': tokens.Keyword, 'CHECKPOINT': tokens.Keyword, 'CLASS': tokens.Keyword, 'CLASS_ORIGIN': tokens.Keyword, 'CLOB': tokens.Keyword, 'CLOSE': tokens.Keyword, 'CLUSTER': tokens.Keyword, 'COALESCE': tokens.Keyword, 'COBOL': tokens.Keyword, 'COLLATE': tokens.Keyword, 'COLLATION': tokens.Keyword, 'COLLATION_CATALOG': tokens.Keyword, 'COLLATION_NAME': tokens.Keyword, 'COLLATION_SCHEMA': tokens.Keyword, 'COLLECT': tokens.Keyword, 'COLUMN': tokens.Keyword, 'COLUMN_NAME': tokens.Keyword, 'COMPRESS': tokens.Keyword, 'COMMAND_FUNCTION': tokens.Keyword, 'COMMAND_FUNCTION_CODE': tokens.Keyword, 'COMMENT': tokens.Keyword, 'COMMIT': tokens.Keyword.DML, 'COMMITTED': tokens.Keyword, 'COMPLETION': tokens.Keyword, 'CONCURRENTLY': tokens.Keyword, 'CONDITION_NUMBER': tokens.Keyword, 'CONNECT': tokens.Keyword, 'CONNECTION': tokens.Keyword, 'CONNECTION_NAME': tokens.Keyword, 'CONSTRAINT': tokens.Keyword, 'CONSTRAINTS': tokens.Keyword, 'CONSTRAINT_CATALOG': tokens.Keyword, 'CONSTRAINT_NAME': tokens.Keyword, 'CONSTRAINT_SCHEMA': tokens.Keyword, 'CONSTRUCTOR': tokens.Keyword, 'CONTAINS': tokens.Keyword, 'CONTINUE': tokens.Keyword, 'CONVERSION': tokens.Keyword, 'CONVERT': tokens.Keyword, 'COPY': tokens.Keyword, 'CORRESPONDING': tokens.Keyword, 'COUNT': tokens.Keyword, 'CREATEDB': tokens.Keyword, 'CREATEUSER': tokens.Keyword, 'CROSS': tokens.Keyword, 'CUBE': tokens.Keyword, 'CURRENT': tokens.Keyword, 'CURRENT_DATE': tokens.Keyword, 'CURRENT_PATH': tokens.Keyword, 'CURRENT_ROLE': tokens.Keyword, 'CURRENT_TIME': tokens.Keyword, 'CURRENT_TIMESTAMP': tokens.Keyword, 'CURRENT_USER': tokens.Keyword, 'CURSOR': tokens.Keyword, 'CURSOR_NAME': tokens.Keyword, 'CYCLE': tokens.Keyword, 'DATA': tokens.Keyword, 'DATABASE': tokens.Keyword, 'DATETIME_INTERVAL_CODE': tokens.Keyword, 'DATETIME_INTERVAL_PRECISION': tokens.Keyword, 'DAY': tokens.Keyword, 'DEALLOCATE': tokens.Keyword, 'DECLARE': tokens.Keyword, 'DEFAULT': tokens.Keyword, 'DEFAULTS': tokens.Keyword, 'DEFERRABLE': tokens.Keyword, 'DEFERRED': tokens.Keyword, 'DEFINED': tokens.Keyword, 'DEFINER': tokens.Keyword, 'DELIMITER': tokens.Keyword, 'DELIMITERS': tokens.Keyword, 'DEREF': tokens.Keyword, 'DESC': tokens.Keyword.Order, 'DESCRIBE': tokens.Keyword, 'DESCRIPTOR': tokens.Keyword, 'DESTROY': tokens.Keyword, 'DESTRUCTOR': tokens.Keyword, 'DETERMINISTIC': tokens.Keyword, 'DIAGNOSTICS': tokens.Keyword, 'DICTIONARY': tokens.Keyword, 'DISABLE': tokens.Keyword, 'DISCONNECT': tokens.Keyword, 'DISPATCH': tokens.Keyword, 'DO': tokens.Keyword, 'DOMAIN': tokens.Keyword, 'DYNAMIC': tokens.Keyword, 'DYNAMIC_FUNCTION': tokens.Keyword, 'DYNAMIC_FUNCTION_CODE': tokens.Keyword, 'EACH': tokens.Keyword, 'ENABLE': tokens.Keyword, 'ENCODING': tokens.Keyword, 'ENCRYPTED': tokens.Keyword, 'END-EXEC': tokens.Keyword, 'ENGINE': tokens.Keyword, 'EQUALS': tokens.Keyword, 'ESCAPE': tokens.Keyword, 'EVERY': tokens.Keyword, 'EXCEPT': tokens.Keyword, 'EXCEPTION': tokens.Keyword, 'EXCLUDING': tokens.Keyword, 'EXCLUSIVE': tokens.Keyword, 'EXEC': tokens.Keyword, 'EXECUTE': tokens.Keyword, 'EXISTING': tokens.Keyword, 'EXISTS': tokens.Keyword, 'EXPLAIN': tokens.Keyword, 'EXTERNAL': tokens.Keyword, 'EXTRACT': tokens.Keyword, 'FALSE': tokens.Keyword, 'FETCH': tokens.Keyword, 'FILE': tokens.Keyword, 'FINAL': tokens.Keyword, 'FIRST': tokens.Keyword, 'FORCE': tokens.Keyword, 'FOREACH': tokens.Keyword, 'FOREIGN': tokens.Keyword, 'FORTRAN': tokens.Keyword, 'FORWARD': tokens.Keyword, 'FOUND': tokens.Keyword, 'FREE': tokens.Keyword, 'FREEZE': tokens.Keyword, 'FULL': tokens.Keyword, 'FUNCTION': tokens.Keyword, # 'G': tokens.Keyword, 'GENERAL': tokens.Keyword, 'GENERATED': tokens.Keyword, 'GET': tokens.Keyword, 'GLOBAL': tokens.Keyword, 'GO': tokens.Keyword, 'GOTO': tokens.Keyword, 'GRANT': tokens.Keyword, 'GRANTED': tokens.Keyword, 'GROUPING': tokens.Keyword, 'HAVING': tokens.Keyword, 'HIERARCHY': tokens.Keyword, 'HOLD': tokens.Keyword, 'HOUR': tokens.Keyword, 'HOST': tokens.Keyword, 'IDENTIFIED': tokens.Keyword, 'IDENTITY': tokens.Keyword, 'IGNORE': tokens.Keyword, 'ILIKE': tokens.Keyword, 'IMMEDIATE': tokens.Keyword, 'IMMUTABLE': tokens.Keyword, 'IMPLEMENTATION': tokens.Keyword, 'IMPLICIT': tokens.Keyword, 'INCLUDING': tokens.Keyword, 'INCREMENT': tokens.Keyword, 'INDEX': tokens.Keyword, 'INDITCATOR': tokens.Keyword, 'INFIX': tokens.Keyword, 'INHERITS': tokens.Keyword, 'INITIAL': tokens.Keyword, 'INITIALIZE': tokens.Keyword, 'INITIALLY': tokens.Keyword, 'INOUT': tokens.Keyword, 'INPUT': tokens.Keyword, 'INSENSITIVE': tokens.Keyword, 'INSTANTIABLE': tokens.Keyword, 'INSTEAD': tokens.Keyword, 'INTERSECT': tokens.Keyword, 'INTO': tokens.Keyword, 'INVOKER': tokens.Keyword, 'IS': tokens.Keyword, 'ISNULL': tokens.Keyword, 'ISOLATION': tokens.Keyword, 'ITERATE': tokens.Keyword, # 'K': tokens.Keyword, 'KEY': tokens.Keyword, 'KEY_MEMBER': tokens.Keyword, 'KEY_TYPE': tokens.Keyword, 'LANCOMPILER': tokens.Keyword, 'LANGUAGE': tokens.Keyword, 'LARGE': tokens.Keyword, 'LAST': tokens.Keyword, 'LATERAL': tokens.Keyword, 'LEADING': tokens.Keyword, 'LENGTH': tokens.Keyword, 'LESS': tokens.Keyword, 'LEVEL': tokens.Keyword, 'LIMIT': tokens.Keyword, 'LISTEN': tokens.Keyword, 'LOAD': tokens.Keyword, 'LOCAL': tokens.Keyword, 'LOCALTIME': tokens.Keyword, 'LOCALTIMESTAMP': tokens.Keyword, 'LOCATION': tokens.Keyword, 'LOCATOR': tokens.Keyword, 'LOCK': tokens.Keyword, 'LOWER': tokens.Keyword, # 'M': tokens.Keyword, 'MAP': tokens.Keyword, 'MATCH': tokens.Keyword, 'MAXEXTENTS': tokens.Keyword, 'MAXVALUE': tokens.Keyword, 'MESSAGE_LENGTH': tokens.Keyword, 'MESSAGE_OCTET_LENGTH': tokens.Keyword, 'MESSAGE_TEXT': tokens.Keyword, 'METHOD': tokens.Keyword, 'MINUTE': tokens.Keyword, 'MINUS': tokens.Keyword, 'MINVALUE': tokens.Keyword, 'MOD': tokens.Keyword, 'MODE': tokens.Keyword, 'MODIFIES': tokens.Keyword, 'MODIFY': tokens.Keyword, 'MONTH': tokens.Keyword, 'MORE': tokens.Keyword, 'MOVE': tokens.Keyword, 'MUMPS': tokens.Keyword, 'NAMES': tokens.Keyword, 'NATIONAL': tokens.Keyword, 'NATURAL': tokens.Keyword, 'NCHAR': tokens.Keyword, 'NCLOB': tokens.Keyword, 'NEW': tokens.Keyword, 'NEXT': tokens.Keyword, 'NO': tokens.Keyword, 'NOAUDIT': tokens.Keyword, 'NOCOMPRESS': tokens.Keyword, 'NOCREATEDB': tokens.Keyword, 'NOCREATEUSER': tokens.Keyword, 'NONE': tokens.Keyword, 'NOT': tokens.Keyword, 'NOTFOUND': tokens.Keyword, 'NOTHING': tokens.Keyword, 'NOTIFY': tokens.Keyword, 'NOTNULL': tokens.Keyword, 'NOWAIT': tokens.Keyword, 'NULL': tokens.Keyword, 'NULLABLE': tokens.Keyword, 'NULLIF': tokens.Keyword, 'OBJECT': tokens.Keyword, 'OCTET_LENGTH': tokens.Keyword, 'OF': tokens.Keyword, 'OFF': tokens.Keyword, 'OFFLINE': tokens.Keyword, 'OFFSET': tokens.Keyword, 'OIDS': tokens.Keyword, 'OLD': tokens.Keyword, 'ONLINE': tokens.Keyword, 'ONLY': tokens.Keyword, 'OPEN': tokens.Keyword, 'OPERATION': tokens.Keyword, 'OPERATOR': tokens.Keyword, 'OPTION': tokens.Keyword, 'OPTIONS': tokens.Keyword, 'ORDINALITY': tokens.Keyword, 'OUT': tokens.Keyword, 'OUTPUT': tokens.Keyword, 'OVERLAPS': tokens.Keyword, 'OVERLAY': tokens.Keyword, 'OVERRIDING': tokens.Keyword, 'OWNER': tokens.Keyword, 'QUARTER': tokens.Keyword, 'PAD': tokens.Keyword, 'PARAMETER': tokens.Keyword, 'PARAMETERS': tokens.Keyword, 'PARAMETER_MODE': tokens.Keyword, 'PARAMETER_NAME': tokens.Keyword, 'PARAMETER_ORDINAL_POSITION': tokens.Keyword, 'PARAMETER_SPECIFIC_CATALOG': tokens.Keyword, 'PARAMETER_SPECIFIC_NAME': tokens.Keyword, 'PARAMETER_SPECIFIC_SCHEMA': tokens.Keyword, 'PARTIAL': tokens.Keyword, 'PASCAL': tokens.Keyword, 'PCTFREE': tokens.Keyword, 'PENDANT': tokens.Keyword, 'PLACING': tokens.Keyword, 'PLI': tokens.Keyword, 'POSITION': tokens.Keyword, 'POSTFIX': tokens.Keyword, 'PRECISION': tokens.Keyword, 'PREFIX': tokens.Keyword, 'PREORDER': tokens.Keyword, 'PREPARE': tokens.Keyword, 'PRESERVE': tokens.Keyword, 'PRIMARY': tokens.Keyword, 'PRIOR': tokens.Keyword, 'PRIVILEGES': tokens.Keyword, 'PROCEDURAL': tokens.Keyword, 'PROCEDURE': tokens.Keyword, 'PUBLIC': tokens.Keyword, 'RAISE': tokens.Keyword, 'RAW': tokens.Keyword, 'READ': tokens.Keyword, 'READS': tokens.Keyword, 'RECHECK': tokens.Keyword, 'RECURSIVE': tokens.Keyword, 'REF': tokens.Keyword, 'REFERENCES': tokens.Keyword, 'REFERENCING': tokens.Keyword, 'REINDEX': tokens.Keyword, 'RELATIVE': tokens.Keyword, 'RENAME': tokens.Keyword, 'REPEATABLE': tokens.Keyword, 'RESET': tokens.Keyword, 'RESOURCE': tokens.Keyword, 'RESTART': tokens.Keyword, 'RESTRICT': tokens.Keyword, 'RESULT': tokens.Keyword, 'RETURN': tokens.Keyword, 'RETURNED_LENGTH': tokens.Keyword, 'RETURNED_OCTET_LENGTH': tokens.Keyword, 'RETURNED_SQLSTATE': tokens.Keyword, 'RETURNING': tokens.Keyword, 'RETURNS': tokens.Keyword, 'REVOKE': tokens.Keyword, 'RIGHT': tokens.Keyword, 'ROLE': tokens.Keyword, 'ROLLBACK': tokens.Keyword.DML, 'ROLLUP': tokens.Keyword, 'ROUTINE': tokens.Keyword, 'ROUTINE_CATALOG': tokens.Keyword, 'ROUTINE_NAME': tokens.Keyword, 'ROUTINE_SCHEMA': tokens.Keyword, 'ROW': tokens.Keyword, 'ROWS': tokens.Keyword, 'ROW_COUNT': tokens.Keyword, 'RULE': tokens.Keyword, 'SAVE_POINT': tokens.Keyword, 'SCALE': tokens.Keyword, 'SCHEMA': tokens.Keyword, 'SCHEMA_NAME': tokens.Keyword, 'SCOPE': tokens.Keyword, 'SCROLL': tokens.Keyword, 'SEARCH': tokens.Keyword, 'SECOND': tokens.Keyword, 'SECURITY': tokens.Keyword, 'SELF': tokens.Keyword, 'SENSITIVE': tokens.Keyword, 'SEQUENCE': tokens.Keyword, 'SERIALIZABLE': tokens.Keyword, 'SERVER_NAME': tokens.Keyword, 'SESSION': tokens.Keyword, 'SESSION_USER': tokens.Keyword, 'SETOF': tokens.Keyword, 'SETS': tokens.Keyword, 'SHARE': tokens.Keyword, 'SHOW': tokens.Keyword, 'SIMILAR': tokens.Keyword, 'SIMPLE': tokens.Keyword, 'SIZE': tokens.Keyword, 'SOME': tokens.Keyword, 'SOURCE': tokens.Keyword, 'SPACE': tokens.Keyword, 'SPECIFIC': tokens.Keyword, 'SPECIFICTYPE': tokens.Keyword, 'SPECIFIC_NAME': tokens.Keyword, 'SQL': tokens.Keyword, 'SQLBUF': tokens.Keyword, 'SQLCODE': tokens.Keyword, 'SQLERROR': tokens.Keyword, 'SQLEXCEPTION': tokens.Keyword, 'SQLSTATE': tokens.Keyword, 'SQLWARNING': tokens.Keyword, 'STABLE': tokens.Keyword, 'START': tokens.Keyword.DML, # 'STATE': tokens.Keyword, 'STATEMENT': tokens.Keyword, 'STATIC': tokens.Keyword, 'STATISTICS': tokens.Keyword, 'STDIN': tokens.Keyword, 'STDOUT': tokens.Keyword, 'STORAGE': tokens.Keyword, 'STRICT': tokens.Keyword, 'STRUCTURE': tokens.Keyword, 'STYPE': tokens.Keyword, 'SUBCLASS_ORIGIN': tokens.Keyword, 'SUBLIST': tokens.Keyword, 'SUBSTRING': tokens.Keyword, 'SUCCESSFUL': tokens.Keyword, 'SUM': tokens.Keyword, 'SYMMETRIC': tokens.Keyword, 'SYNONYM': tokens.Keyword, 'SYSID': tokens.Keyword, 'SYSTEM': tokens.Keyword, 'SYSTEM_USER': tokens.Keyword, 'TABLE': tokens.Keyword, 'TABLE_NAME': tokens.Keyword, 'TEMP': tokens.Keyword, 'TEMPLATE': tokens.Keyword, 'TEMPORARY': tokens.Keyword, 'TERMINATE': tokens.Keyword, 'THAN': tokens.Keyword, 'TIMESTAMP': tokens.Keyword, 'TIMEZONE_HOUR': tokens.Keyword, 'TIMEZONE_MINUTE': tokens.Keyword, 'TO': tokens.Keyword, 'TOAST': tokens.Keyword, 'TRAILING': tokens.Keyword, 'TRANSATION': tokens.Keyword, 'TRANSACTIONS_COMMITTED': tokens.Keyword, 'TRANSACTIONS_ROLLED_BACK': tokens.Keyword, 'TRANSATION_ACTIVE': tokens.Keyword, 'TRANSFORM': tokens.Keyword, 'TRANSFORMS': tokens.Keyword, 'TRANSLATE': tokens.Keyword, 'TRANSLATION': tokens.Keyword, 'TREAT': tokens.Keyword, 'TRIGGER': tokens.Keyword, 'TRIGGER_CATALOG': tokens.Keyword, 'TRIGGER_NAME': tokens.Keyword, 'TRIGGER_SCHEMA': tokens.Keyword, 'TRIM': tokens.Keyword, 'TRUE': tokens.Keyword, 'TRUNCATE': tokens.Keyword, 'TRUSTED': tokens.Keyword, 'TYPE': tokens.Keyword, 'UID': tokens.Keyword, 'UNCOMMITTED': tokens.Keyword, 'UNDER': tokens.Keyword, 'UNENCRYPTED': tokens.Keyword, 'UNION': tokens.Keyword, 'UNIQUE': tokens.Keyword, 'UNKNOWN': tokens.Keyword, 'UNLISTEN': tokens.Keyword, 'UNNAMED': tokens.Keyword, 'UNNEST': tokens.Keyword, 'UNTIL': tokens.Keyword, 'UPPER': tokens.Keyword, 'USAGE': tokens.Keyword, 'USE': tokens.Keyword, 'USER': tokens.Keyword, 'USER_DEFINED_TYPE_CATALOG': tokens.Keyword, 'USER_DEFINED_TYPE_NAME': tokens.Keyword, 'USER_DEFINED_TYPE_SCHEMA': tokens.Keyword, 'USING': tokens.Keyword, 'VACUUM': tokens.Keyword, 'VALID': tokens.Keyword, 'VALIDATE': tokens.Keyword, 'VALIDATOR': tokens.Keyword, 'VALUES': tokens.Keyword, 'VARIABLE': tokens.Keyword, 'VERBOSE': tokens.Keyword, 'VERSION': tokens.Keyword, 'VIEW': tokens.Keyword, 'VOLATILE': tokens.Keyword, 'WEEK': tokens.Keyword, 'WHENEVER': tokens.Keyword, 'WITH': tokens.Keyword.CTE, 'WITHOUT': tokens.Keyword, 'WORK': tokens.Keyword, 'WRITE': tokens.Keyword, 'YEAR': tokens.Keyword, 'ZONE': tokens.Keyword, # Name.Builtin 'ARRAY': tokens.Name.Builtin, 'BIGINT': tokens.Name.Builtin, 'BINARY': tokens.Name.Builtin, 'BIT': tokens.Name.Builtin, 'BLOB': tokens.Name.Builtin, 'BOOLEAN': tokens.Name.Builtin, 'CHAR': tokens.Name.Builtin, 'CHARACTER': tokens.Name.Builtin, 'DATE': tokens.Name.Builtin, 'DEC': tokens.Name.Builtin, 'DECIMAL': tokens.Name.Builtin, 'FILE_TYPE': tokens.Name.Builtin, 'FLOAT': tokens.Name.Builtin, 'INT': tokens.Name.Builtin, 'INT8': tokens.Name.Builtin, 'INTEGER': tokens.Name.Builtin, 'INTERVAL': tokens.Name.Builtin, 'LONG': tokens.Name.Builtin, 'NATURALN': tokens.Name.Builtin, 'NVARCHAR': tokens.Name.Builtin, 'NUMBER': tokens.Name.Builtin, 'NUMERIC': tokens.Name.Builtin, 'PLS_INTEGER': tokens.Name.Builtin, 'POSITIVE': tokens.Name.Builtin, 'POSITIVEN': tokens.Name.Builtin, 'REAL': tokens.Name.Builtin, 'ROWID': tokens.Name.Builtin, 'ROWLABEL': tokens.Name.Builtin, 'ROWNUM': tokens.Name.Builtin, 'SERIAL': tokens.Name.Builtin, 'SERIAL8': tokens.Name.Builtin, 'SIGNED': tokens.Name.Builtin, 'SIGNTYPE': tokens.Name.Builtin, 'SIMPLE_DOUBLE': tokens.Name.Builtin, 'SIMPLE_FLOAT': tokens.Name.Builtin, 'SIMPLE_INTEGER': tokens.Name.Builtin, 'SMALLINT': tokens.Name.Builtin, 'SYS_REFCURSOR': tokens.Name.Builtin, 'SYSDATE': tokens.Name, 'TEXT': tokens.Name.Builtin, 'TINYINT': tokens.Name.Builtin, 'UNSIGNED': tokens.Name.Builtin, 'UROWID': tokens.Name.Builtin, 'UTL_FILE': tokens.Name.Builtin, 'VARCHAR': tokens.Name.Builtin, 'VARCHAR2': tokens.Name.Builtin, 'VARYING': tokens.Name.Builtin, } KEYWORDS_COMMON = { 'SELECT': tokens.Keyword.DML, 'INSERT': tokens.Keyword.DML, 'DELETE': tokens.Keyword.DML, 'UPDATE': tokens.Keyword.DML, 'UPSERT': tokens.Keyword.DML, 'REPLACE': tokens.Keyword.DML, 'MERGE': tokens.Keyword.DML, 'DROP': tokens.Keyword.DDL, 'CREATE': tokens.Keyword.DDL, 'ALTER': tokens.Keyword.DDL, 'WHERE': tokens.Keyword, 'FROM': tokens.Keyword, 'INNER': tokens.Keyword, 'JOIN': tokens.Keyword, 'STRAIGHT_JOIN': tokens.Keyword, 'AND': tokens.Keyword, 'OR': tokens.Keyword, 'LIKE': tokens.Keyword, 'ON': tokens.Keyword, 'IN': tokens.Keyword, 'SET': tokens.Keyword, 'BY': tokens.Keyword, 'GROUP': tokens.Keyword, 'ORDER': tokens.Keyword, 'LEFT': tokens.Keyword, 'OUTER': tokens.Keyword, 'FULL': tokens.Keyword, 'IF': tokens.Keyword, 'END': tokens.Keyword, 'THEN': tokens.Keyword, 'LOOP': tokens.Keyword, 'AS': tokens.Keyword, 'ELSE': tokens.Keyword, 'FOR': tokens.Keyword, 'WHILE': tokens.Keyword, 'CASE': tokens.Keyword, 'WHEN': tokens.Keyword, 'MIN': tokens.Keyword, 'MAX': tokens.Keyword, 'DISTINCT': tokens.Keyword, } # oracle 关键字 KEYWORDS_ORACLE = { 'ARCHIVE': tokens.Keyword, 'ARCHIVELOG': tokens.Keyword, 'BACKUP': tokens.Keyword, 'BECOME': tokens.Keyword, 'BLOCK': tokens.Keyword, 'BODY': tokens.Keyword, 'CANCEL': tokens.Keyword, 'CHANGE': tokens.Keyword, 'COMPILE': tokens.Keyword, 'CONTENTS': tokens.Keyword, 'CONTROLFILE': tokens.Keyword, 'DATAFILE': tokens.Keyword, 'DBA': tokens.Keyword, 'DISMOUNT': tokens.Keyword, 'DOUBLE': tokens.Keyword, 'DUMP': tokens.Keyword, 'ELSIF': tokens.Keyword, 'EVENTS': tokens.Keyword, 'EXCEPTIONS': tokens.Keyword, 'EXPLAIN': tokens.Keyword, 'EXTENT': tokens.Keyword, 'EXTERNALLY': tokens.Keyword, 'FLUSH': tokens.Keyword, 'FREELIST': tokens.Keyword, 'FREELISTS': tokens.Keyword, # groups seems too common as table name # 'GROUPS': tokens.Keyword, 'INDICATOR': tokens.Keyword, 'INITRANS': tokens.Keyword, 'INSTANCE': tokens.Keyword, 'LAYER': tokens.Keyword, 'LINK': tokens.Keyword, 'LISTS': tokens.Keyword, 'LOGFILE': tokens.Keyword, 'MANAGE': tokens.Keyword, 'MANUAL': tokens.Keyword, 'MAXDATAFILES': tokens.Keyword, 'MAXINSTANCES': tokens.Keyword, 'MAXLOGFILES': tokens.Keyword, 'MAXLOGHISTORY': tokens.Keyword, 'MAXLOGMEMBERS': tokens.Keyword, 'MAXTRANS': tokens.Keyword, 'MINEXTENTS': tokens.Keyword, 'MODULE': tokens.Keyword, 'MOUNT': tokens.Keyword, 'NOARCHIVELOG': tokens.Keyword, 'NOCACHE': tokens.Keyword, 'NOCYCLE': tokens.Keyword, 'NOMAXVALUE': tokens.Keyword, 'NOMINVALUE': tokens.Keyword, 'NOORDER': tokens.Keyword, 'NORESETLOGS': tokens.Keyword, 'NORMAL': tokens.Keyword, 'NOSORT': tokens.Keyword, 'OPTIMAL': tokens.Keyword, 'OWN': tokens.Keyword, 'PACKAGE': tokens.Keyword, 'PARALLEL': tokens.Keyword, 'PCTINCREASE': tokens.Keyword, 'PCTUSED': tokens.Keyword, 'PLAN': tokens.Keyword, 'PRIVATE': tokens.Keyword, 'PROFILE': tokens.Keyword, 'QUOTA': tokens.Keyword, 'RECOVER': tokens.Keyword, 'RESETLOGS': tokens.Keyword, 'RESTRICTED': tokens.Keyword, 'REUSE': tokens.Keyword, 'ROLES': tokens.Keyword, 'SAVEPOINT': tokens.Keyword, 'SCN': tokens.Keyword, 'SECTION': tokens.Keyword, 'SEGMENT': tokens.Keyword, 'SHARED': tokens.Keyword, 'SNAPSHOT': tokens.Keyword, 'SORT': tokens.Keyword, 'STATEMENT_ID': tokens.Keyword, 'STOP': tokens.Keyword, 'SWITCH': tokens.Keyword, 'TABLES': tokens.Keyword, 'TABLESPACE': tokens.Keyword, 'THREAD': tokens.Keyword, 'TIME': tokens.Keyword, 'TRACING': tokens.Keyword, 'TRANSACTION': tokens.Keyword, 'TRIGGERS': tokens.Keyword, 'UNLIMITED': tokens.Keyword, 'UNLOCK': tokens.Keyword, } # PostgreSQL Syntax KEYWORDS_PLPGSQL = { 'CONFLICT': tokens.Keyword, 'WINDOW': tokens.Keyword, 'PARTITION': tokens.Keyword, 'OVER': tokens.Keyword, 'PERFORM': tokens.Keyword, 'NOTICE': tokens.Keyword, 'PLPGSQL': tokens.Keyword, 'INHERIT': tokens.Keyword, 'INDEXES': tokens.Keyword, 'ON_ERROR_STOP': tokens.Keyword, 'BYTEA': tokens.Keyword, 'BIGSERIAL': tokens.Keyword, 'BIT VARYING': tokens.Keyword, 'BOX': tokens.Keyword, 'CHARACTER': tokens.Keyword, 'CHARACTER VARYING': tokens.Keyword, 'CIDR': tokens.Keyword, 'CIRCLE': tokens.Keyword, 'DOUBLE PRECISION': tokens.Keyword, 'INET': tokens.Keyword, 'JSON': tokens.Keyword, 'JSONB': tokens.Keyword, 'LINE': tokens.Keyword, 'LSEG': tokens.Keyword, 'MACADDR': tokens.Keyword, 'MONEY': tokens.Keyword, 'PATH': tokens.Keyword, 'PG_LSN': tokens.Keyword, 'POINT': tokens.Keyword, 'POLYGON': tokens.Keyword, 'SMALLSERIAL': tokens.Keyword, 'TSQUERY': tokens.Keyword, 'TSVECTOR': tokens.Keyword, 'TXID_SNAPSHOT': tokens.Keyword, 'UUID': tokens.Keyword, 'XML': tokens.Keyword, 'FOR': tokens.Keyword, 'IN': tokens.Keyword, 'LOOP': tokens.Keyword, } # Hive Syntax # hive 语法 KEYWORDS_HQL = { 'EXPLODE': tokens.Keyword, 'DIRECTORY': tokens.Keyword, 'DISTRIBUTE': tokens.Keyword, 'INCLUDE': tokens.Keyword, 'LOCATE': tokens.Keyword, 'OVERWRITE': tokens.Keyword, 'POSEXPLODE': tokens.Keyword, 'ARRAY_CONTAINS': tokens.Keyword, 'CMP': tokens.Keyword, 'COLLECT_LIST': tokens.Keyword, 'CONCAT': tokens.Keyword, 'CONDITION': tokens.Keyword, 'DATE_ADD': tokens.Keyword, 'DATE_SUB': tokens.Keyword, 'DECODE': tokens.Keyword, 'DBMS_OUTPUT': tokens.Keyword, 'ELEMENTS': tokens.Keyword, 'EXCHANGE': tokens.Keyword, 'EXTENDED': tokens.Keyword, 'FLOOR': tokens.Keyword, 'FOLLOWING': tokens.Keyword, 'FROM_UNIXTIME': tokens.Keyword, 'FTP': tokens.Keyword, 'HOUR': tokens.Keyword, 'INLINE': tokens.Keyword, 'INSTR': tokens.Keyword, 'LEN': tokens.Keyword, 'MAXELEMENT': tokens.Keyword, 'MAXINDEX': tokens.Keyword, 'MAX_PART_DATE': tokens.Keyword, 'MAX_PART_INT': tokens.Keyword, 'MAX_PART_STRING': tokens.Keyword, 'MINELEMENT': tokens.Keyword, 'MININDEX': tokens.Keyword, 'MIN_PART_DATE': tokens.Keyword, 'MIN_PART_INT': tokens.Keyword, 'MIN_PART_STRING': tokens.Keyword, 'NOW': tokens.Keyword, 'NVL': tokens.Keyword, 'NVL2': tokens.Keyword, 'PARSE_URL_TUPLE': tokens.Keyword, 'PART_LOC': tokens.Keyword, 'PART_COUNT': tokens.Keyword, 'PART_COUNT_BY': tokens.Keyword, 'PRINT': tokens.Keyword, 'PUT_LINE': tokens.Keyword, 'RANGE': tokens.Keyword, 'REDUCE': tokens.Keyword, 'REGEXP_REPLACE': tokens.Keyword, 'RESIGNAL': tokens.Keyword, 'RTRIM': tokens.Keyword, 'SIGN': tokens.Keyword, 'SIGNAL': tokens.Keyword, 'SIN': tokens.Keyword, 'SPLIT': tokens.Keyword, 'SQRT': tokens.Keyword, 'STACK': tokens.Keyword, 'STR': tokens.Keyword, 'SUBSTR': tokens.Keyword, 'SUMMARY': tokens.Keyword, 'TBLPROPERTIES': tokens.Keyword, 'TIMESTAMP_ISO': tokens.Keyword, 'TO_CHAR': tokens.Keyword, 'TO_DATE': tokens.Keyword, 'TO_TIMESTAMP': tokens.Keyword, 'TRUNC': tokens.Keyword, 'UNBOUNDED': tokens.Keyword, 'UNIQUEJOIN': tokens.Keyword, 'UNIX_TIMESTAMP': tokens.Keyword, 'UTC_TIMESTAMP': tokens.Keyword, 'VIEWS': tokens.Keyword, 'EXIT': tokens.Keyword, 'BREAK': tokens.Keyword, 'LEAVE': tokens.Keyword, }
true
true
f7fe5f5f307063ef2a363000c8b682531216c607
1,618
py
Python
dataset/SamplingDataSetRnet.py
swpucwf/MTCNN_Pytorch
d9ffd1ca8ea28eb4f7cd1e5d24d2ec8402f0e0b0
[ "Apache-2.0" ]
null
null
null
dataset/SamplingDataSetRnet.py
swpucwf/MTCNN_Pytorch
d9ffd1ca8ea28eb4f7cd1e5d24d2ec8402f0e0b0
[ "Apache-2.0" ]
null
null
null
dataset/SamplingDataSetRnet.py
swpucwf/MTCNN_Pytorch
d9ffd1ca8ea28eb4f7cd1e5d24d2ec8402f0e0b0
[ "Apache-2.0" ]
null
null
null
import torch from torch.utils.data import Dataset import os from torchvision.transforms import transforms from PIL import Image class FaceDataset(Dataset): def __init__(self,path_1=r"D:\DataSet",path_2="D:\DataSet\wider",size=24,tf=transforms.ToTensor()): super(FaceDataset, self).__init__() self.dataset = [] self.size = size for path in [path_2,path_1]: self.base_path_1 = path self.path = os.path.join(self.base_path_1,str(self.size)) for txt in ["positive.txt","negative.txt","part.txt"]: with open(os.path.join(self.path,txt),"r") as f: data = f.readlines() for line in data: line = line.strip().split() img_path = os.path.join(self.path,line[0]) benkdata = " ".join(line[1:]) self.dataset.append([img_path,benkdata]) self.tf = tf def __len__(self): return len(self.dataset) # 数据集长度 def __getitem__(self, index): # 获取数据 img_path,strs = self.dataset[index] strs = strs.strip().split(" ") # 取一条数据,去掉前后字符串,再按空格分割 #标签:置信度+偏移量 cond = torch.Tensor([int(strs[0])]) # []莫丢,否则指定的是shape offset = torch.Tensor([float(strs[1]),float(strs[2]),float(strs[3]),float(strs[4])]) # # #样本:img_data # print(img_path) img = Image.open(img_path) img = self.tf(img) return img,cond,offset # 测试 if __name__ == '__main__': dataset = FaceDataset(size=12) print(dataset[0][0].shape) print(dataset[0][0])
32.36
103
0.573548
import torch from torch.utils.data import Dataset import os from torchvision.transforms import transforms from PIL import Image class FaceDataset(Dataset): def __init__(self,path_1=r"D:\DataSet",path_2="D:\DataSet\wider",size=24,tf=transforms.ToTensor()): super(FaceDataset, self).__init__() self.dataset = [] self.size = size for path in [path_2,path_1]: self.base_path_1 = path self.path = os.path.join(self.base_path_1,str(self.size)) for txt in ["positive.txt","negative.txt","part.txt"]: with open(os.path.join(self.path,txt),"r") as f: data = f.readlines() for line in data: line = line.strip().split() img_path = os.path.join(self.path,line[0]) benkdata = " ".join(line[1:]) self.dataset.append([img_path,benkdata]) self.tf = tf def __len__(self): return len(self.dataset) def __getitem__(self, index): img_path,strs = self.dataset[index] strs = strs.strip().split(" ") cond = torch.Tensor([int(strs[0])]) offset = torch.Tensor([float(strs[1]),float(strs[2]),float(strs[3]),float(strs[4])]) img = Image.open(img_path) img = self.tf(img) return img,cond,offset if __name__ == '__main__': dataset = FaceDataset(size=12) print(dataset[0][0].shape) print(dataset[0][0])
true
true
f7fe5f7ea5da7a1c2f0d7e15ad992c72ffe12b0f
177
py
Python
scripts/add_path.py
XueLianjie/rpg_trajectory_evaluation
7f49501d0fa09b5fa3790635ce68653ad8420d93
[ "MIT" ]
636
2018-10-03T10:37:54.000Z
2022-03-29T12:36:11.000Z
scripts/add_path.py
XueLianjie/rpg_trajectory_evaluation
7f49501d0fa09b5fa3790635ce68653ad8420d93
[ "MIT" ]
32
2018-10-12T07:43:39.000Z
2022-03-18T09:46:56.000Z
scripts/add_path.py
XueLianjie/rpg_trajectory_evaluation
7f49501d0fa09b5fa3790635ce68653ad8420d93
[ "MIT" ]
275
2018-10-06T12:48:46.000Z
2022-03-14T07:52:48.000Z
#!/usr/bin/env python2 import os import sys sys.path.append( os.path.join(os.path.dirname(os.path.abspath(__file__)), '../src/rpg_trajectory_evaluation'))
22.125
60
0.666667
import os import sys sys.path.append( os.path.join(os.path.dirname(os.path.abspath(__file__)), '../src/rpg_trajectory_evaluation'))
true
true
f7fe5fa93f5b08ad07637ef68787f5ddcda596d8
4,428
py
Python
examples/adwords/v201409/campaign_management/add_keywords_in_bulk.py
dietrichc/streamline-ppc-reports
256f79246aba3c2cf8f792d87a066391a2f471e0
[ "Apache-2.0" ]
null
null
null
examples/adwords/v201409/campaign_management/add_keywords_in_bulk.py
dietrichc/streamline-ppc-reports
256f79246aba3c2cf8f792d87a066391a2f471e0
[ "Apache-2.0" ]
null
null
null
examples/adwords/v201409/campaign_management/add_keywords_in_bulk.py
dietrichc/streamline-ppc-reports
256f79246aba3c2cf8f792d87a066391a2f471e0
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This code sample illustrates how to perform asynchronous requests. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our README. Tags: MutateJobService.mutate Tags: MutateJobService.get Tags: MutateJobService.getResult Api: AdWordsOnly """ __author__ = ('api.kwinter@gmail.com (Kevin Winter)' 'Joseph DiLallo') import random import re import time from googleads import adwords from googleads import errors RETRY_INTERVAL = 10 RETRIES_COUNT = 30 KEYWORD_NUMBER = 100 INDEX_REGEX = r'operations\[(\d+)\].operand' AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' def main(client, ad_group_id): # Initialize appropriate service. mutate_job_service = client.GetService('MutateJobService', version='v201409') # Create list of all operations for the job. operations = [] # Create AdGroupCriterionOperations to add keywords. for i in range(KEYWORD_NUMBER): keyword = 'mars%d' % i if random.randint(1, 10) == 1: keyword += '!!!' operations.append({ 'xsi_type': 'AdGroupCriterionOperation', 'operator': 'ADD', 'operand': { 'xsi_type': 'BiddableAdGroupCriterion', 'adGroupId': ad_group_id, 'criterion': { 'xsi_type': 'Keyword', 'matchType': 'BROAD', 'text': keyword } } }) # You can specify up to 3 job IDs that must successfully complete before # this job can be processed. policy = { 'prerequisiteJobIds': [] } # Call mutate to create a new job. response = mutate_job_service.mutate(operations, policy) if not response: raise errors.GoogleAdsError('Failed to submit a job; aborting.') job_id = response['id'] print 'Job with ID %s was successfully created.' % job_id # Create selector to retrieve job status and wait for it to complete. selector = { 'xsi_type': 'BulkMutateJobSelector', 'jobIds': [job_id] } time.sleep(RETRY_INTERVAL) # Poll for job status until it's finished. print 'Retrieving job status...' for i in range(RETRIES_COUNT): job_status_response = mutate_job_service.get(selector) status = job_status_response[0]['status'] if status in ('COMPLETED', 'FAILED'): break print ('[%d] Current status is \'%s\', waiting %d seconds to retry...' % (i, status, RETRY_INTERVAL)) time.sleep(RETRY_INTERVAL) if status == 'FAILED': raise errors.GoogleAdsError('Job failed with reason: \'%s\'' % job_status_response[0]['failure_reason']) if status in ('PROCESSING', 'PENDING'): raise errors.GoogleAdsError('Job did not complete within %d seconds' % (RETRY_INTERVAL * (RETRIES_COUNT - 1))) # Status must be COMPLETED. # Get the job result. Here we re-use the same selector. result_response = mutate_job_service.getResult(selector) # Output results. index = 0 for result in result_response['SimpleMutateResult']['results']: if 'PlaceHolder' in result: print 'Operation [%d] - FAILED' % index else: print 'Operation [%d] - SUCCEEDED' % index index += 1 # Output errors for error in result_response['SimpleMutateResult']['errors']: index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1)) reason = error['reason'] keyword = operations[index]['operand']['criterion']['text'] print ('ERROR - keyword \'%s\' failed due to \'%s\'' % (keyword, reason)) if __name__ == '__main__': # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() main(adwords_client, AD_GROUP_ID)
31.183099
79
0.677733
"""This code sample illustrates how to perform asynchronous requests. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our README. Tags: MutateJobService.mutate Tags: MutateJobService.get Tags: MutateJobService.getResult Api: AdWordsOnly """ __author__ = ('api.kwinter@gmail.com (Kevin Winter)' 'Joseph DiLallo') import random import re import time from googleads import adwords from googleads import errors RETRY_INTERVAL = 10 RETRIES_COUNT = 30 KEYWORD_NUMBER = 100 INDEX_REGEX = r'operations\[(\d+)\].operand' AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' def main(client, ad_group_id): mutate_job_service = client.GetService('MutateJobService', version='v201409') operations = [] for i in range(KEYWORD_NUMBER): keyword = 'mars%d' % i if random.randint(1, 10) == 1: keyword += '!!!' operations.append({ 'xsi_type': 'AdGroupCriterionOperation', 'operator': 'ADD', 'operand': { 'xsi_type': 'BiddableAdGroupCriterion', 'adGroupId': ad_group_id, 'criterion': { 'xsi_type': 'Keyword', 'matchType': 'BROAD', 'text': keyword } } }) policy = { 'prerequisiteJobIds': [] } response = mutate_job_service.mutate(operations, policy) if not response: raise errors.GoogleAdsError('Failed to submit a job; aborting.') job_id = response['id'] print 'Job with ID %s was successfully created.' % job_id selector = { 'xsi_type': 'BulkMutateJobSelector', 'jobIds': [job_id] } time.sleep(RETRY_INTERVAL) print 'Retrieving job status...' for i in range(RETRIES_COUNT): job_status_response = mutate_job_service.get(selector) status = job_status_response[0]['status'] if status in ('COMPLETED', 'FAILED'): break print ('[%d] Current status is \'%s\', waiting %d seconds to retry...' % (i, status, RETRY_INTERVAL)) time.sleep(RETRY_INTERVAL) if status == 'FAILED': raise errors.GoogleAdsError('Job failed with reason: \'%s\'' % job_status_response[0]['failure_reason']) if status in ('PROCESSING', 'PENDING'): raise errors.GoogleAdsError('Job did not complete within %d seconds' % (RETRY_INTERVAL * (RETRIES_COUNT - 1))) # Status must be COMPLETED. # Get the job result. Here we re-use the same selector. result_response = mutate_job_service.getResult(selector) # Output results. index = 0 for result in result_response['SimpleMutateResult']['results']: if 'PlaceHolder' in result: print 'Operation [%d] - FAILED' % index else: print 'Operation [%d] - SUCCEEDED' % index index += 1 # Output errors for error in result_response['SimpleMutateResult']['errors']: index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1)) reason = error['reason'] keyword = operations[index]['operand']['criterion']['text'] print ('ERROR - keyword \'%s\' failed due to \'%s\'' % (keyword, reason)) if __name__ == '__main__': # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() main(adwords_client, AD_GROUP_ID)
false
true
f7fe6045a0700d18c7c3dfbb20fa828b124aa0f5
7,677
py
Python
salt/cli/batch.py
mattmb/salt
d02a718120cc202901437ef5ed8ec282c22178c3
[ "Apache-2.0" ]
null
null
null
salt/cli/batch.py
mattmb/salt
d02a718120cc202901437ef5ed8ec282c22178c3
[ "Apache-2.0" ]
null
null
null
salt/cli/batch.py
mattmb/salt
d02a718120cc202901437ef5ed8ec282c22178c3
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- ''' Execute batch runs ''' # Import python libs from __future__ import absolute_import, print_function import math import time import copy # Import salt libs import salt.client import salt.output from salt.utils import print_cli # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin import salt.ext.six as six from salt.ext.six.moves import range # pylint: enable=import-error,no-name-in-module,redefined-builtin class Batch(object): ''' Manage the execution of batch runs ''' def __init__(self, opts, eauth=None, quiet=False): self.opts = opts self.eauth = eauth if eauth else {} self.quiet = quiet self.local = salt.client.get_local_client(opts['conf_file']) self.minions, self.ping_gen = self.__gather_minions() def __gather_minions(self): ''' Return a list of minions to use for the batch run ''' args = [self.opts['tgt'], 'test.ping', [], self.opts['timeout'], ] selected_target_option = self.opts.get('selected_target_option', None) if selected_target_option is not None: args.append(selected_target_option) else: args.append(self.opts.get('expr_form', 'glob')) ping_gen = self.local.cmd_iter(*args, **self.eauth) fret = set() for ret in ping_gen: m = next(six.iterkeys(ret)) if m is not None: fret.add(m) return (list(fret), ping_gen) def get_bnum(self): ''' Return the active number of minions to maintain ''' partition = lambda x: float(x) / 100.0 * len(self.minions) try: if '%' in self.opts['batch']: res = partition(float(self.opts['batch'].strip('%'))) if res < 1: return int(math.ceil(res)) else: return int(res) else: return int(self.opts['batch']) except ValueError: if not self.quiet: print_cli('Invalid batch data sent: {0}\nData must be in the ' 'form of %10, 10% or 3'.format(self.opts['batch'])) def run(self): ''' Execute the batch run ''' args = [[], self.opts['fun'], self.opts['arg'], self.opts['timeout'], 'list', ] bnum = self.get_bnum() to_run = copy.deepcopy(self.minions) active = [] ret = {} iters = [] # the minion tracker keeps track of responses and iterators # - it removes finished iterators from iters[] # - if a previously detected minion does not respond, its # added with an empty answer to ret{} once the timeout is reached # - unresponsive minions are removed from active[] to make # sure that the main while loop finishes even with unresp minions minion_tracker = {} # Iterate while we still have things to execute while len(ret) < len(self.minions): next_ = [] if len(to_run) <= bnum and not active: # last bit of them, add them all to next iterator while to_run: next_.append(to_run.pop()) else: for i in range(bnum - len(active)): if to_run: minion_id = to_run.pop() if isinstance(minion_id, dict): next_.append(minion_id.keys()[0]) else: next_.append(minion_id) active += next_ args[0] = next_ if next_: if not self.quiet: print_cli('\nExecuting run on {0}\n'.format(next_)) # create a new iterator for this batch of minions new_iter = self.local.cmd_iter_no_block( *args, raw=self.opts.get('raw', False), ret=self.opts.get('return', ''), **self.eauth) # add it to our iterators and to the minion_tracker iters.append(new_iter) minion_tracker[new_iter] = {} # every iterator added is 'active' and has its set of minions minion_tracker[new_iter]['minions'] = next_ minion_tracker[new_iter]['active'] = True else: time.sleep(0.02) parts = {} # see if we found more minions for ping_ret in self.ping_gen: if ping_ret is None: break m = next(ping_ret.iterkeys()) if m not in self.minions: self.minions.append(m) to_run.append(m) for queue in iters: try: # Gather returns until we get to the bottom ncnt = 0 while True: part = next(queue) if part is None: time.sleep(0.01) ncnt += 1 if ncnt > 5: break continue if self.opts.get('raw'): parts.update({part['id']: part}) else: parts.update(part) except StopIteration: # if a iterator is done: # - set it to inactive # - add minions that have not responded to parts{} # check if the tracker contains the iterator if queue in minion_tracker: minion_tracker[queue]['active'] = False # add all minions that belong to this iterator and # that have not responded to parts{} with an empty response for minion in minion_tracker[queue]['minions']: if minion not in parts: parts[minion] = {} parts[minion]['ret'] = {} for minion, data in six.iteritems(parts): active.remove(minion) if self.opts.get('raw'): yield data else: ret[minion] = data['ret'] yield {minion: data['ret']} if not self.quiet: ret[minion] = data['ret'] data[minion] = data.pop('ret') if 'out' in data: out = data.pop('out') else: out = None salt.output.display_output( data, out, self.opts) # remove inactive iterators from the iters list for queue in minion_tracker: # only remove inactive queues if not minion_tracker[queue]['active'] and queue in iters: iters.remove(queue) # also remove the iterator's minions from the active list for minion in minion_tracker[queue]['minions']: if minion in active: active.remove(minion)
36.383886
83
0.470366
from __future__ import absolute_import, print_function import math import time import copy import salt.client import salt.output from salt.utils import print_cli import salt.ext.six as six from salt.ext.six.moves import range class Batch(object): def __init__(self, opts, eauth=None, quiet=False): self.opts = opts self.eauth = eauth if eauth else {} self.quiet = quiet self.local = salt.client.get_local_client(opts['conf_file']) self.minions, self.ping_gen = self.__gather_minions() def __gather_minions(self): args = [self.opts['tgt'], 'test.ping', [], self.opts['timeout'], ] selected_target_option = self.opts.get('selected_target_option', None) if selected_target_option is not None: args.append(selected_target_option) else: args.append(self.opts.get('expr_form', 'glob')) ping_gen = self.local.cmd_iter(*args, **self.eauth) fret = set() for ret in ping_gen: m = next(six.iterkeys(ret)) if m is not None: fret.add(m) return (list(fret), ping_gen) def get_bnum(self): partition = lambda x: float(x) / 100.0 * len(self.minions) try: if '%' in self.opts['batch']: res = partition(float(self.opts['batch'].strip('%'))) if res < 1: return int(math.ceil(res)) else: return int(res) else: return int(self.opts['batch']) except ValueError: if not self.quiet: print_cli('Invalid batch data sent: {0}\nData must be in the ' 'form of %10, 10% or 3'.format(self.opts['batch'])) def run(self): args = [[], self.opts['fun'], self.opts['arg'], self.opts['timeout'], 'list', ] bnum = self.get_bnum() to_run = copy.deepcopy(self.minions) active = [] ret = {} iters = [] minion_tracker = {} while len(ret) < len(self.minions): next_ = [] if len(to_run) <= bnum and not active: while to_run: next_.append(to_run.pop()) else: for i in range(bnum - len(active)): if to_run: minion_id = to_run.pop() if isinstance(minion_id, dict): next_.append(minion_id.keys()[0]) else: next_.append(minion_id) active += next_ args[0] = next_ if next_: if not self.quiet: print_cli('\nExecuting run on {0}\n'.format(next_)) new_iter = self.local.cmd_iter_no_block( *args, raw=self.opts.get('raw', False), ret=self.opts.get('return', ''), **self.eauth) iters.append(new_iter) minion_tracker[new_iter] = {} minion_tracker[new_iter]['minions'] = next_ minion_tracker[new_iter]['active'] = True else: time.sleep(0.02) parts = {} for ping_ret in self.ping_gen: if ping_ret is None: break m = next(ping_ret.iterkeys()) if m not in self.minions: self.minions.append(m) to_run.append(m) for queue in iters: try: ncnt = 0 while True: part = next(queue) if part is None: time.sleep(0.01) ncnt += 1 if ncnt > 5: break continue if self.opts.get('raw'): parts.update({part['id']: part}) else: parts.update(part) except StopIteration: if queue in minion_tracker: minion_tracker[queue]['active'] = False for minion in minion_tracker[queue]['minions']: if minion not in parts: parts[minion] = {} parts[minion]['ret'] = {} for minion, data in six.iteritems(parts): active.remove(minion) if self.opts.get('raw'): yield data else: ret[minion] = data['ret'] yield {minion: data['ret']} if not self.quiet: ret[minion] = data['ret'] data[minion] = data.pop('ret') if 'out' in data: out = data.pop('out') else: out = None salt.output.display_output( data, out, self.opts) for queue in minion_tracker: if not minion_tracker[queue]['active'] and queue in iters: iters.remove(queue) for minion in minion_tracker[queue]['minions']: if minion in active: active.remove(minion)
true
true
f7fe62e9d80211104fecfb8d49bbab2d7c99e009
3,651
py
Python
coderunner/myapp/tests.py
kelseylyn/CodeRunner
4085515e46ca1b2dab42c9f91598acbd70b9227e
[ "MIT" ]
null
null
null
coderunner/myapp/tests.py
kelseylyn/CodeRunner
4085515e46ca1b2dab42c9f91598acbd70b9227e
[ "MIT" ]
null
null
null
coderunner/myapp/tests.py
kelseylyn/CodeRunner
4085515e46ca1b2dab42c9f91598acbd70b9227e
[ "MIT" ]
null
null
null
from django.test import TestCase # myapp/tests.py from channels.testing import ChannelsLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.wait import WebDriverWait class ChatTests(ChannelsLiveServerTestCase): serve_static = True # emulate StaticLiveServerTestCase @classmethod def setUpClass(cls): super().setUpClass() try: # NOTE: Requires "chromedriver" binary to be installed in $PATH cls.driver = webdriver.Chrome() except: super().tearDownClass() raise @classmethod def tearDownClass(cls): cls.driver.quit() super().tearDownClass() def test_when_chat_message_posted_then_seen_by_everyone_in_same_room(self): try: self._enter_chat_room('room_1') self._open_new_window() self._enter_chat_room('room_1') self._switch_to_window(0) self._post_message('hello') WebDriverWait(self.driver, 2).until(lambda _: 'hello' in self._chat_log_value, 'Message was not received by window 1 from window 1') self._switch_to_window(1) WebDriverWait(self.driver, 2).until(lambda _: 'hello' in self._chat_log_value, 'Message was not received by window 2 from window 1') finally: self._close_all_new_windows() def test_when_chat_message_posted_then_not_seen_by_anyone_in_different_room(self): try: self._enter_chat_room('room_1') self._open_new_window() self._enter_chat_room('room_2') self._switch_to_window(0) self._post_message('hello') WebDriverWait(self.driver, 2).until(lambda _: 'hello' in self._chat_log_value, 'Message was not received by window 1 from window 1') self._switch_to_window(1) self._post_message('world') WebDriverWait(self.driver, 2).until(lambda _: 'world' in self._chat_log_value, 'Message was not received by window 2 from window 2') self.assertTrue('hello' not in self._chat_log_value, 'Message was improperly received by window 2 from window 1') finally: self._close_all_new_windows() # === Utility === def _enter_chat_room(self, room_name): self.driver.get(self.live_server_url + '/chat/') ActionChains(self.driver).send_keys(room_name + '\n').perform() WebDriverWait(self.driver, 2).until(lambda _: room_name in self.driver.current_url) def _open_new_window(self): self.driver.execute_script('window.open("about:blank", "_blank");') self.driver.switch_to_window(self.driver.window_handles[-1]) def _close_all_new_windows(self): while len(self.driver.window_handles) > 1: self.driver.switch_to_window(self.driver.window_handles[-1]) self.driver.execute_script('window.close();') if len(self.driver.window_handles) == 1: self.driver.switch_to_window(self.driver.window_handles[0]) def _switch_to_window(self, window_index): self.driver.switch_to_window(self.driver.window_handles[window_index]) def _post_message(self, message): ActionChains(self.driver).send_keys(message + '\n').perform() @property def _chat_log_value(self): return self.driver.find_element_by_css_selector('#chat-log').get_property('value')# Create your tests here.
38.03125
115
0.650781
from django.test import TestCase from channels.testing import ChannelsLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.wait import WebDriverWait class ChatTests(ChannelsLiveServerTestCase): serve_static = True @classmethod def setUpClass(cls): super().setUpClass() try: cls.driver = webdriver.Chrome() except: super().tearDownClass() raise @classmethod def tearDownClass(cls): cls.driver.quit() super().tearDownClass() def test_when_chat_message_posted_then_seen_by_everyone_in_same_room(self): try: self._enter_chat_room('room_1') self._open_new_window() self._enter_chat_room('room_1') self._switch_to_window(0) self._post_message('hello') WebDriverWait(self.driver, 2).until(lambda _: 'hello' in self._chat_log_value, 'Message was not received by window 1 from window 1') self._switch_to_window(1) WebDriverWait(self.driver, 2).until(lambda _: 'hello' in self._chat_log_value, 'Message was not received by window 2 from window 1') finally: self._close_all_new_windows() def test_when_chat_message_posted_then_not_seen_by_anyone_in_different_room(self): try: self._enter_chat_room('room_1') self._open_new_window() self._enter_chat_room('room_2') self._switch_to_window(0) self._post_message('hello') WebDriverWait(self.driver, 2).until(lambda _: 'hello' in self._chat_log_value, 'Message was not received by window 1 from window 1') self._switch_to_window(1) self._post_message('world') WebDriverWait(self.driver, 2).until(lambda _: 'world' in self._chat_log_value, 'Message was not received by window 2 from window 2') self.assertTrue('hello' not in self._chat_log_value, 'Message was improperly received by window 2 from window 1') finally: self._close_all_new_windows() def _enter_chat_room(self, room_name): self.driver.get(self.live_server_url + '/chat/') ActionChains(self.driver).send_keys(room_name + '\n').perform() WebDriverWait(self.driver, 2).until(lambda _: room_name in self.driver.current_url) def _open_new_window(self): self.driver.execute_script('window.open("about:blank", "_blank");') self.driver.switch_to_window(self.driver.window_handles[-1]) def _close_all_new_windows(self): while len(self.driver.window_handles) > 1: self.driver.switch_to_window(self.driver.window_handles[-1]) self.driver.execute_script('window.close();') if len(self.driver.window_handles) == 1: self.driver.switch_to_window(self.driver.window_handles[0]) def _switch_to_window(self, window_index): self.driver.switch_to_window(self.driver.window_handles[window_index]) def _post_message(self, message): ActionChains(self.driver).send_keys(message + '\n').perform() @property def _chat_log_value(self): return self.driver.find_element_by_css_selector('#chat-log').get_property('value')
true
true
f7fe64a6acb2e2a59e42278b437fcbb3e026050b
746
py
Python
LeetCodeSolutions/python/652_Find_Duplicate_Subtrees.py
ChuanleiGuo/AlgorithmsPlayground
90b6287b742c8bfd3797540c408d679be2821a40
[ "MIT" ]
1
2017-03-27T13:38:37.000Z
2017-03-27T13:38:37.000Z
LeetCodeSolutions/python/652_Find_Duplicate_Subtrees.py
ChuanleiGuo/AlgorithmsPlayground
90b6287b742c8bfd3797540c408d679be2821a40
[ "MIT" ]
null
null
null
LeetCodeSolutions/python/652_Find_Duplicate_Subtrees.py
ChuanleiGuo/AlgorithmsPlayground
90b6287b742c8bfd3797540c408d679be2821a40
[ "MIT" ]
null
null
null
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def findDuplicateSubtrees(self, root): """ :type root: TreeNode :rtype: List[TreeNode] """ res = [] self.subtree_serial(root, dict(), res) return res def subtree_serial(self, cur, hash_map, res): if cur is None: return '#' serial = str(cur.val) + ',' + self.subtree_serial(cur.left, hash_map, res) + ',' + \ self.subtree_serial(cur.right, hash_map, res) if hash_map.get(serial, 0) == 1: res.append(cur) hash_map[serial] = hash_map.get(serial, 0) + 1 return serial
27.62963
92
0.542895
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def findDuplicateSubtrees(self, root): res = [] self.subtree_serial(root, dict(), res) return res def subtree_serial(self, cur, hash_map, res): if cur is None: return '#' serial = str(cur.val) + ',' + self.subtree_serial(cur.left, hash_map, res) + ',' + \ self.subtree_serial(cur.right, hash_map, res) if hash_map.get(serial, 0) == 1: res.append(cur) hash_map[serial] = hash_map.get(serial, 0) + 1 return serial
true
true
f7fe655b6d6424d781be8957cb4989cf33dd3e62
934
py
Python
lemur/plugins/bases/source.py
prdonahue/lemur
267159af1950a77fa298275f234d7e458b91dda9
[ "Apache-2.0" ]
null
null
null
lemur/plugins/bases/source.py
prdonahue/lemur
267159af1950a77fa298275f234d7e458b91dda9
[ "Apache-2.0" ]
1
2022-03-29T22:05:53.000Z
2022-03-29T22:05:53.000Z
lemur/plugins/bases/source.py
TinLe/lemur
dfb9e3a0c8f8f1f1bd908b1fcb8596af7c65f739
[ "Apache-2.0" ]
null
null
null
""" .. module: lemur.plugins.bases.source :platform: Unix :copyright: (c) 2015 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. .. moduleauthor:: Kevin Glisson <kglisson@netflix.com> """ from lemur.plugins.base import Plugin class SourcePlugin(Plugin): type = 'source' default_options = [ { 'name': 'pollRate', 'type': 'int', 'required': False, 'helpMessage': 'Rate in seconds to poll source for new information.', 'default': '60', } ] def get_certificates(self, options, **kwargs): raise NotImplementedError def get_endpoints(self, options, **kwargs): raise NotImplementedError def clean(self, certificate, options, **kwargs): raise NotImplementedError @property def options(self): return self.default_options + self.additional_options
25.243243
81
0.624197
from lemur.plugins.base import Plugin class SourcePlugin(Plugin): type = 'source' default_options = [ { 'name': 'pollRate', 'type': 'int', 'required': False, 'helpMessage': 'Rate in seconds to poll source for new information.', 'default': '60', } ] def get_certificates(self, options, **kwargs): raise NotImplementedError def get_endpoints(self, options, **kwargs): raise NotImplementedError def clean(self, certificate, options, **kwargs): raise NotImplementedError @property def options(self): return self.default_options + self.additional_options
true
true
f7fe65a12de4eccfbbee75203b13bad6dff57dc2
27,558
py
Python
tensorflow_probability/python/experimental/mcmc/gradient_based_trajectory_length_adaptation_test.py
jakee417/probability-1
ae7117f37ac441bc7a888167ea23e5e620c5bcde
[ "Apache-2.0" ]
3,670
2018-02-14T03:29:40.000Z
2022-03-30T01:19:52.000Z
tensorflow_probability/python/experimental/mcmc/gradient_based_trajectory_length_adaptation_test.py
jakee417/probability-1
ae7117f37ac441bc7a888167ea23e5e620c5bcde
[ "Apache-2.0" ]
1,395
2018-02-24T02:28:49.000Z
2022-03-31T16:12:06.000Z
tensorflow_probability/python/experimental/mcmc/gradient_based_trajectory_length_adaptation_test.py
jakee417/probability-1
ae7117f37ac441bc7a888167ea23e5e620c5bcde
[ "Apache-2.0" ]
1,135
2018-02-14T01:51:10.000Z
2022-03-28T02:24:11.000Z
# Copyright 2020 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests for gradient_based_trajectory_length_adaptation.""" from absl.testing import parameterized import numpy as np import tensorflow.compat.v1 as tf1 import tensorflow.compat.v2 as tf import tensorflow_probability as tfp from tensorflow_probability.python.internal import distribute_lib from tensorflow_probability.python.internal import distribute_test_lib from tensorflow_probability.python.internal import samplers from tensorflow_probability.python.internal import test_util tfb = tfp.bijectors tfd = tfp.distributions JAX_MODE = False def snaper_criterion_dummy_direction(previous_state, *args, **kwargs): # Technically direction should be normalized, but omitting the normalization # term only rescales the criterion so we're fine. return tfp.experimental.mcmc.snaper_criterion( previous_state, *args, direction=tf.nest.map_structure(tf.ones_like, previous_state), **kwargs, ) def snaper_criterion_2d_direction(previous_state, *args, **kwargs): return tfp.experimental.mcmc.snaper_criterion( previous_state, *args, direction=tf.constant([0., 1.], previous_state.dtype), **kwargs, ) @test_util.test_graph_and_eager_modes class GradientBasedTrajectoryLengthAdaptationTestGeneric( test_util.TestCase, parameterized.TestCase): def testForbiddenTransformedKernel(self): kernel = tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=lambda x: -x**2, step_size=0.1, num_leapfrog_steps=1) kernel = tfp.mcmc.TransformedTransitionKernel(kernel, tfb.Identity()) with self.assertRaisesRegex( ValueError, 'The inner kernel cannot contain a `TransformedTransitionKernel`'): kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=100) def testNestedStepSizeError(self): kernel = tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=lambda x: -x**2, step_size=[0.1], num_leapfrog_steps=1) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=100) with self.assertRaisesRegex(ValueError, 'Step size must be a scalar'): kernel.bootstrap_results([1.]) @parameterized.named_parameters(('StaticShape', True), ('DynamicShape', False)) def testNonScalarStepSizeError(self, use_static_shape): step_size = tf1.placeholder_with_default( [0.1, 0.2], shape=[2] if use_static_shape else None) kernel = tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=lambda x: -x**2, step_size=step_size, num_leapfrog_steps=1) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=100, validate_args=True) with self.assertRaisesRegex(Exception, 'Step size must be a scalar'): self.evaluate(kernel.bootstrap_results(tf.constant(1.))) @parameterized.named_parameters( ('ChEESStaticShape', True, tfp.experimental.mcmc.chees_criterion), ('ChEESDynamicShape', False, tfp.experimental.mcmc.chees_criterion), ('SNAPERStaticShape', True, snaper_criterion_dummy_direction), ('SNAPERDynamicShape', False, snaper_criterion_dummy_direction), ) def testTooFewChains(self, use_static_shape, criterion_fn): state = tf1.placeholder_with_default( [[0.1, 0.2]], shape=[1, 2] if use_static_shape else None) accept_prob = tf1.placeholder_with_default( [1.], shape=[1] if use_static_shape else None) with self.assertRaisesRegex(Exception, 'chees_criterion requires at least 2 chains'): self.evaluate( tfp.experimental.mcmc.chees_criterion( state, state, accept_prob, 1., validate_args=True)) @parameterized.named_parameters( ('ChEESStaticShape', True, tfp.experimental.mcmc.chees_criterion), ('ChEESDynamicShape', False, tfp.experimental.mcmc.chees_criterion), ('SNAPERStaticShape', True, snaper_criterion_dummy_direction), ('SNAPERDynamicShape', False, snaper_criterion_dummy_direction), ) def testNoBatchDims(self, use_static_shape, criterion_fn): state = tf1.placeholder_with_default( [[0.1, 0.2]], shape=[1, 2] if use_static_shape else None) accept_prob = tf1.placeholder_with_default( 1., shape=[] if use_static_shape else None) with self.assertRaisesRegex(Exception, 'requires at least 2 chains'): self.evaluate( criterion_fn(state, state, accept_prob, 1., validate_args=True)) class _GradientBasedTrajectoryLengthAdaptationTest(test_util.TestCase): def testDocstringExample(self): if tf.executing_eagerly() and not JAX_MODE: self.skipTest('Too slow for TF Eager.') target = tfd.JointDistributionSequential([ tfd.Normal(0., tf.constant(20., dtype=self.dtype)), tfd.HalfNormal(tf.constant(10., dtype=self.dtype)), ]) def target_log_prob_fn(*x): return tf.cast(target.log_prob(x), self.dtype) num_burnin_steps = 1000 num_adaptation_steps = int(num_burnin_steps * 0.8) num_results = 500 num_chains = 16 step_size = 0.1 kernel = tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target_log_prob_fn, step_size=step_size, num_leapfrog_steps=1, ) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=num_adaptation_steps, validate_args=True) kernel = tfp.mcmc.DualAveragingStepSizeAdaptation( kernel, num_adaptation_steps=num_adaptation_steps) kernel = tfp.mcmc.TransformedTransitionKernel( kernel, [tfb.Identity(), tfb.Exp()]) def trace_fn(_, pkr): return ( pkr.inner_results.inner_results.inner_results.accepted_results .step_size, pkr.inner_results.inner_results.max_trajectory_length, pkr.inner_results.inner_results.inner_results.log_accept_ratio, ) # The chain will be stepped for num_results + num_burnin_steps, adapting for # the first num_adaptation_steps. chain, [step_size, max_trajectory_length, log_accept_ratio] = ( tfp.mcmc.sample_chain( num_results=num_results, num_burnin_steps=num_burnin_steps, current_state=[ tf.ones(num_chains, dtype=self.dtype), tf.ones(num_chains, dtype=self.dtype) ], kernel=kernel, trace_fn=trace_fn, seed=test_util.test_seed(sampler_type='stateless'))) p_accept = tf.math.exp( tfp.math.reduce_logmeanexp(tf.minimum(log_accept_ratio, 0.))) mean_step_size = tf.reduce_mean(step_size) mean_max_trajectory_length = tf.reduce_mean(max_trajectory_length) self.assertAllClose(0.75, p_accept, atol=0.1) self.assertAllClose(0.52, mean_step_size, atol=0.2) self.assertAllClose(46., mean_max_trajectory_length, atol=15) self.assertAllClose( target.mean(), [tf.reduce_mean(x, axis=[0, 1]) for x in chain], atol=1.5) self.assertAllClose( target.variance(), [tf.math.reduce_variance(x, axis=[0, 1]) for x in chain], rtol=0.2) def testStateMeanSNAPER(self): state = np.array([[0.1, 0.2]], self.dtype) accept_prob = np.ones([], self.dtype) # This doesn't fail because state_mean is provided externally. self.evaluate(tfp.experimental.mcmc.snaper_criterion( state, state, accept_prob, 2., direction=tf.ones_like(state), state_mean=state, state_mean_weight=0.1, )) @parameterized.named_parameters( ('ChEES', tfp.experimental.mcmc.chees_criterion), ('SNAPER', snaper_criterion_dummy_direction), ) def testScalarState(self, criterion_fn): def target_log_prob_fn(x): return -x**2 / 2 kernel = tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target_log_prob_fn, step_size=0.1, num_leapfrog_steps=1, ) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=5, adaptation_rate=1., criterion_fn=criterion_fn, validate_args=True) state = tf.zeros([64], self.dtype) init_kernel_results = kernel.bootstrap_results(state) init_kernel_results, (_, final_kernel_results) = self.evaluate([ init_kernel_results, kernel.one_step( state, init_kernel_results, seed=test_util.test_seed(sampler_type='stateless')) ]) # We expect it to move it a little bit. self.assertGreater( np.abs(init_kernel_results.max_trajectory_length - final_kernel_results.max_trajectory_length), 0.0005) @parameterized.named_parameters( ('ChEES', tfp.experimental.mcmc.chees_criterion), ('SNAPER', snaper_criterion_dummy_direction), ) def testTensorState(self, criterion_fn): def target_log_prob_fn(x): return -tf.reduce_mean(x**2, [-1, -2]) / 2 kernel = tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target_log_prob_fn, step_size=0.1, num_leapfrog_steps=1, ) kernel = ( tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=5, adaptation_rate=1., criterion_fn=criterion_fn, validate_args=True)) state = tf.zeros([64, 2, 3], self.dtype) init_kernel_results = kernel.bootstrap_results(state) init_kernel_results, (_, final_kernel_results) = self.evaluate([ init_kernel_results, kernel.one_step( state, init_kernel_results, seed=test_util.test_seed(sampler_type='stateless')) ]) # We expect it to move it a little bit. self.assertGreater( np.abs(init_kernel_results.max_trajectory_length - final_kernel_results.max_trajectory_length), 0.0005) @parameterized.named_parameters( ('ChEES', tfp.experimental.mcmc.chees_criterion), ('SNAPER', snaper_criterion_dummy_direction), ) def testListState(self, criterion_fn): def target_log_prob_fn(x, y): return -x**2 / 2 - y**2 / 2 kernel = tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target_log_prob_fn, step_size=0.1, num_leapfrog_steps=1, ) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=5, adaptation_rate=1., criterion_fn=criterion_fn, validate_args=True) state = [tf.zeros([64], self.dtype), tf.zeros([64], self.dtype)] init_kernel_results = kernel.bootstrap_results(state) init_kernel_results, (_, final_kernel_results) = self.evaluate([ init_kernel_results, kernel.one_step( state, init_kernel_results, seed=test_util.test_seed(sampler_type='stateless')) ]) # We expect it to move it a little bit. self.assertGreater( np.abs(init_kernel_results.max_trajectory_length - final_kernel_results.max_trajectory_length), 0.0005) @parameterized.named_parameters( ('ChEES', tfp.experimental.mcmc.chees_rate_criterion), ('SNAPER', snaper_criterion_2d_direction), ) def testAdaptation(self, criterion_fn): if tf.executing_eagerly() and not JAX_MODE: self.skipTest('Too slow for TF Eager.') target = tfd.Independent( tfd.Normal(0., tf.constant([1., 10.], self.dtype)), 1) num_burnin_steps = 1000 num_adaptation_steps = int(num_burnin_steps * 0.8) num_results = 500 num_chains = 16 step_size = 0.1 kernel = tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=step_size, num_leapfrog_steps=1, ) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=num_adaptation_steps, criterion_fn=criterion_fn, validate_args=True) kernel = tfp.mcmc.DualAveragingStepSizeAdaptation( kernel, num_adaptation_steps=num_adaptation_steps) def trace_fn(_, pkr): return ( pkr.inner_results.inner_results.accepted_results .step_size, pkr.inner_results.max_trajectory_length, pkr.inner_results.inner_results.log_accept_ratio, ) # The chain will be stepped for num_results + num_burnin_steps, adapting for # the first num_adaptation_steps. chain, [step_size, max_trajectory_length, log_accept_ratio] = ( tfp.mcmc.sample_chain( num_results=num_results, num_burnin_steps=num_burnin_steps, current_state=tf.zeros([num_chains, 2], dtype=self.dtype), kernel=kernel, trace_fn=trace_fn, seed=test_util.test_seed(sampler_type='stateless'))) p_accept = tf.math.exp( tfp.math.reduce_logmeanexp(tf.minimum(log_accept_ratio, 0.))) mean_step_size = tf.reduce_mean(step_size) mean_max_trajectory_length = tf.reduce_mean(max_trajectory_length) self.assertAllClose(0.75, p_accept, atol=0.1) self.assertAllClose(1.5, mean_step_size, atol=0.2) # Both SNAPER and ChEES-rate find roughly the same trajectory length for # this target. self.assertAllClose(15., mean_max_trajectory_length, rtol=0.3) self.assertAllClose( target.mean(), tf.reduce_mean(chain, axis=[0, 1]), atol=1.) self.assertAllClose( target.variance(), tf.math.reduce_variance(chain, axis=[0, 1]), rtol=0.1) def testPreconditionedHMC(self): if tf.executing_eagerly() and not JAX_MODE: self.skipTest('Too slow for TF Eager.') target = tfd.Independent( tfd.Normal(0., tf.constant([1., 10.], self.dtype)), 1) num_burnin_steps = 1000 num_adaptation_steps = int(num_burnin_steps * 0.8) num_results = 500 num_chains = 16 step_size = 0.1 kernel = tfp.experimental.mcmc.PreconditionedHamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=step_size, num_leapfrog_steps=1, momentum_distribution=tfd.Independent( tfd.Normal(0., tf.constant([1., 1. / 10.], self.dtype)), 1), ) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=num_adaptation_steps, validate_args=True) kernel = tfp.mcmc.DualAveragingStepSizeAdaptation( kernel, num_adaptation_steps=num_adaptation_steps) def trace_fn(_, pkr): return ( pkr.inner_results.inner_results.accepted_results .step_size, pkr.inner_results.max_trajectory_length, pkr.inner_results.inner_results.log_accept_ratio, ) # The chain will be stepped for num_results + num_burnin_steps, adapting for # the first num_adaptation_steps. chain, [step_size, max_trajectory_length, log_accept_ratio] = ( tfp.mcmc.sample_chain( num_results=num_results, num_burnin_steps=num_burnin_steps, current_state=tf.zeros([num_chains, 2], dtype=self.dtype), kernel=kernel, trace_fn=trace_fn, seed=test_util.test_seed(sampler_type='stateless'))) p_accept = tf.math.exp( tfp.math.reduce_logmeanexp(tf.minimum(log_accept_ratio, 0.))) mean_step_size = tf.reduce_mean(step_size) mean_max_trajectory_length = tf.reduce_mean(max_trajectory_length) self.assertAllClose(0.75, p_accept, atol=0.1) self.assertAllClose(1.2, mean_step_size, atol=0.2) self.assertAllClose(1.5, mean_max_trajectory_length, rtol=0.25) self.assertAllClose( target.mean(), tf.reduce_mean(chain, axis=[0, 1]), atol=0.3) self.assertAllClose( target.variance(), tf.math.reduce_variance(chain, axis=[0, 1]), rtol=0.1) def testNumAdaptationSteps(self): def target_log_prob_fn(x): return -x**2 kernel = tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target_log_prob_fn, step_size=0.1, num_leapfrog_steps=1, ) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=1, adaptation_rate=1., validate_args=True) state = tf.zeros([64], self.dtype) seed = test_util.test_seed(sampler_type='stateless') step_0_kernel_results = kernel.bootstrap_results(state) state, step_1_kernel_results = kernel.one_step( state, step_0_kernel_results, seed=seed) _, step_2_kernel_results = kernel.one_step( state, step_1_kernel_results, seed=seed) (step_0_kernel_results, step_1_kernel_results, step_2_kernel_results) = self.evaluate([ step_0_kernel_results, step_1_kernel_results, step_2_kernel_results, ]) # The intention of num_adaptation_steps is that we should adapt for 1 step # and then hold the hyperparameters constant. self.assertGreater( np.abs(step_0_kernel_results.max_trajectory_length - step_1_kernel_results.max_trajectory_length), 0.005) self.assertAllClose(step_1_kernel_results.max_trajectory_length, step_2_kernel_results.max_trajectory_length) @parameterized.named_parameters( ('ChEES', tfp.experimental.mcmc.chees_criterion), ('ChEESR', tfp.experimental.mcmc.chees_rate_criterion), ('SNAPER', snaper_criterion_dummy_direction), ) def testCriterionStateEquivalence(self, criterion_fn): # Criteria should not care about the exact arrangement of state parts. previous_state = np.random.randn(4, 6).astype(self.dtype) new_state = np.random.randn(4, 6).astype(self.dtype) accept_prob = np.random.uniform(size=(4,)).astype(self.dtype) matrix_previous_state = previous_state.reshape([4, 3, 2]) matrix_new_state = new_state.reshape([4, 3, 2]) list_previous_state = [previous_state[:, :2], previous_state[:, 2:]] list_new_state = [new_state[:, :2], new_state[:, 2:]] criterion = criterion_fn( previous_state, new_state, accept_prob, 1.) matrix_criterion = criterion_fn( matrix_previous_state, matrix_new_state, accept_prob, 1.) list_criterion = criterion_fn( list_previous_state, list_new_state, accept_prob, 1.) self.assertAllEqual([4], criterion.shape) self.assertAllClose(criterion, matrix_criterion) self.assertAllClose(criterion, list_criterion) class GradientBasedTrajectoryLengthAdaptationTestFloat32( _GradientBasedTrajectoryLengthAdaptationTest): dtype = np.float32 class GradientBasedTrajectoryLengthAdaptationTestFloat64( _GradientBasedTrajectoryLengthAdaptationTest): dtype = np.float64 @test_util.test_all_tf_execution_regimes class DistributedGBTLATest(distribute_test_lib.DistributedTest): def test_gbtla_kernel_tracks_axis_names(self): inner_kernel = tfp.mcmc.HamiltonianMonteCarlo(tfd.Normal(0, 1).log_prob, step_size=1.9, num_leapfrog_steps=2) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( inner_kernel, 1) self.assertIsNone(kernel.experimental_shard_axis_names) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( inner_kernel, 1, experimental_shard_axis_names=['a']) self.assertListEqual(kernel.experimental_shard_axis_names, ['a']) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( inner_kernel, 1).experimental_with_shard_axes(['a']) self.assertListEqual(kernel.experimental_shard_axis_names, ['a']) @parameterized.named_parameters( ('ChEES', tfp.experimental.mcmc.chees_criterion), ('ChEESR', tfp.experimental.mcmc.chees_rate_criterion), ('SNAPER', snaper_criterion_dummy_direction), ) def test_gbtla_kernel_computes_same_criterion_info_with_sharded_state( self, criterion_fn, ): if not JAX_MODE: self.skipTest('Test in TF runs into `merge_call` error: see b/178944108') def target_log_prob(a, b): return ( tfd.Normal(0., 1.).log_prob(a) + distribute_lib.psum(tfd.Normal( distribute_lib.pbroadcast(a, 'foo'), 1.).log_prob(b), 'foo')) kernel = tfp.mcmc.HamiltonianMonteCarlo(target_log_prob, step_size=1e-2, num_leapfrog_steps=2) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, 10, criterion_fn=criterion_fn) sharded_kernel = kernel.experimental_with_shard_axes([None, ['foo']]) def run(seed): init_seed, sample_seed = samplers.split_seed(seed) state_seeds = samplers.split_seed(init_seed) state = [ samplers.normal(seed=state_seeds[0], shape=[5]), samplers.normal(seed=state_seeds[1], shape=[5]) ] kr = sharded_kernel.bootstrap_results(state) _, kr = sharded_kernel.one_step(state, kr, seed=sample_seed) return ( kr.criterion, kr.averaged_sq_grad, kr.averaged_max_trajectory_length ) criterion, avg_sq_grad, avg_max_tl = self.evaluate( self.per_replica_to_tensor(self.strategy_run( run, args=(samplers.zeros_seed(),), in_axes=None, axis_name='foo'), 0)) for i in range(distribute_test_lib.NUM_DEVICES): self.assertAllClose(criterion[0], criterion[i]) self.assertAllClose(avg_sq_grad[0], avg_sq_grad[i]) self.assertAllClose(avg_max_tl[0], avg_max_tl[i]) @parameterized.named_parameters( ('ChEES', tfp.experimental.mcmc.chees_criterion), ('ChEESR', tfp.experimental.mcmc.chees_rate_criterion), ('SNAPER', snaper_criterion_dummy_direction), ) def test_gbtla_kernel_can_shard_chains_across_devices(self, criterion_fn): def target_log_prob(a, b): return ( tfd.Normal(0., 1.).log_prob(a) + tfd.Sample(tfd.Normal(a, 1.), 4).log_prob(b)) kernel = tfp.mcmc.HamiltonianMonteCarlo(target_log_prob, step_size=1e-2, num_leapfrog_steps=2) sharded_kernel = ( tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, 10, experimental_reduce_chain_axis_names=self.axis_name, criterion_fn=criterion_fn)) def run(seed): init_seed, sample_seed = samplers.split_seed(seed) state_seeds = samplers.split_seed(init_seed) state = [ samplers.normal(seed=state_seeds[0], shape=[]), samplers.normal(seed=state_seeds[1], shape=[4]) ] kr = sharded_kernel.bootstrap_results(state) _, kr = sharded_kernel.one_step(state, kr, seed=sample_seed) return ( kr.averaged_sq_grad, kr.averaged_max_trajectory_length ) seeds = self.shard_values(tf.stack(tfp.random.split_seed( samplers.zeros_seed(), distribute_test_lib.NUM_DEVICES)), 0) avg_sq_grad, avg_max_tl = self.evaluate( self.per_replica_to_tensor(self.strategy_run( run, args=(seeds,), axis_name=self.axis_name), 0)) for i in range(distribute_test_lib.NUM_DEVICES): self.assertAllClose(avg_sq_grad[0], avg_sq_grad[i]) self.assertAllClose(avg_max_tl[0], avg_max_tl[i]) @parameterized.named_parameters( ('ChEES', tfp.experimental.mcmc.chees_rate_criterion), ('SNAPER', snaper_criterion_2d_direction), ) def test_adaptation(self, criterion_fn): # Compare this to testAdaptation. There we don't use SPMD, but should # get the same hyperparameters. if not JAX_MODE: self.skipTest('TF does not have pmax implemented.') target = tfd.Independent( tfd.Normal(0., tf.constant([1., 10.])), 1) def run(seed): num_burnin_steps = 1000 num_adaptation_steps = int(num_burnin_steps * 0.8) num_results = 500 num_chains = 16 // distribute_test_lib.NUM_DEVICES step_size = 0.1 kernel = tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=step_size, num_leapfrog_steps=1, ) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=num_adaptation_steps, criterion_fn=criterion_fn, experimental_reduce_chain_axis_names=self.axis_name, validate_args=True) kernel = tfp.mcmc.DualAveragingStepSizeAdaptation( kernel, num_adaptation_steps=num_adaptation_steps, experimental_reduce_chain_axis_names=self.axis_name) def trace_fn(_, pkr): return ( pkr.inner_results.inner_results.accepted_results .step_size, pkr.inner_results.max_trajectory_length, pkr.inner_results.inner_results.log_accept_ratio, ) # The chain will be stepped for num_results + num_burnin_steps, adapting # for the first num_adaptation_steps. chain, [step_size, max_trajectory_length, log_accept_ratio] = ( tfp.mcmc.sample_chain( num_results=num_results, num_burnin_steps=num_burnin_steps, current_state=tf.zeros([num_chains, 2]), kernel=kernel, trace_fn=trace_fn, seed=seed)) p_accept = tf.math.exp( tfp.math.reduce_logmeanexp(tf.minimum(log_accept_ratio, 0.))) mean_step_size = tf.reduce_mean(step_size) mean_max_trajectory_length = tf.reduce_mean(max_trajectory_length) mean = tf.reduce_mean(chain, axis=[0, 1]) var = tf.reduce_variance(chain, axis=[0, 1]) return mean, var, p_accept, mean_step_size, mean_max_trajectory_length seeds = self.shard_values(tf.stack(tfp.random.split_seed( samplers.zeros_seed(), distribute_test_lib.NUM_DEVICES)), 0) (mean, var, p_accept, mean_step_size, mean_max_trajectory_length) = ( self.evaluate( self.per_replica_to_tensor( self.strategy_run(run, args=(seeds,), axis_name=self.axis_name), 0, ))) self.assertAllClose(0.75, p_accept.mean(), atol=0.1) # Both ChEES-rate and SNAPER learn roughly the same trajectory length. self.assertAllClose(1.5, mean_step_size[0], atol=0.2) self.assertAllClose(15., mean_max_trajectory_length[0], rtol=0.3) self.assertAllClose( target.mean(), mean.mean(0), atol=1.) self.assertAllClose( target.variance(), var.mean(0) + mean.var(0), rtol=0.1) del _GradientBasedTrajectoryLengthAdaptationTest if __name__ == '__main__': test_util.main()
37.59618
80
0.684774
from absl.testing import parameterized import numpy as np import tensorflow.compat.v1 as tf1 import tensorflow.compat.v2 as tf import tensorflow_probability as tfp from tensorflow_probability.python.internal import distribute_lib from tensorflow_probability.python.internal import distribute_test_lib from tensorflow_probability.python.internal import samplers from tensorflow_probability.python.internal import test_util tfb = tfp.bijectors tfd = tfp.distributions JAX_MODE = False def snaper_criterion_dummy_direction(previous_state, *args, **kwargs): return tfp.experimental.mcmc.snaper_criterion( previous_state, *args, direction=tf.nest.map_structure(tf.ones_like, previous_state), **kwargs, ) def snaper_criterion_2d_direction(previous_state, *args, **kwargs): return tfp.experimental.mcmc.snaper_criterion( previous_state, *args, direction=tf.constant([0., 1.], previous_state.dtype), **kwargs, ) @test_util.test_graph_and_eager_modes class GradientBasedTrajectoryLengthAdaptationTestGeneric( test_util.TestCase, parameterized.TestCase): def testForbiddenTransformedKernel(self): kernel = tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=lambda x: -x**2, step_size=0.1, num_leapfrog_steps=1) kernel = tfp.mcmc.TransformedTransitionKernel(kernel, tfb.Identity()) with self.assertRaisesRegex( ValueError, 'The inner kernel cannot contain a `TransformedTransitionKernel`'): kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=100) def testNestedStepSizeError(self): kernel = tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=lambda x: -x**2, step_size=[0.1], num_leapfrog_steps=1) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=100) with self.assertRaisesRegex(ValueError, 'Step size must be a scalar'): kernel.bootstrap_results([1.]) @parameterized.named_parameters(('StaticShape', True), ('DynamicShape', False)) def testNonScalarStepSizeError(self, use_static_shape): step_size = tf1.placeholder_with_default( [0.1, 0.2], shape=[2] if use_static_shape else None) kernel = tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=lambda x: -x**2, step_size=step_size, num_leapfrog_steps=1) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=100, validate_args=True) with self.assertRaisesRegex(Exception, 'Step size must be a scalar'): self.evaluate(kernel.bootstrap_results(tf.constant(1.))) @parameterized.named_parameters( ('ChEESStaticShape', True, tfp.experimental.mcmc.chees_criterion), ('ChEESDynamicShape', False, tfp.experimental.mcmc.chees_criterion), ('SNAPERStaticShape', True, snaper_criterion_dummy_direction), ('SNAPERDynamicShape', False, snaper_criterion_dummy_direction), ) def testTooFewChains(self, use_static_shape, criterion_fn): state = tf1.placeholder_with_default( [[0.1, 0.2]], shape=[1, 2] if use_static_shape else None) accept_prob = tf1.placeholder_with_default( [1.], shape=[1] if use_static_shape else None) with self.assertRaisesRegex(Exception, 'chees_criterion requires at least 2 chains'): self.evaluate( tfp.experimental.mcmc.chees_criterion( state, state, accept_prob, 1., validate_args=True)) @parameterized.named_parameters( ('ChEESStaticShape', True, tfp.experimental.mcmc.chees_criterion), ('ChEESDynamicShape', False, tfp.experimental.mcmc.chees_criterion), ('SNAPERStaticShape', True, snaper_criterion_dummy_direction), ('SNAPERDynamicShape', False, snaper_criterion_dummy_direction), ) def testNoBatchDims(self, use_static_shape, criterion_fn): state = tf1.placeholder_with_default( [[0.1, 0.2]], shape=[1, 2] if use_static_shape else None) accept_prob = tf1.placeholder_with_default( 1., shape=[] if use_static_shape else None) with self.assertRaisesRegex(Exception, 'requires at least 2 chains'): self.evaluate( criterion_fn(state, state, accept_prob, 1., validate_args=True)) class _GradientBasedTrajectoryLengthAdaptationTest(test_util.TestCase): def testDocstringExample(self): if tf.executing_eagerly() and not JAX_MODE: self.skipTest('Too slow for TF Eager.') target = tfd.JointDistributionSequential([ tfd.Normal(0., tf.constant(20., dtype=self.dtype)), tfd.HalfNormal(tf.constant(10., dtype=self.dtype)), ]) def target_log_prob_fn(*x): return tf.cast(target.log_prob(x), self.dtype) num_burnin_steps = 1000 num_adaptation_steps = int(num_burnin_steps * 0.8) num_results = 500 num_chains = 16 step_size = 0.1 kernel = tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target_log_prob_fn, step_size=step_size, num_leapfrog_steps=1, ) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=num_adaptation_steps, validate_args=True) kernel = tfp.mcmc.DualAveragingStepSizeAdaptation( kernel, num_adaptation_steps=num_adaptation_steps) kernel = tfp.mcmc.TransformedTransitionKernel( kernel, [tfb.Identity(), tfb.Exp()]) def trace_fn(_, pkr): return ( pkr.inner_results.inner_results.inner_results.accepted_results .step_size, pkr.inner_results.inner_results.max_trajectory_length, pkr.inner_results.inner_results.inner_results.log_accept_ratio, ) # The chain will be stepped for num_results + num_burnin_steps, adapting for # the first num_adaptation_steps. chain, [step_size, max_trajectory_length, log_accept_ratio] = ( tfp.mcmc.sample_chain( num_results=num_results, num_burnin_steps=num_burnin_steps, current_state=[ tf.ones(num_chains, dtype=self.dtype), tf.ones(num_chains, dtype=self.dtype) ], kernel=kernel, trace_fn=trace_fn, seed=test_util.test_seed(sampler_type='stateless'))) p_accept = tf.math.exp( tfp.math.reduce_logmeanexp(tf.minimum(log_accept_ratio, 0.))) mean_step_size = tf.reduce_mean(step_size) mean_max_trajectory_length = tf.reduce_mean(max_trajectory_length) self.assertAllClose(0.75, p_accept, atol=0.1) self.assertAllClose(0.52, mean_step_size, atol=0.2) self.assertAllClose(46., mean_max_trajectory_length, atol=15) self.assertAllClose( target.mean(), [tf.reduce_mean(x, axis=[0, 1]) for x in chain], atol=1.5) self.assertAllClose( target.variance(), [tf.math.reduce_variance(x, axis=[0, 1]) for x in chain], rtol=0.2) def testStateMeanSNAPER(self): state = np.array([[0.1, 0.2]], self.dtype) accept_prob = np.ones([], self.dtype) # This doesn't fail because state_mean is provided externally. self.evaluate(tfp.experimental.mcmc.snaper_criterion( state, state, accept_prob, 2., direction=tf.ones_like(state), state_mean=state, state_mean_weight=0.1, )) @parameterized.named_parameters( ('ChEES', tfp.experimental.mcmc.chees_criterion), ('SNAPER', snaper_criterion_dummy_direction), ) def testScalarState(self, criterion_fn): def target_log_prob_fn(x): return -x**2 / 2 kernel = tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target_log_prob_fn, step_size=0.1, num_leapfrog_steps=1, ) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=5, adaptation_rate=1., criterion_fn=criterion_fn, validate_args=True) state = tf.zeros([64], self.dtype) init_kernel_results = kernel.bootstrap_results(state) init_kernel_results, (_, final_kernel_results) = self.evaluate([ init_kernel_results, kernel.one_step( state, init_kernel_results, seed=test_util.test_seed(sampler_type='stateless')) ]) self.assertGreater( np.abs(init_kernel_results.max_trajectory_length - final_kernel_results.max_trajectory_length), 0.0005) @parameterized.named_parameters( ('ChEES', tfp.experimental.mcmc.chees_criterion), ('SNAPER', snaper_criterion_dummy_direction), ) def testTensorState(self, criterion_fn): def target_log_prob_fn(x): return -tf.reduce_mean(x**2, [-1, -2]) / 2 kernel = tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target_log_prob_fn, step_size=0.1, num_leapfrog_steps=1, ) kernel = ( tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=5, adaptation_rate=1., criterion_fn=criterion_fn, validate_args=True)) state = tf.zeros([64, 2, 3], self.dtype) init_kernel_results = kernel.bootstrap_results(state) init_kernel_results, (_, final_kernel_results) = self.evaluate([ init_kernel_results, kernel.one_step( state, init_kernel_results, seed=test_util.test_seed(sampler_type='stateless')) ]) self.assertGreater( np.abs(init_kernel_results.max_trajectory_length - final_kernel_results.max_trajectory_length), 0.0005) @parameterized.named_parameters( ('ChEES', tfp.experimental.mcmc.chees_criterion), ('SNAPER', snaper_criterion_dummy_direction), ) def testListState(self, criterion_fn): def target_log_prob_fn(x, y): return -x**2 / 2 - y**2 / 2 kernel = tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target_log_prob_fn, step_size=0.1, num_leapfrog_steps=1, ) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=5, adaptation_rate=1., criterion_fn=criterion_fn, validate_args=True) state = [tf.zeros([64], self.dtype), tf.zeros([64], self.dtype)] init_kernel_results = kernel.bootstrap_results(state) init_kernel_results, (_, final_kernel_results) = self.evaluate([ init_kernel_results, kernel.one_step( state, init_kernel_results, seed=test_util.test_seed(sampler_type='stateless')) ]) self.assertGreater( np.abs(init_kernel_results.max_trajectory_length - final_kernel_results.max_trajectory_length), 0.0005) @parameterized.named_parameters( ('ChEES', tfp.experimental.mcmc.chees_rate_criterion), ('SNAPER', snaper_criterion_2d_direction), ) def testAdaptation(self, criterion_fn): if tf.executing_eagerly() and not JAX_MODE: self.skipTest('Too slow for TF Eager.') target = tfd.Independent( tfd.Normal(0., tf.constant([1., 10.], self.dtype)), 1) num_burnin_steps = 1000 num_adaptation_steps = int(num_burnin_steps * 0.8) num_results = 500 num_chains = 16 step_size = 0.1 kernel = tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=step_size, num_leapfrog_steps=1, ) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=num_adaptation_steps, criterion_fn=criterion_fn, validate_args=True) kernel = tfp.mcmc.DualAveragingStepSizeAdaptation( kernel, num_adaptation_steps=num_adaptation_steps) def trace_fn(_, pkr): return ( pkr.inner_results.inner_results.accepted_results .step_size, pkr.inner_results.max_trajectory_length, pkr.inner_results.inner_results.log_accept_ratio, ) chain, [step_size, max_trajectory_length, log_accept_ratio] = ( tfp.mcmc.sample_chain( num_results=num_results, num_burnin_steps=num_burnin_steps, current_state=tf.zeros([num_chains, 2], dtype=self.dtype), kernel=kernel, trace_fn=trace_fn, seed=test_util.test_seed(sampler_type='stateless'))) p_accept = tf.math.exp( tfp.math.reduce_logmeanexp(tf.minimum(log_accept_ratio, 0.))) mean_step_size = tf.reduce_mean(step_size) mean_max_trajectory_length = tf.reduce_mean(max_trajectory_length) self.assertAllClose(0.75, p_accept, atol=0.1) self.assertAllClose(1.5, mean_step_size, atol=0.2) self.assertAllClose(15., mean_max_trajectory_length, rtol=0.3) self.assertAllClose( target.mean(), tf.reduce_mean(chain, axis=[0, 1]), atol=1.) self.assertAllClose( target.variance(), tf.math.reduce_variance(chain, axis=[0, 1]), rtol=0.1) def testPreconditionedHMC(self): if tf.executing_eagerly() and not JAX_MODE: self.skipTest('Too slow for TF Eager.') target = tfd.Independent( tfd.Normal(0., tf.constant([1., 10.], self.dtype)), 1) num_burnin_steps = 1000 num_adaptation_steps = int(num_burnin_steps * 0.8) num_results = 500 num_chains = 16 step_size = 0.1 kernel = tfp.experimental.mcmc.PreconditionedHamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=step_size, num_leapfrog_steps=1, momentum_distribution=tfd.Independent( tfd.Normal(0., tf.constant([1., 1. / 10.], self.dtype)), 1), ) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=num_adaptation_steps, validate_args=True) kernel = tfp.mcmc.DualAveragingStepSizeAdaptation( kernel, num_adaptation_steps=num_adaptation_steps) def trace_fn(_, pkr): return ( pkr.inner_results.inner_results.accepted_results .step_size, pkr.inner_results.max_trajectory_length, pkr.inner_results.inner_results.log_accept_ratio, ) chain, [step_size, max_trajectory_length, log_accept_ratio] = ( tfp.mcmc.sample_chain( num_results=num_results, num_burnin_steps=num_burnin_steps, current_state=tf.zeros([num_chains, 2], dtype=self.dtype), kernel=kernel, trace_fn=trace_fn, seed=test_util.test_seed(sampler_type='stateless'))) p_accept = tf.math.exp( tfp.math.reduce_logmeanexp(tf.minimum(log_accept_ratio, 0.))) mean_step_size = tf.reduce_mean(step_size) mean_max_trajectory_length = tf.reduce_mean(max_trajectory_length) self.assertAllClose(0.75, p_accept, atol=0.1) self.assertAllClose(1.2, mean_step_size, atol=0.2) self.assertAllClose(1.5, mean_max_trajectory_length, rtol=0.25) self.assertAllClose( target.mean(), tf.reduce_mean(chain, axis=[0, 1]), atol=0.3) self.assertAllClose( target.variance(), tf.math.reduce_variance(chain, axis=[0, 1]), rtol=0.1) def testNumAdaptationSteps(self): def target_log_prob_fn(x): return -x**2 kernel = tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target_log_prob_fn, step_size=0.1, num_leapfrog_steps=1, ) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=1, adaptation_rate=1., validate_args=True) state = tf.zeros([64], self.dtype) seed = test_util.test_seed(sampler_type='stateless') step_0_kernel_results = kernel.bootstrap_results(state) state, step_1_kernel_results = kernel.one_step( state, step_0_kernel_results, seed=seed) _, step_2_kernel_results = kernel.one_step( state, step_1_kernel_results, seed=seed) (step_0_kernel_results, step_1_kernel_results, step_2_kernel_results) = self.evaluate([ step_0_kernel_results, step_1_kernel_results, step_2_kernel_results, ]) self.assertGreater( np.abs(step_0_kernel_results.max_trajectory_length - step_1_kernel_results.max_trajectory_length), 0.005) self.assertAllClose(step_1_kernel_results.max_trajectory_length, step_2_kernel_results.max_trajectory_length) @parameterized.named_parameters( ('ChEES', tfp.experimental.mcmc.chees_criterion), ('ChEESR', tfp.experimental.mcmc.chees_rate_criterion), ('SNAPER', snaper_criterion_dummy_direction), ) def testCriterionStateEquivalence(self, criterion_fn): previous_state = np.random.randn(4, 6).astype(self.dtype) new_state = np.random.randn(4, 6).astype(self.dtype) accept_prob = np.random.uniform(size=(4,)).astype(self.dtype) matrix_previous_state = previous_state.reshape([4, 3, 2]) matrix_new_state = new_state.reshape([4, 3, 2]) list_previous_state = [previous_state[:, :2], previous_state[:, 2:]] list_new_state = [new_state[:, :2], new_state[:, 2:]] criterion = criterion_fn( previous_state, new_state, accept_prob, 1.) matrix_criterion = criterion_fn( matrix_previous_state, matrix_new_state, accept_prob, 1.) list_criterion = criterion_fn( list_previous_state, list_new_state, accept_prob, 1.) self.assertAllEqual([4], criterion.shape) self.assertAllClose(criterion, matrix_criterion) self.assertAllClose(criterion, list_criterion) class GradientBasedTrajectoryLengthAdaptationTestFloat32( _GradientBasedTrajectoryLengthAdaptationTest): dtype = np.float32 class GradientBasedTrajectoryLengthAdaptationTestFloat64( _GradientBasedTrajectoryLengthAdaptationTest): dtype = np.float64 @test_util.test_all_tf_execution_regimes class DistributedGBTLATest(distribute_test_lib.DistributedTest): def test_gbtla_kernel_tracks_axis_names(self): inner_kernel = tfp.mcmc.HamiltonianMonteCarlo(tfd.Normal(0, 1).log_prob, step_size=1.9, num_leapfrog_steps=2) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( inner_kernel, 1) self.assertIsNone(kernel.experimental_shard_axis_names) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( inner_kernel, 1, experimental_shard_axis_names=['a']) self.assertListEqual(kernel.experimental_shard_axis_names, ['a']) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( inner_kernel, 1).experimental_with_shard_axes(['a']) self.assertListEqual(kernel.experimental_shard_axis_names, ['a']) @parameterized.named_parameters( ('ChEES', tfp.experimental.mcmc.chees_criterion), ('ChEESR', tfp.experimental.mcmc.chees_rate_criterion), ('SNAPER', snaper_criterion_dummy_direction), ) def test_gbtla_kernel_computes_same_criterion_info_with_sharded_state( self, criterion_fn, ): if not JAX_MODE: self.skipTest('Test in TF runs into `merge_call` error: see b/178944108') def target_log_prob(a, b): return ( tfd.Normal(0., 1.).log_prob(a) + distribute_lib.psum(tfd.Normal( distribute_lib.pbroadcast(a, 'foo'), 1.).log_prob(b), 'foo')) kernel = tfp.mcmc.HamiltonianMonteCarlo(target_log_prob, step_size=1e-2, num_leapfrog_steps=2) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, 10, criterion_fn=criterion_fn) sharded_kernel = kernel.experimental_with_shard_axes([None, ['foo']]) def run(seed): init_seed, sample_seed = samplers.split_seed(seed) state_seeds = samplers.split_seed(init_seed) state = [ samplers.normal(seed=state_seeds[0], shape=[5]), samplers.normal(seed=state_seeds[1], shape=[5]) ] kr = sharded_kernel.bootstrap_results(state) _, kr = sharded_kernel.one_step(state, kr, seed=sample_seed) return ( kr.criterion, kr.averaged_sq_grad, kr.averaged_max_trajectory_length ) criterion, avg_sq_grad, avg_max_tl = self.evaluate( self.per_replica_to_tensor(self.strategy_run( run, args=(samplers.zeros_seed(),), in_axes=None, axis_name='foo'), 0)) for i in range(distribute_test_lib.NUM_DEVICES): self.assertAllClose(criterion[0], criterion[i]) self.assertAllClose(avg_sq_grad[0], avg_sq_grad[i]) self.assertAllClose(avg_max_tl[0], avg_max_tl[i]) @parameterized.named_parameters( ('ChEES', tfp.experimental.mcmc.chees_criterion), ('ChEESR', tfp.experimental.mcmc.chees_rate_criterion), ('SNAPER', snaper_criterion_dummy_direction), ) def test_gbtla_kernel_can_shard_chains_across_devices(self, criterion_fn): def target_log_prob(a, b): return ( tfd.Normal(0., 1.).log_prob(a) + tfd.Sample(tfd.Normal(a, 1.), 4).log_prob(b)) kernel = tfp.mcmc.HamiltonianMonteCarlo(target_log_prob, step_size=1e-2, num_leapfrog_steps=2) sharded_kernel = ( tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, 10, experimental_reduce_chain_axis_names=self.axis_name, criterion_fn=criterion_fn)) def run(seed): init_seed, sample_seed = samplers.split_seed(seed) state_seeds = samplers.split_seed(init_seed) state = [ samplers.normal(seed=state_seeds[0], shape=[]), samplers.normal(seed=state_seeds[1], shape=[4]) ] kr = sharded_kernel.bootstrap_results(state) _, kr = sharded_kernel.one_step(state, kr, seed=sample_seed) return ( kr.averaged_sq_grad, kr.averaged_max_trajectory_length ) seeds = self.shard_values(tf.stack(tfp.random.split_seed( samplers.zeros_seed(), distribute_test_lib.NUM_DEVICES)), 0) avg_sq_grad, avg_max_tl = self.evaluate( self.per_replica_to_tensor(self.strategy_run( run, args=(seeds,), axis_name=self.axis_name), 0)) for i in range(distribute_test_lib.NUM_DEVICES): self.assertAllClose(avg_sq_grad[0], avg_sq_grad[i]) self.assertAllClose(avg_max_tl[0], avg_max_tl[i]) @parameterized.named_parameters( ('ChEES', tfp.experimental.mcmc.chees_rate_criterion), ('SNAPER', snaper_criterion_2d_direction), ) def test_adaptation(self, criterion_fn): # get the same hyperparameters. if not JAX_MODE: self.skipTest('TF does not have pmax implemented.') target = tfd.Independent( tfd.Normal(0., tf.constant([1., 10.])), 1) def run(seed): num_burnin_steps = 1000 num_adaptation_steps = int(num_burnin_steps * 0.8) num_results = 500 num_chains = 16 // distribute_test_lib.NUM_DEVICES step_size = 0.1 kernel = tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target.log_prob, step_size=step_size, num_leapfrog_steps=1, ) kernel = tfp.experimental.mcmc.GradientBasedTrajectoryLengthAdaptation( kernel, num_adaptation_steps=num_adaptation_steps, criterion_fn=criterion_fn, experimental_reduce_chain_axis_names=self.axis_name, validate_args=True) kernel = tfp.mcmc.DualAveragingStepSizeAdaptation( kernel, num_adaptation_steps=num_adaptation_steps, experimental_reduce_chain_axis_names=self.axis_name) def trace_fn(_, pkr): return ( pkr.inner_results.inner_results.accepted_results .step_size, pkr.inner_results.max_trajectory_length, pkr.inner_results.inner_results.log_accept_ratio, ) # The chain will be stepped for num_results + num_burnin_steps, adapting # for the first num_adaptation_steps. chain, [step_size, max_trajectory_length, log_accept_ratio] = ( tfp.mcmc.sample_chain( num_results=num_results, num_burnin_steps=num_burnin_steps, current_state=tf.zeros([num_chains, 2]), kernel=kernel, trace_fn=trace_fn, seed=seed)) p_accept = tf.math.exp( tfp.math.reduce_logmeanexp(tf.minimum(log_accept_ratio, 0.))) mean_step_size = tf.reduce_mean(step_size) mean_max_trajectory_length = tf.reduce_mean(max_trajectory_length) mean = tf.reduce_mean(chain, axis=[0, 1]) var = tf.reduce_variance(chain, axis=[0, 1]) return mean, var, p_accept, mean_step_size, mean_max_trajectory_length seeds = self.shard_values(tf.stack(tfp.random.split_seed( samplers.zeros_seed(), distribute_test_lib.NUM_DEVICES)), 0) (mean, var, p_accept, mean_step_size, mean_max_trajectory_length) = ( self.evaluate( self.per_replica_to_tensor( self.strategy_run(run, args=(seeds,), axis_name=self.axis_name), 0, ))) self.assertAllClose(0.75, p_accept.mean(), atol=0.1) # Both ChEES-rate and SNAPER learn roughly the same trajectory length. self.assertAllClose(1.5, mean_step_size[0], atol=0.2) self.assertAllClose(15., mean_max_trajectory_length[0], rtol=0.3) self.assertAllClose( target.mean(), mean.mean(0), atol=1.) self.assertAllClose( target.variance(), var.mean(0) + mean.var(0), rtol=0.1) del _GradientBasedTrajectoryLengthAdaptationTest if __name__ == '__main__': test_util.main()
true
true
f7fe65b23c0297d29f75693515a88dffa7e50e93
2,718
py
Python
counters/views.py
aisahana/eclinic_api
feb67008f55f6af978adf2e55600ed17e7e514d3
[ "MIT" ]
5
2019-10-29T22:45:24.000Z
2021-08-15T07:04:50.000Z
counters/views.py
AldiAE/eclinic_api
feb67008f55f6af978adf2e55600ed17e7e514d3
[ "MIT" ]
5
2020-06-06T00:16:24.000Z
2022-02-10T10:43:15.000Z
counters/views.py
AldiAE/eclinic_api
feb67008f55f6af978adf2e55600ed17e7e514d3
[ "MIT" ]
8
2019-10-29T04:17:14.000Z
2022-03-02T13:32:25.000Z
from rest_framework import viewsets, status from rest_framework.authentication import TokenAuthentication from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated, AllowAny from rest_framework.response import Response from counters.models import Counter, Queue from counters.serializers import CounterSerializer, QueueSerializer, GenerateQueueSerializer from utils.views import generate_queue class CounterViewSet(viewsets.ModelViewSet): serializer_class = CounterSerializer queryset = Counter.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) ordering_fields = ['created',] search_fields = [ 'counter_number', 'name', ] filterset_fields = [ 'is_draft', ] @action(detail=True, methods=['post']) def publish(self, request, pk=None): counter = self.get_object() counter.is_draft = False counter.save() return Response(self.get_serializer(counter, many=False).data) @action(detail=True, methods=['post']) def draft(self, request, pk=None): counter = self.get_object() counter.is_draft = True counter.save() return Response(self.get_serializer(counter, many=False).data) @action(detail=False, methods=['get'], permission_classes=[AllowAny]) def public(self, request): queryset = self.get_queryset().filter(is_draft=False) return Response(self.get_serializer(queryset, many=True).data) class QueueViewSet(viewsets.ModelViewSet): serializer_class = QueueSerializer queryset = Queue.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) ordering_fields = ['created',] search_fields = [ 'counter__counter_number', 'counter__counter_name', 'number', ] filterset_fields = [ 'is_draft', 'is_complete', ] @action(detail=False, methods=['post'], permission_classes=[AllowAny]) def generate(self, request): serializer = GenerateQueueSerializer(data=request.data) if serializer.is_valid(): queue = serializer.save() queue = generate_queue(queue.counter, queue) return Response(self.get_serializer(queue, many=False).data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @action(detail=True, methods=['post'], permission_classes=[AllowAny]) def next_number(self, request, pk=None): queue = self.get_object() queue.is_complete = True queue.save() return Response(self.get_serializer(queue, many=False).data)
33.975
92
0.696836
from rest_framework import viewsets, status from rest_framework.authentication import TokenAuthentication from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated, AllowAny from rest_framework.response import Response from counters.models import Counter, Queue from counters.serializers import CounterSerializer, QueueSerializer, GenerateQueueSerializer from utils.views import generate_queue class CounterViewSet(viewsets.ModelViewSet): serializer_class = CounterSerializer queryset = Counter.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) ordering_fields = ['created',] search_fields = [ 'counter_number', 'name', ] filterset_fields = [ 'is_draft', ] @action(detail=True, methods=['post']) def publish(self, request, pk=None): counter = self.get_object() counter.is_draft = False counter.save() return Response(self.get_serializer(counter, many=False).data) @action(detail=True, methods=['post']) def draft(self, request, pk=None): counter = self.get_object() counter.is_draft = True counter.save() return Response(self.get_serializer(counter, many=False).data) @action(detail=False, methods=['get'], permission_classes=[AllowAny]) def public(self, request): queryset = self.get_queryset().filter(is_draft=False) return Response(self.get_serializer(queryset, many=True).data) class QueueViewSet(viewsets.ModelViewSet): serializer_class = QueueSerializer queryset = Queue.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) ordering_fields = ['created',] search_fields = [ 'counter__counter_number', 'counter__counter_name', 'number', ] filterset_fields = [ 'is_draft', 'is_complete', ] @action(detail=False, methods=['post'], permission_classes=[AllowAny]) def generate(self, request): serializer = GenerateQueueSerializer(data=request.data) if serializer.is_valid(): queue = serializer.save() queue = generate_queue(queue.counter, queue) return Response(self.get_serializer(queue, many=False).data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @action(detail=True, methods=['post'], permission_classes=[AllowAny]) def next_number(self, request, pk=None): queue = self.get_object() queue.is_complete = True queue.save() return Response(self.get_serializer(queue, many=False).data)
true
true
f7fe662a0c6c60ba566830b70edc654b6129c849
2,538
py
Python
Dynamic-channels/test.py
void-zxh/CS337-SRDGI
e86413affd5867d42f9bbe66030d13b29bd2e067
[ "MIT" ]
null
null
null
Dynamic-channels/test.py
void-zxh/CS337-SRDGI
e86413affd5867d42f9bbe66030d13b29bd2e067
[ "MIT" ]
null
null
null
Dynamic-channels/test.py
void-zxh/CS337-SRDGI
e86413affd5867d42f9bbe66030d13b29bd2e067
[ "MIT" ]
1
2022-01-04T12:32:40.000Z
2022-01-04T12:32:40.000Z
import argparse import os import time import torch from torch.autograd import Variable from dynamic_channels import sample_tiny_sub_channel from model import G from util import is_image, load_image, save_image parser = argparse.ArgumentParser(description='DeepRendering-implementation') parser.add_argument('--dataset', required=True, help='unity') parser.add_argument('--model', type=str, required=True, help='model file') parser.add_argument('--accuracy', type=int, default=1, help='model file') parser.add_argument('--n_channel_input', type=int, default=3, help='input channel') parser.add_argument('--n_channel_output', type=int, default=3, help='output channel') parser.add_argument('--n_generator_filters', type=int, default=64, help="number of generator filters") opt = parser.parse_args() netG_model = torch.load(opt.model) netG = G(opt.n_channel_input * 4, opt.n_channel_output, opt.n_generator_filters) netG.load_state_dict(netG_model['state_dict_G']) root_dir = 'dataset/{}/test/'.format(opt.dataset) image_dir = 'dataset/{}/test/albedo'.format(opt.dataset) image_filenames = [x for x in os.listdir(image_dir) if is_image(x)] time_list=[] for image_name in image_filenames: albedo_image = load_image(root_dir + 'albedo/' + image_name) direct_image = load_image(root_dir + 'direct/' + image_name) normal_image = load_image(root_dir + 'normal/' + image_name) depth_image = load_image(root_dir + 'depth/' + image_name) gt_image = load_image(root_dir + 'gt/' + image_name) albedo = Variable(albedo_image).view(1, -1, 256, 256).cuda() direct = Variable(direct_image).view(1, -1, 256, 256).cuda() normal = Variable(normal_image).view(1, -1, 256, 256).cuda() depth = Variable(depth_image).view(1, -1, 256, 256).cuda() sample_tiny_sub_channel(netG, size=opt.accuracy, n_filters=opt.n_generator_filters) netG = netG.cuda() start_p=time.time() out = netG(torch.cat((albedo, direct, normal, depth), 1)) end_p=time.time() out = out.cpu() out_img = out.data[0] time_list.append(end_p-start_p) if not os.path.exists("result"): os.mkdir("result") if not os.path.exists(os.path.join("result", "accuracy_{}".format(opt.accuracy))): os.mkdir(os.path.join("result", "accuracy_{}".format(opt.accuracy))) save_image(out_img, "result/accuracy_{}/{}".format(opt.accuracy, image_name)) save_image(gt_image, "result/accuracy_{}/GT{}".format(opt.accuracy, image_name)) print(time_list)
45.321429
103
0.70922
import argparse import os import time import torch from torch.autograd import Variable from dynamic_channels import sample_tiny_sub_channel from model import G from util import is_image, load_image, save_image parser = argparse.ArgumentParser(description='DeepRendering-implementation') parser.add_argument('--dataset', required=True, help='unity') parser.add_argument('--model', type=str, required=True, help='model file') parser.add_argument('--accuracy', type=int, default=1, help='model file') parser.add_argument('--n_channel_input', type=int, default=3, help='input channel') parser.add_argument('--n_channel_output', type=int, default=3, help='output channel') parser.add_argument('--n_generator_filters', type=int, default=64, help="number of generator filters") opt = parser.parse_args() netG_model = torch.load(opt.model) netG = G(opt.n_channel_input * 4, opt.n_channel_output, opt.n_generator_filters) netG.load_state_dict(netG_model['state_dict_G']) root_dir = 'dataset/{}/test/'.format(opt.dataset) image_dir = 'dataset/{}/test/albedo'.format(opt.dataset) image_filenames = [x for x in os.listdir(image_dir) if is_image(x)] time_list=[] for image_name in image_filenames: albedo_image = load_image(root_dir + 'albedo/' + image_name) direct_image = load_image(root_dir + 'direct/' + image_name) normal_image = load_image(root_dir + 'normal/' + image_name) depth_image = load_image(root_dir + 'depth/' + image_name) gt_image = load_image(root_dir + 'gt/' + image_name) albedo = Variable(albedo_image).view(1, -1, 256, 256).cuda() direct = Variable(direct_image).view(1, -1, 256, 256).cuda() normal = Variable(normal_image).view(1, -1, 256, 256).cuda() depth = Variable(depth_image).view(1, -1, 256, 256).cuda() sample_tiny_sub_channel(netG, size=opt.accuracy, n_filters=opt.n_generator_filters) netG = netG.cuda() start_p=time.time() out = netG(torch.cat((albedo, direct, normal, depth), 1)) end_p=time.time() out = out.cpu() out_img = out.data[0] time_list.append(end_p-start_p) if not os.path.exists("result"): os.mkdir("result") if not os.path.exists(os.path.join("result", "accuracy_{}".format(opt.accuracy))): os.mkdir(os.path.join("result", "accuracy_{}".format(opt.accuracy))) save_image(out_img, "result/accuracy_{}/{}".format(opt.accuracy, image_name)) save_image(gt_image, "result/accuracy_{}/GT{}".format(opt.accuracy, image_name)) print(time_list)
true
true
f7fe67c0cfeb378edf623c5d01b3a275d4d5bf9d
336
py
Python
docs/add_glossary.py
NotMyFault/templating-engine-plugin
a3506f938a189909a5c8b921f18845b87a8ac5c7
[ "Apache-2.0" ]
133
2019-03-07T21:08:02.000Z
2022-03-29T14:05:53.000Z
docs/add_glossary.py
NotMyFault/templating-engine-plugin
a3506f938a189909a5c8b921f18845b87a8ac5c7
[ "Apache-2.0" ]
156
2019-07-30T13:46:57.000Z
2022-03-28T16:27:19.000Z
docs/add_glossary.py
NotMyFault/templating-engine-plugin
a3506f938a189909a5c8b921f18845b87a8ac5c7
[ "Apache-2.0" ]
61
2019-03-07T20:00:18.000Z
2022-03-21T01:28:06.000Z
import mkdocs_gen_files import os import glob # iterate over pages and append glossary for file in glob.glob("/docs/docs/**/*.md", recursive = True): if file.endswith('.md'): text = open(file).read() with mkdocs_gen_files.open(file.replace('/docs/docs/', ''), "w") as f: print(text + '\n--8<-- "./glossary.md"', file=f)
33.6
74
0.64881
import mkdocs_gen_files import os import glob for file in glob.glob("/docs/docs/**/*.md", recursive = True): if file.endswith('.md'): text = open(file).read() with mkdocs_gen_files.open(file.replace('/docs/docs/', ''), "w") as f: print(text + '\n--8<-- "./glossary.md"', file=f)
true
true
f7fe68d6d7de6e694493f5f30e97587cbc29d818
394
py
Python
instagram_api/response/post_live_viewer_list.py
Yuego/instagram_api
b53f72db36c505a2eb24ebac1ba8267a0cc295bb
[ "MIT" ]
13
2019-08-07T21:24:34.000Z
2020-12-12T12:23:50.000Z
instagram_api/response/post_live_viewer_list.py
Yuego/instagram_api
b53f72db36c505a2eb24ebac1ba8267a0cc295bb
[ "MIT" ]
null
null
null
instagram_api/response/post_live_viewer_list.py
Yuego/instagram_api
b53f72db36c505a2eb24ebac1ba8267a0cc295bb
[ "MIT" ]
null
null
null
from .mapper import ApiResponse, ApiResponseInterface from .mapper.types import Timestamp, AnyType from .model import User __all__ = ['PostLiveViewerListResponse'] class PostLiveViewerListResponseInterface(ApiResponseInterface): users: [User] next_max_id: str total_viewer_count: int class PostLiveViewerListResponse(ApiResponse, PostLiveViewerListResponseInterface): pass
24.625
83
0.814721
from .mapper import ApiResponse, ApiResponseInterface from .mapper.types import Timestamp, AnyType from .model import User __all__ = ['PostLiveViewerListResponse'] class PostLiveViewerListResponseInterface(ApiResponseInterface): users: [User] next_max_id: str total_viewer_count: int class PostLiveViewerListResponse(ApiResponse, PostLiveViewerListResponseInterface): pass
true
true
f7fe68f88a88b9128f190f27c71f8783dc3120dc
607
py
Python
integration_tests/test_leica_disto_r12.py
jkjt/ezdxf
2acc5611b81476ea16b98063b9f55446a9182b81
[ "MIT" ]
515
2017-01-25T05:46:52.000Z
2022-03-29T09:52:27.000Z
integration_tests/test_leica_disto_r12.py
jkjt/ezdxf
2acc5611b81476ea16b98063b9f55446a9182b81
[ "MIT" ]
417
2017-01-25T10:01:17.000Z
2022-03-29T09:22:04.000Z
integration_tests/test_leica_disto_r12.py
jkjt/ezdxf
2acc5611b81476ea16b98063b9f55446a9182b81
[ "MIT" ]
149
2017-02-01T15:52:02.000Z
2022-03-17T10:33:38.000Z
# Copyright (c) 2020, Manfred Moitzi # License: MIT License import os import pytest import ezdxf BASEDIR = os.path.dirname(__file__) DATADIR = "data" @pytest.fixture(params=["Leica_Disto_S910.dxf"]) def filename(request): filename = os.path.join(BASEDIR, DATADIR, request.param) if not os.path.exists(filename): pytest.skip(f"File {filename} not found.") return filename def test_leica_disto_r12(filename): doc = ezdxf.readfile(filename) msp = doc.modelspace() points = list(msp.query("POINT")) assert len(points) == 11 assert len(points[0].dxf.location) == 3
24.28
60
0.69687
import os import pytest import ezdxf BASEDIR = os.path.dirname(__file__) DATADIR = "data" @pytest.fixture(params=["Leica_Disto_S910.dxf"]) def filename(request): filename = os.path.join(BASEDIR, DATADIR, request.param) if not os.path.exists(filename): pytest.skip(f"File {filename} not found.") return filename def test_leica_disto_r12(filename): doc = ezdxf.readfile(filename) msp = doc.modelspace() points = list(msp.query("POINT")) assert len(points) == 11 assert len(points[0].dxf.location) == 3
true
true
f7fe6aaab78490f28adb8207d40caa3e9121ddc2
663
py
Python
modules/jquery/chuck_module.py
msabramo/django-chuck
bbef6171c9b3738460dc05cb77e65ba88fcc5ad8
[ "BSD-2-Clause" ]
1
2020-05-29T04:27:50.000Z
2020-05-29T04:27:50.000Z
modules/jquery/chuck_module.py
msabramo/django-chuck
bbef6171c9b3738460dc05cb77e65ba88fcc5ad8
[ "BSD-2-Clause" ]
null
null
null
modules/jquery/chuck_module.py
msabramo/django-chuck
bbef6171c9b3738460dc05cb77e65ba88fcc5ad8
[ "BSD-2-Clause" ]
null
null
null
import subprocess import os description = """ Installs the jQuery javascript library into the static folders. Please note, that this module requires Git in order to work properly. For more information, visit: http://jquery.org/ """ def post_build(): jquery_dir = os.path.join(project_dir, 'static/scripts/libs/jquery') if not os.path.exists(jquery_dir): os.makedirs(jquery_dir) subprocess.call( 'cd '+site_dir+'; mkdir .src; cd .src; \ git clone git://github.com/jquery/jquery.git; \ cd jquery; \ make; \ mv -v dist/* '+jquery_dir+'; \ cd '+site_dir+'; rm -rf .src;', shell=True)
27.625
72
0.636501
import subprocess import os description = """ Installs the jQuery javascript library into the static folders. Please note, that this module requires Git in order to work properly. For more information, visit: http://jquery.org/ """ def post_build(): jquery_dir = os.path.join(project_dir, 'static/scripts/libs/jquery') if not os.path.exists(jquery_dir): os.makedirs(jquery_dir) subprocess.call( 'cd '+site_dir+'; mkdir .src; cd .src; \ git clone git://github.com/jquery/jquery.git; \ cd jquery; \ make; \ mv -v dist/* '+jquery_dir+'; \ cd '+site_dir+'; rm -rf .src;', shell=True)
true
true
f7fe6cf13e7d36f7c5800d10790a765e3630fd45
3,994
py
Python
src/cowrie/ssh_proxy/protocols/exec_term.py
iconnor/cowrie
33c3f7c7d0ec797fd098043d4b1c201e8e1f4a11
[ "BSD-3-Clause" ]
1
2021-10-15T05:00:15.000Z
2021-10-15T05:00:15.000Z
src/cowrie/ssh_proxy/protocols/exec_term.py
iconnor/cowrie
33c3f7c7d0ec797fd098043d4b1c201e8e1f4a11
[ "BSD-3-Clause" ]
3
2021-09-13T02:37:23.000Z
2022-03-03T21:48:46.000Z
src/cowrie/ssh_proxy/protocols/exec_term.py
iconnor/cowrie
33c3f7c7d0ec797fd098043d4b1c201e8e1f4a11
[ "BSD-3-Clause" ]
null
null
null
# Copyright (c) 2016 Thomas Nicholson <tnnich@googlemail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. The names of the author(s) may not be used to endorse or promote # products derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. import os import time from twisted.python import log from cowrie.core import ttylog from cowrie.core.config import CowrieConfig from cowrie.ssh_proxy.protocols import base_protocol class ExecTerm(base_protocol.BaseProtocol): def __init__(self, uuid, channelName, ssh, channelId, command): super().__init__(uuid, channelName, ssh) try: log.msg( eventid="cowrie.command.input", input=command.decode("utf8"), format="CMD: %(input)s", ) except UnicodeDecodeError: log.err("Unusual execcmd: {}".format(repr(command))) self.transportId = ssh.server.transportId self.channelId = channelId self.startTime: float = time.time() self.ttylogPath: str = CowrieConfig.get("honeypot", "ttylog_path") self.ttylogEnabled: bool = CowrieConfig.getboolean( "honeypot", "ttylog", fallback=True ) self.ttylogSize: bool = 0 if self.ttylogEnabled: self.ttylogFile = "{}/{}-{}-{}e.log".format( self.ttylogPath, time.strftime("%Y%m%d-%H%M%S"), self.transportId, self.channelId, ) ttylog.ttylog_open(self.ttylogFile, self.startTime) def parse_packet(self, parent, payload): if self.ttylogEnabled: ttylog.ttylog_write( self.ttylogFile, len(payload), ttylog.TYPE_OUTPUT, time.time(), payload ) self.ttylogSize += len(payload) def channel_closed(self): if self.ttylogEnabled: ttylog.ttylog_close(self.ttylogFile, time.time()) shasum = ttylog.ttylog_inputhash(self.ttylogFile) shasumfile = os.path.join(self.ttylogPath, shasum) if os.path.exists(shasumfile): duplicate = True os.remove(self.ttylogFile) else: duplicate = False os.rename(self.ttylogFile, shasumfile) umask = os.umask(0) os.umask(umask) os.chmod(shasumfile, 0o666 & ~umask) log.msg( eventid="cowrie.log.closed", format="Closing TTY Log: %(ttylog)s after %(duration)d seconds", ttylog=shasumfile, size=self.ttylogSize, shasum=shasum, duplicate=duplicate, duration=time.time() - self.startTime, )
38.776699
87
0.641963
import os import time from twisted.python import log from cowrie.core import ttylog from cowrie.core.config import CowrieConfig from cowrie.ssh_proxy.protocols import base_protocol class ExecTerm(base_protocol.BaseProtocol): def __init__(self, uuid, channelName, ssh, channelId, command): super().__init__(uuid, channelName, ssh) try: log.msg( eventid="cowrie.command.input", input=command.decode("utf8"), format="CMD: %(input)s", ) except UnicodeDecodeError: log.err("Unusual execcmd: {}".format(repr(command))) self.transportId = ssh.server.transportId self.channelId = channelId self.startTime: float = time.time() self.ttylogPath: str = CowrieConfig.get("honeypot", "ttylog_path") self.ttylogEnabled: bool = CowrieConfig.getboolean( "honeypot", "ttylog", fallback=True ) self.ttylogSize: bool = 0 if self.ttylogEnabled: self.ttylogFile = "{}/{}-{}-{}e.log".format( self.ttylogPath, time.strftime("%Y%m%d-%H%M%S"), self.transportId, self.channelId, ) ttylog.ttylog_open(self.ttylogFile, self.startTime) def parse_packet(self, parent, payload): if self.ttylogEnabled: ttylog.ttylog_write( self.ttylogFile, len(payload), ttylog.TYPE_OUTPUT, time.time(), payload ) self.ttylogSize += len(payload) def channel_closed(self): if self.ttylogEnabled: ttylog.ttylog_close(self.ttylogFile, time.time()) shasum = ttylog.ttylog_inputhash(self.ttylogFile) shasumfile = os.path.join(self.ttylogPath, shasum) if os.path.exists(shasumfile): duplicate = True os.remove(self.ttylogFile) else: duplicate = False os.rename(self.ttylogFile, shasumfile) umask = os.umask(0) os.umask(umask) os.chmod(shasumfile, 0o666 & ~umask) log.msg( eventid="cowrie.log.closed", format="Closing TTY Log: %(ttylog)s after %(duration)d seconds", ttylog=shasumfile, size=self.ttylogSize, shasum=shasum, duplicate=duplicate, duration=time.time() - self.startTime, )
true
true
f7fe6df0e3dabb730e3d388fe3b34f930ffd281f
954
py
Python
test/t_normalrdmbased.py
ZitongLu1996/PyCTRSA
7b243930321c089e235c9fc1e771b6432d530819
[ "MIT" ]
17
2020-07-26T17:05:12.000Z
2022-03-09T04:59:09.000Z
test/t_normalrdmbased.py
ZitongLu1996/PyCTRSA
7b243930321c089e235c9fc1e771b6432d530819
[ "MIT" ]
null
null
null
test/t_normalrdmbased.py
ZitongLu1996/PyCTRSA
7b243930321c089e235c9fc1e771b6432d530819
[ "MIT" ]
3
2020-08-02T14:48:02.000Z
2020-11-26T12:31:46.000Z
# -*- coding: utf-8 """ @File : t_normalrdmbased.py @Author : Zitong Lu @Contact : zitonglu1996@gmail.com @License : MIT License """ import numpy as np import unittest from pyctrsa.ctsimilarity.normalrdmbased import ctsimilarities_cal class test_normalrdmbased(unittest.TestCase): def test_ctsimilarities_cal(self): RDMs = np.random.rand(20, 6, 6) CTSimilarities = ctsimilarities_cal(RDMs) self.assertEqual(CTSimilarities.shape[0], 20) self.assertEqual(len(CTSimilarities.shape), 3) RDMs = np.random.rand(5, 20, 6, 6) CTSimilarities = ctsimilarities_cal(RDMs) self.assertEqual(CTSimilarities.shape[0], 5) self.assertEqual(len(CTSimilarities.shape), 4) RDMs = np.random.rand(5, 4, 20, 6, 6) CTSimilarities = ctsimilarities_cal(RDMs) self.assertEqual(CTSimilarities.shape[0], 5) self.assertEqual(len(CTSimilarities.shape), 5)
30.774194
66
0.675052
import numpy as np import unittest from pyctrsa.ctsimilarity.normalrdmbased import ctsimilarities_cal class test_normalrdmbased(unittest.TestCase): def test_ctsimilarities_cal(self): RDMs = np.random.rand(20, 6, 6) CTSimilarities = ctsimilarities_cal(RDMs) self.assertEqual(CTSimilarities.shape[0], 20) self.assertEqual(len(CTSimilarities.shape), 3) RDMs = np.random.rand(5, 20, 6, 6) CTSimilarities = ctsimilarities_cal(RDMs) self.assertEqual(CTSimilarities.shape[0], 5) self.assertEqual(len(CTSimilarities.shape), 4) RDMs = np.random.rand(5, 4, 20, 6, 6) CTSimilarities = ctsimilarities_cal(RDMs) self.assertEqual(CTSimilarities.shape[0], 5) self.assertEqual(len(CTSimilarities.shape), 5)
true
true
f7fe6e12069e9f9aeeb94f79139bee9b65302204
3,491
py
Python
test/test_bytesstorage.py
Pat-Laub/pyABC
f23f0ff8d430a8ce0a0c8253b45e19add9121992
[ "BSD-3-Clause" ]
null
null
null
test/test_bytesstorage.py
Pat-Laub/pyABC
f23f0ff8d430a8ce0a0c8253b45e19add9121992
[ "BSD-3-Clause" ]
null
null
null
test/test_bytesstorage.py
Pat-Laub/pyABC
f23f0ff8d430a8ce0a0c8253b45e19add9121992
[ "BSD-3-Clause" ]
null
null
null
import pytest from pyabc.storage.bytes_storage import to_bytes, from_bytes import pandas as pd import numpy as np import scipy as sp from rpy2.robjects import r import rpy2.robjects as robjects from rpy2.robjects import pandas2ri @pytest.fixture(params=["empty", "int", "float", "non_numeric_str", "numeric_str", "int-float-numeric_str", "int-float-non_numeric_str-str_ind", "int-float-numeric_str-str_ind", "py-int", "py-float", "py-str", "r-df-cars", "r-df-faithful" # TODO re-add iris, see #45 ]) def object_(request): par = request.param if par == "empty": return pd.DataFrame() if par == "int": return pd.DataFrame({"a": sp.random.randint(-20, 20, 100), "b": sp.random.randint(-20, 20, 100)}) if par == "float": return pd.DataFrame({"a": sp.randn(100), "b": sp.randn(100)}) if par == "non_numeric_str": return pd.DataFrame({"a": ["foo", "bar"], "b": ["bar", "foo"]}) if par == "numeric_str": return pd.DataFrame({"a": list(map(str, sp.randn(100))), "b": list(map(str, sp.random.randint(-20, 20, 100)))}) if par == "int-float-numeric_str": return pd.DataFrame({"a": sp.random.randint(-20, 20, 100), "b": sp.randn(100), "c": list(map(str, sp.random.randint(-20, 20, 100)))}) if par == "int-float-non_numeric_str-str_ind": return pd.DataFrame({"a": [1, 2], "b": [1.1, 2.2], "c": ["foo", "bar"]}, index=["first", "second"]) if par == "int-float-numeric_str-str_ind": return pd.DataFrame({"a": [1, 2], "b": [1.1, 2.2], "c": ["1", "2"]}, index=["first", "second"]) if par == "py-int": return 42 if par == "py-float": return 42.42 if par == "py-str": return "foo bar" if par == "np-int": return sp.random.randint(-20, 20, 100) if par == "np-float": return sp.random.randn(100) if par == "r-df-cars": return r["mtcars"] if par == "r-df-iris": return r["iris"] if par == "r-df-faithful": return r["faithful"] raise Exception("Invalid Test DataFrame Type") def test_storage(object_): serial = to_bytes(object_) assert isinstance(serial, bytes) rebuilt = from_bytes(serial) if not isinstance(object_, robjects.DataFrame): assert isinstance(object_, type(rebuilt)) if isinstance(object_, int): assert object_ == rebuilt elif isinstance(object_, float): assert object_ == rebuilt elif isinstance(object_, str): assert object_ == rebuilt elif isinstance(object_, np.ndarray): assert (object_ == rebuilt).all() elif isinstance(object_, pd.DataFrame): assert (object_ == rebuilt).all().all() elif isinstance(object_, robjects.DataFrame): assert (pandas2ri.ri2py(object_) == rebuilt).all().all() else: raise Exception("Could not compare")
36.747368
78
0.496419
import pytest from pyabc.storage.bytes_storage import to_bytes, from_bytes import pandas as pd import numpy as np import scipy as sp from rpy2.robjects import r import rpy2.robjects as robjects from rpy2.robjects import pandas2ri @pytest.fixture(params=["empty", "int", "float", "non_numeric_str", "numeric_str", "int-float-numeric_str", "int-float-non_numeric_str-str_ind", "int-float-numeric_str-str_ind", "py-int", "py-float", "py-str", "r-df-cars", "r-df-faithful" ]) def object_(request): par = request.param if par == "empty": return pd.DataFrame() if par == "int": return pd.DataFrame({"a": sp.random.randint(-20, 20, 100), "b": sp.random.randint(-20, 20, 100)}) if par == "float": return pd.DataFrame({"a": sp.randn(100), "b": sp.randn(100)}) if par == "non_numeric_str": return pd.DataFrame({"a": ["foo", "bar"], "b": ["bar", "foo"]}) if par == "numeric_str": return pd.DataFrame({"a": list(map(str, sp.randn(100))), "b": list(map(str, sp.random.randint(-20, 20, 100)))}) if par == "int-float-numeric_str": return pd.DataFrame({"a": sp.random.randint(-20, 20, 100), "b": sp.randn(100), "c": list(map(str, sp.random.randint(-20, 20, 100)))}) if par == "int-float-non_numeric_str-str_ind": return pd.DataFrame({"a": [1, 2], "b": [1.1, 2.2], "c": ["foo", "bar"]}, index=["first", "second"]) if par == "int-float-numeric_str-str_ind": return pd.DataFrame({"a": [1, 2], "b": [1.1, 2.2], "c": ["1", "2"]}, index=["first", "second"]) if par == "py-int": return 42 if par == "py-float": return 42.42 if par == "py-str": return "foo bar" if par == "np-int": return sp.random.randint(-20, 20, 100) if par == "np-float": return sp.random.randn(100) if par == "r-df-cars": return r["mtcars"] if par == "r-df-iris": return r["iris"] if par == "r-df-faithful": return r["faithful"] raise Exception("Invalid Test DataFrame Type") def test_storage(object_): serial = to_bytes(object_) assert isinstance(serial, bytes) rebuilt = from_bytes(serial) if not isinstance(object_, robjects.DataFrame): assert isinstance(object_, type(rebuilt)) if isinstance(object_, int): assert object_ == rebuilt elif isinstance(object_, float): assert object_ == rebuilt elif isinstance(object_, str): assert object_ == rebuilt elif isinstance(object_, np.ndarray): assert (object_ == rebuilt).all() elif isinstance(object_, pd.DataFrame): assert (object_ == rebuilt).all().all() elif isinstance(object_, robjects.DataFrame): assert (pandas2ri.ri2py(object_) == rebuilt).all().all() else: raise Exception("Could not compare")
true
true
f7fe6ff68f166ec3b32d20a529d63d348ef8636d
2,564
py
Python
pypy/module/_rawffi/__init__.py
benoitc/pypy
a3e1b12d1d01dc29056b7badc051ffc034297658
[ "MIT" ]
1
2020-01-21T11:10:51.000Z
2020-01-21T11:10:51.000Z
pypy/module/_rawffi/__init__.py
benoitc/pypy
a3e1b12d1d01dc29056b7badc051ffc034297658
[ "MIT" ]
null
null
null
pypy/module/_rawffi/__init__.py
benoitc/pypy
a3e1b12d1d01dc29056b7badc051ffc034297658
[ "MIT" ]
null
null
null
""" Low-level interface to clibffi """ from pypy.interpreter.mixedmodule import MixedModule from pypy.module._rawffi.interp_rawffi import W_CDLL from pypy.rpython.lltypesystem import lltype, rffi from pypy.module._rawffi.tracker import Tracker import sys class Module(MixedModule): interpleveldefs = { 'CDLL' : 'interp_rawffi.W_CDLL', 'FuncPtr' : 'interp_rawffi.W_FuncPtr', 'Structure' : 'structure.W_Structure', 'StructureInstance' : 'structure.W_StructureInstance', 'StructureInstanceAutoFree' : 'structure.W_StructureInstanceAutoFree', 'Array' : 'array.W_Array', 'ArrayInstance' : 'array.W_ArrayInstance', 'ArrayInstanceAutoFree' : 'array.W_ArrayInstanceAutoFree', 'sizeof' : 'interp_rawffi.sizeof', 'alignment' : 'interp_rawffi.alignment', 'charp2string' : 'interp_rawffi.charp2string', 'wcharp2unicode' : 'interp_rawffi.wcharp2unicode', 'charp2rawstring' : 'interp_rawffi.charp2rawstring', 'wcharp2rawunicode' : 'interp_rawffi.wcharp2rawunicode', 'CallbackPtr' : 'callback.W_CallbackPtr', '_num_of_allocated_objects' : 'tracker.num_of_allocated_objects', 'get_libc' : 'interp_rawffi.get_libc', 'get_errno' : 'interp_rawffi.get_errno', 'set_errno' : 'interp_rawffi.set_errno', 'SegfaultException' : 'space.new_exception_class("_rawffi.SegfaultException")', } if sys.platform == 'win32': interpleveldefs['get_last_error'] = 'interp_rawffi.get_last_error' interpleveldefs['set_last_error'] = 'interp_rawffi.set_last_error' appleveldefs = { } def buildloaders(cls): from pypy.module._rawffi import interp_rawffi if hasattr(interp_rawffi, 'FormatError'): Module.interpleveldefs['FormatError'] = 'interp_rawffi.FormatError' if hasattr(interp_rawffi, 'check_HRESULT'): Module.interpleveldefs['check_HRESULT'] = 'interp_rawffi.check_HRESULT' from pypy.rlib import clibffi for name in ['FUNCFLAG_STDCALL', 'FUNCFLAG_CDECL', 'FUNCFLAG_PYTHONAPI', 'FUNCFLAG_USE_ERRNO', 'FUNCFLAG_USE_LASTERROR', ]: if hasattr(clibffi, name): Module.interpleveldefs[name] = "space.wrap(%r)" % getattr(clibffi, name) super(Module, cls).buildloaders() buildloaders = classmethod(buildloaders)
42.733333
88
0.640796
from pypy.interpreter.mixedmodule import MixedModule from pypy.module._rawffi.interp_rawffi import W_CDLL from pypy.rpython.lltypesystem import lltype, rffi from pypy.module._rawffi.tracker import Tracker import sys class Module(MixedModule): interpleveldefs = { 'CDLL' : 'interp_rawffi.W_CDLL', 'FuncPtr' : 'interp_rawffi.W_FuncPtr', 'Structure' : 'structure.W_Structure', 'StructureInstance' : 'structure.W_StructureInstance', 'StructureInstanceAutoFree' : 'structure.W_StructureInstanceAutoFree', 'Array' : 'array.W_Array', 'ArrayInstance' : 'array.W_ArrayInstance', 'ArrayInstanceAutoFree' : 'array.W_ArrayInstanceAutoFree', 'sizeof' : 'interp_rawffi.sizeof', 'alignment' : 'interp_rawffi.alignment', 'charp2string' : 'interp_rawffi.charp2string', 'wcharp2unicode' : 'interp_rawffi.wcharp2unicode', 'charp2rawstring' : 'interp_rawffi.charp2rawstring', 'wcharp2rawunicode' : 'interp_rawffi.wcharp2rawunicode', 'CallbackPtr' : 'callback.W_CallbackPtr', '_num_of_allocated_objects' : 'tracker.num_of_allocated_objects', 'get_libc' : 'interp_rawffi.get_libc', 'get_errno' : 'interp_rawffi.get_errno', 'set_errno' : 'interp_rawffi.set_errno', 'SegfaultException' : 'space.new_exception_class("_rawffi.SegfaultException")', } if sys.platform == 'win32': interpleveldefs['get_last_error'] = 'interp_rawffi.get_last_error' interpleveldefs['set_last_error'] = 'interp_rawffi.set_last_error' appleveldefs = { } def buildloaders(cls): from pypy.module._rawffi import interp_rawffi if hasattr(interp_rawffi, 'FormatError'): Module.interpleveldefs['FormatError'] = 'interp_rawffi.FormatError' if hasattr(interp_rawffi, 'check_HRESULT'): Module.interpleveldefs['check_HRESULT'] = 'interp_rawffi.check_HRESULT' from pypy.rlib import clibffi for name in ['FUNCFLAG_STDCALL', 'FUNCFLAG_CDECL', 'FUNCFLAG_PYTHONAPI', 'FUNCFLAG_USE_ERRNO', 'FUNCFLAG_USE_LASTERROR', ]: if hasattr(clibffi, name): Module.interpleveldefs[name] = "space.wrap(%r)" % getattr(clibffi, name) super(Module, cls).buildloaders() buildloaders = classmethod(buildloaders)
true
true
f7fe703f6f2db29de7ef8d07447547769508e6c1
8,759
py
Python
official/vision/beta/projects/simclr/heads/simclr_head.py
1ucky40nc3/models
1933222e454f0d2ab8582e48fcc46f26c36ace87
[ "Apache-2.0" ]
1
2021-05-22T12:50:50.000Z
2021-05-22T12:50:50.000Z
official/vision/beta/projects/simclr/heads/simclr_head.py
DemonDamon/mask-detection-based-on-tf2odapi
192ae544169c1230c21141c033800aa1bd94e9b6
[ "MIT" ]
null
null
null
official/vision/beta/projects/simclr/heads/simclr_head.py
DemonDamon/mask-detection-based-on-tf2odapi
192ae544169c1230c21141c033800aa1bd94e9b6
[ "MIT" ]
null
null
null
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Dense prediction heads.""" from typing import Text, Optional import tensorflow as tf from official.vision.beta.projects.simclr.modeling.layers import nn_blocks regularizers = tf.keras.regularizers layers = tf.keras.layers @tf.keras.utils.register_keras_serializable(package='simclr') class ProjectionHead(tf.keras.layers.Layer): """Projection head.""" def __init__( self, num_proj_layers: int = 3, proj_output_dim: Optional[int] = None, ft_proj_idx: int = 0, kernel_initializer: Text = 'VarianceScaling', kernel_regularizer: Optional[regularizers.Regularizer] = None, bias_regularizer: Optional[regularizers.Regularizer] = None, use_sync_bn: bool = False, norm_momentum: float = 0.99, norm_epsilon: float = 0.001, **kwargs): """The projection head used during pretraining of SimCLR. Args: num_proj_layers: `int` number of Dense layers used. proj_output_dim: `int` output dimension of projection head, i.e., output dimension of the final layer. ft_proj_idx: `int` index of layer to use during fine-tuning. 0 means no projection head during fine tuning, -1 means the final layer. kernel_initializer: kernel_initializer for convolutional layers. kernel_regularizer: tf.keras.regularizers.Regularizer object for Conv2D. Default to None. bias_regularizer: tf.keras.regularizers.Regularizer object for Conv2d. Default to None. use_sync_bn: if True, use synchronized batch normalization. norm_momentum: `float` normalization omentum for the moving average. norm_epsilon: `float` small float added to variance to avoid dividing by zero. **kwargs: keyword arguments to be passed. """ super(ProjectionHead, self).__init__(**kwargs) assert proj_output_dim is not None or num_proj_layers == 0 assert ft_proj_idx <= num_proj_layers, (num_proj_layers, ft_proj_idx) self._proj_output_dim = proj_output_dim self._num_proj_layers = num_proj_layers self._ft_proj_idx = ft_proj_idx self._kernel_initializer = kernel_initializer self._kernel_regularizer = kernel_regularizer self._bias_regularizer = bias_regularizer self._use_sync_bn = use_sync_bn self._norm_momentum = norm_momentum self._norm_epsilon = norm_epsilon self._layers = [] def get_config(self): config = { 'proj_output_dim': self._proj_output_dim, 'num_proj_layers': self._num_proj_layers, 'ft_proj_idx': self._ft_proj_idx, 'kernel_initializer': self._kernel_initializer, 'kernel_regularizer': self._kernel_regularizer, 'bias_regularizer': self._bias_regularizer, 'use_normalization': self._use_normalization, 'norm_momentum': self._norm_momentum, 'norm_epsilon': self._norm_epsilon } base_config = super(ProjectionHead, self).get_config() return dict(list(base_config.items()) + list(config.items())) def build(self, input_shape): self._layers = [] if self._num_proj_layers > 0: intermediate_dim = int(input_shape[-1]) for j in range(self._num_proj_layers): if j != self._num_proj_layers - 1: # for the middle layers, use bias and relu for the output. layer = nn_blocks.DenseBN( output_dim=intermediate_dim, use_bias=True, use_normalization=True, activation='relu', kernel_initializer=self._kernel_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer, use_sync_bn=self._use_sync_bn, norm_momentum=self._norm_momentum, norm_epsilon=self._norm_epsilon, name='nl_%d' % j) else: # for the final layer, neither bias nor relu is used. layer = nn_blocks.DenseBN( output_dim=self._proj_output_dim, use_bias=False, use_normalization=True, activation=None, kernel_regularizer=self._kernel_regularizer, kernel_initializer=self._kernel_initializer, use_sync_bn=self._use_sync_bn, norm_momentum=self._norm_momentum, norm_epsilon=self._norm_epsilon, name='nl_%d' % j) self._layers.append(layer) super(ProjectionHead, self).build(input_shape) def call(self, inputs, training=None): hiddens_list = [tf.identity(inputs, 'proj_head_input')] if self._num_proj_layers == 0: proj_head_output = inputs proj_finetune_output = inputs else: for j in range(self._num_proj_layers): hiddens = self._layers[j](hiddens_list[-1], training) hiddens_list.append(hiddens) proj_head_output = tf.identity( hiddens_list[-1], 'proj_head_output') proj_finetune_output = tf.identity( hiddens_list[self._ft_proj_idx], 'proj_finetune_output') # The first element is the output of the projection head. # The second element is the input of the finetune head. return proj_head_output, proj_finetune_output @tf.keras.utils.register_keras_serializable(package='simclr') class ClassificationHead(tf.keras.layers.Layer): """Classification Head.""" def __init__( self, num_classes: int, kernel_initializer: Text = 'random_uniform', kernel_regularizer: Optional[regularizers.Regularizer] = None, bias_regularizer: Optional[regularizers.Regularizer] = None, name: Text = 'head_supervised', **kwargs): """The classification head used during pretraining or fine tuning. Args: num_classes: `int` size of the output dimension or number of classes for classification task. kernel_initializer: kernel_initializer for convolutional layers. kernel_regularizer: tf.keras.regularizers.Regularizer object for Conv2D. Default to None. bias_regularizer: tf.keras.regularizers.Regularizer object for Conv2d. Default to None. name: `str`, name of the layer. **kwargs: keyword arguments to be passed. """ super(ClassificationHead, self).__init__(name=name, **kwargs) self._num_classes = num_classes self._kernel_initializer = kernel_initializer self._kernel_regularizer = kernel_regularizer self._bias_regularizer = bias_regularizer self._name = name def get_config(self): config = { 'num_classes': self._num_classes, 'kernel_initializer': self._kernel_initializer, 'kernel_regularizer': self._kernel_regularizer, 'bias_regularizer': self._bias_regularizer, } base_config = super(ClassificationHead, self).get_config() return dict(list(base_config.items()) + list(config.items())) def build(self, input_shape): self._dense0 = layers.Dense( units=self._num_classes, kernel_initializer=self._kernel_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer, activation=None) super(ClassificationHead, self).build(input_shape) def call(self, inputs, training=None): inputs = self._dense0(inputs) return inputs
40.550926
81
0.67816
from typing import Text, Optional import tensorflow as tf from official.vision.beta.projects.simclr.modeling.layers import nn_blocks regularizers = tf.keras.regularizers layers = tf.keras.layers @tf.keras.utils.register_keras_serializable(package='simclr') class ProjectionHead(tf.keras.layers.Layer): def __init__( self, num_proj_layers: int = 3, proj_output_dim: Optional[int] = None, ft_proj_idx: int = 0, kernel_initializer: Text = 'VarianceScaling', kernel_regularizer: Optional[regularizers.Regularizer] = None, bias_regularizer: Optional[regularizers.Regularizer] = None, use_sync_bn: bool = False, norm_momentum: float = 0.99, norm_epsilon: float = 0.001, **kwargs): super(ProjectionHead, self).__init__(**kwargs) assert proj_output_dim is not None or num_proj_layers == 0 assert ft_proj_idx <= num_proj_layers, (num_proj_layers, ft_proj_idx) self._proj_output_dim = proj_output_dim self._num_proj_layers = num_proj_layers self._ft_proj_idx = ft_proj_idx self._kernel_initializer = kernel_initializer self._kernel_regularizer = kernel_regularizer self._bias_regularizer = bias_regularizer self._use_sync_bn = use_sync_bn self._norm_momentum = norm_momentum self._norm_epsilon = norm_epsilon self._layers = [] def get_config(self): config = { 'proj_output_dim': self._proj_output_dim, 'num_proj_layers': self._num_proj_layers, 'ft_proj_idx': self._ft_proj_idx, 'kernel_initializer': self._kernel_initializer, 'kernel_regularizer': self._kernel_regularizer, 'bias_regularizer': self._bias_regularizer, 'use_normalization': self._use_normalization, 'norm_momentum': self._norm_momentum, 'norm_epsilon': self._norm_epsilon } base_config = super(ProjectionHead, self).get_config() return dict(list(base_config.items()) + list(config.items())) def build(self, input_shape): self._layers = [] if self._num_proj_layers > 0: intermediate_dim = int(input_shape[-1]) for j in range(self._num_proj_layers): if j != self._num_proj_layers - 1: layer = nn_blocks.DenseBN( output_dim=intermediate_dim, use_bias=True, use_normalization=True, activation='relu', kernel_initializer=self._kernel_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer, use_sync_bn=self._use_sync_bn, norm_momentum=self._norm_momentum, norm_epsilon=self._norm_epsilon, name='nl_%d' % j) else: layer = nn_blocks.DenseBN( output_dim=self._proj_output_dim, use_bias=False, use_normalization=True, activation=None, kernel_regularizer=self._kernel_regularizer, kernel_initializer=self._kernel_initializer, use_sync_bn=self._use_sync_bn, norm_momentum=self._norm_momentum, norm_epsilon=self._norm_epsilon, name='nl_%d' % j) self._layers.append(layer) super(ProjectionHead, self).build(input_shape) def call(self, inputs, training=None): hiddens_list = [tf.identity(inputs, 'proj_head_input')] if self._num_proj_layers == 0: proj_head_output = inputs proj_finetune_output = inputs else: for j in range(self._num_proj_layers): hiddens = self._layers[j](hiddens_list[-1], training) hiddens_list.append(hiddens) proj_head_output = tf.identity( hiddens_list[-1], 'proj_head_output') proj_finetune_output = tf.identity( hiddens_list[self._ft_proj_idx], 'proj_finetune_output') return proj_head_output, proj_finetune_output @tf.keras.utils.register_keras_serializable(package='simclr') class ClassificationHead(tf.keras.layers.Layer): def __init__( self, num_classes: int, kernel_initializer: Text = 'random_uniform', kernel_regularizer: Optional[regularizers.Regularizer] = None, bias_regularizer: Optional[regularizers.Regularizer] = None, name: Text = 'head_supervised', **kwargs): super(ClassificationHead, self).__init__(name=name, **kwargs) self._num_classes = num_classes self._kernel_initializer = kernel_initializer self._kernel_regularizer = kernel_regularizer self._bias_regularizer = bias_regularizer self._name = name def get_config(self): config = { 'num_classes': self._num_classes, 'kernel_initializer': self._kernel_initializer, 'kernel_regularizer': self._kernel_regularizer, 'bias_regularizer': self._bias_regularizer, } base_config = super(ClassificationHead, self).get_config() return dict(list(base_config.items()) + list(config.items())) def build(self, input_shape): self._dense0 = layers.Dense( units=self._num_classes, kernel_initializer=self._kernel_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer, activation=None) super(ClassificationHead, self).build(input_shape) def call(self, inputs, training=None): inputs = self._dense0(inputs) return inputs
true
true
f7fe706cc3d2b9e764a5ada9585376ae6d90e939
692
py
Python
post/admin.py
Neknu/news-site
39606e099f742312bc203262bb9cc17b6c8a998d
[ "Apache-2.0" ]
null
null
null
post/admin.py
Neknu/news-site
39606e099f742312bc203262bb9cc17b6c8a998d
[ "Apache-2.0" ]
5
2021-03-19T10:51:15.000Z
2021-06-10T20:12:59.000Z
post/admin.py
danylott/news-site
39606e099f742312bc203262bb9cc17b6c8a998d
[ "Apache-2.0" ]
null
null
null
from django.contrib import admin from .models import Post @admin.register(Post) class PostAdmin(admin.ModelAdmin): # prepopulated_fields = {'slug': ('title',)} list_display = ['title', 'author', 'status', 'created'] fieldsets = [ ('User content', {'fields': ['title', 'content', 'author']}), ('Admin info', {'fields': ['status', 'slug', 'created']}), ] readonly_fields = ['created', 'slug'] search_fields = ['title', 'content'] list_filter = ['status', 'created', 'author'] ordering = ('created',) admin.site.site_header = "News Site Admin" admin.site.site_title = "Portal to post your news here" admin.site.index_title = "News Site Admin"
31.454545
69
0.634393
from django.contrib import admin from .models import Post @admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ['title', 'author', 'status', 'created'] fieldsets = [ ('User content', {'fields': ['title', 'content', 'author']}), ('Admin info', {'fields': ['status', 'slug', 'created']}), ] readonly_fields = ['created', 'slug'] search_fields = ['title', 'content'] list_filter = ['status', 'created', 'author'] ordering = ('created',) admin.site.site_header = "News Site Admin" admin.site.site_title = "Portal to post your news here" admin.site.index_title = "News Site Admin"
true
true
f7fe70976e3c341cbe527d9e7563942cd20a1582
83
py
Python
ChangeCoordinate/__init__.py
GaryLea/ChangeCoordinate
5a2a94270b9b3eff59163b5bf32e1d2c4c5cd7a6
[ "MIT" ]
10
2019-07-17T06:41:49.000Z
2021-11-24T01:17:07.000Z
ChangeCoordinate/__init__.py
GaryLea/ChangeCoordinate
5a2a94270b9b3eff59163b5bf32e1d2c4c5cd7a6
[ "MIT" ]
null
null
null
ChangeCoordinate/__init__.py
GaryLea/ChangeCoordinate
5a2a94270b9b3eff59163b5bf32e1d2c4c5cd7a6
[ "MIT" ]
7
2019-09-21T11:56:31.000Z
2021-12-10T06:47:38.000Z
# -*- coding: utf-8 -*- from ChangeCoordinate.change_coordinate import ChangeCoord
27.666667
58
0.771084
from ChangeCoordinate.change_coordinate import ChangeCoord
true
true
f7fe739bf4e1a8a8f56b8db57b3c8fdf1d39edf3
14,911
py
Python
flexget/tests/conftest.py
astrotee/Flexget
34121f79eaef2ce27dd2d37b6d1c2e8dfbf98c51
[ "MIT" ]
1,322
2015-01-01T22:00:25.000Z
2022-03-30T05:37:46.000Z
flexget/tests/conftest.py
astrotee/Flexget
34121f79eaef2ce27dd2d37b6d1c2e8dfbf98c51
[ "MIT" ]
2,384
2015-01-01T04:23:15.000Z
2022-03-31T01:06:43.000Z
flexget/tests/conftest.py
soloam/Flexget
f39812981d9ab2665358d8285c7ea7758759ab8d
[ "MIT" ]
617
2015-01-02T15:15:07.000Z
2022-03-15T12:29:31.000Z
import itertools import logging import os import re import shutil import sys from contextlib import contextmanager from http import client from pathlib import Path from typing import Any, Callable, Dict, List, Optional from unittest import mock import flask import jsonschema import pytest import requests import yaml from _pytest.logging import caplog as _caplog from loguru import logger from vcr import VCR from vcr.stubs import VCRHTTPConnection, VCRHTTPSConnection import flexget.log from flexget import plugin from flexget.api import api_app from flexget.event import event from flexget.manager import Manager, Session from flexget.plugin import load_plugins from flexget.task import Task, TaskAbort from flexget.webserver import User logger = logger.bind(name='tests') VCR_CASSETTE_DIR = os.path.join(os.path.dirname(__file__), 'cassettes') VCR_RECORD_MODE = os.environ.get('VCR_RECORD_MODE', 'once') vcr = VCR( cassette_library_dir=VCR_CASSETTE_DIR, record_mode=VCR_RECORD_MODE, custom_patches=( (client, 'HTTPSConnection', VCRHTTPSConnection), (client, 'HTTPConnection', VCRHTTPConnection), ), ) # --- These are the public fixtures tests can ask for --- @pytest.fixture(scope='class') def config(request): """ If used inside a test class, uses the `config` class attribute of the class. This is used by `manager` fixture, and can be parametrized. """ return request.cls.config @pytest.fixture() def manager( request, config, caplog, monkeypatch, filecopy ): # enforce filecopy is run before manager """ Create a :class:`MockManager` for this test based on `config` argument. """ if 'tmpdir' in request.fixturenames: config = config.replace('__tmp__', request.getfixturevalue('tmpdir').strpath) try: mockmanager = MockManager(config, request.cls.__name__) except Exception: # Since we haven't entered the test function yet, pytest won't print the logs on failure. Print them manually. print(caplog.text) raise yield mockmanager mockmanager.shutdown() @pytest.fixture() def execute_task(manager: Manager) -> Callable[..., Task]: """ A function that can be used to execute and return a named task in `config` argument. """ def execute(task_name: str, abort: bool = False, options: bool = None) -> Task: """ Use to execute one test task from config. :param abort: If `True` expect (and require) this task to abort. """ logger.info('********** Running task: {} ********** ', task_name) config = manager.config['tasks'][task_name] task = Task(manager, task_name, config=config, options=options) try: if abort: with pytest.raises(TaskAbort): task.execute() else: task.execute() finally: try: task.session.close() except Exception: pass return task return execute @pytest.fixture() def use_vcr(request, monkeypatch): """ This fixture is applied automatically to any test using the `online` mark. It will record and playback network sessions using VCR. The record mode of VCR can be set using the VCR_RECORD_MODE environment variable when running tests. """ if VCR_RECORD_MODE == 'off': yield None else: module = request.module.__name__.split('tests.')[-1] class_name = request.cls.__name__ cassette_name = '.'.join([module, class_name, request.function.__name__]) cassette_path = os.path.join(VCR_CASSETTE_DIR, cassette_name) online = True if vcr.record_mode == 'none': online = False elif vcr.record_mode == 'once': online = not os.path.exists(cassette_path) # If we are not going online, disable domain limiting during test if not online: logger.debug('Disabling domain limiters during VCR playback.') monkeypatch.setattr('flexget.utils.requests.limit_domains', mock.Mock()) with vcr.use_cassette(path=cassette_path) as cassette: yield cassette @pytest.fixture() def api_client(manager) -> 'APIClient': with Session() as session: user = session.query(User).first() if not user: user = User(name='flexget', password='flexget') session.add(user) session.commit() return APIClient(user.token) @pytest.fixture() def schema_match(manager) -> Callable[[dict, Any], List[dict]]: """ This fixture enables verifying JSON Schema. Return a list of validation error dicts. List is empty if no errors occurred. """ def match(schema: dict, response: Any) -> List[dict]: validator = jsonschema.Draft4Validator(schema) errors = list(validator.iter_errors(response)) return [dict(value=list(e.path), message=e.message) for e in errors] return match @pytest.fixture() def link_headers(manager) -> Callable[[flask.Response], Dict[str, dict]]: """ Parses link headers and return them in dict form """ def headers(response: flask.Response) -> Dict[str, dict]: links = {} for link in requests.utils.parse_header_links(response.headers.get('link')): url = link['url'] page = int(re.search(r'(?<!per_)page=(\d)', url).group(1)) links[link['rel']] = dict(url=url, page=page) return links return headers @pytest.fixture(autouse=True) def caplog(pytestconfig, _caplog): """ Override caplog so that we can send loguru messages to logging for compatibility. """ # set logging level according to pytest verbosity level = logger.level('DEBUG') if pytestconfig.getoption('verbose') == 1: level = logger.level('TRACE') elif pytestconfig.getoption('quiet', None) == 1: level = logger.level('INFO') class PropagateHandler(logging.Handler): def emit(self, record): logging.getLogger(record.name).handle(record) handler_id = logger.add(PropagateHandler(), level=level.no, format="{message}", catch=False) _caplog.set_level(level.no) yield _caplog logger.remove(handler_id) # --- End Public Fixtures --- def pytest_configure(config): # register the filecopy marker config.addinivalue_line( 'markers', 'filecopy(src, dst): mark test to copy a file from `src` to `dst` before running.', ) config.addinivalue_line( 'markers', 'online: mark a test that goes online. VCR will automatically be used.' ) def pytest_runtest_setup(item): # Add the filcopy fixture to any test marked with filecopy if item.get_closest_marker('filecopy'): item.fixturenames.append('filecopy') # Add the online marker to tests that will go online if item.get_closest_marker('online'): item.fixturenames.append('use_vcr') else: item.fixturenames.append('no_requests') @pytest.fixture() def filecopy(request): out_files = [] for marker in request.node.iter_markers('filecopy'): copy_list = marker.args[0] if len(marker.args) == 1 else [marker.args] for sources, dst in copy_list: if isinstance(sources, str): sources = [sources] if 'tmpdir' in request.fixturenames: dst = dst.replace('__tmp__', request.getfixturevalue('tmpdir').strpath) dst = Path(dst) for f in itertools.chain(*(Path().glob(src) for src in sources)): dest_path = dst if dest_path.is_dir(): dest_path = dest_path / f.name logger.debug('copying {} to {}', f, dest_path) if not os.path.isdir(os.path.dirname(dest_path)): os.makedirs(os.path.dirname(dest_path)) if os.path.isdir(f): shutil.copytree(f, dest_path) else: shutil.copy(f, dest_path) out_files.append(dest_path) yield if out_files: for f in out_files: try: if os.path.isdir(f): shutil.rmtree(f) else: f.unlink() except OSError as e: print("couldn't remove %s: %s" % (f, e)) @pytest.fixture() def no_requests(monkeypatch): online_funcs = ['requests.sessions.Session.request', 'http.client.HTTPConnection.request'] # Don't monkey patch HTTPSConnection if ssl not installed as it won't exist in backports try: import ssl # noqa from ssl import SSLContext # noqa online_funcs.append('http.client.HTTPSConnection.request') except ImportError: pass online_funcs.extend( ['http.client.HTTPConnection.request', 'http.client.HTTPSConnection.request'] ) for func in online_funcs: monkeypatch.setattr( func, mock.Mock(side_effect=Exception('Online tests should use @pytest.mark.online')) ) @pytest.fixture(scope='session', autouse=True) def setup_once(pytestconfig, request): # os.chdir(os.path.join(pytestconfig.rootdir.strpath, 'flexget', 'tests')) flexget.log.initialize(True) m = MockManager( 'tasks: {}', 'init' ) # This makes sure our template environment is set up before any tests are run m.shutdown() logging.getLogger().setLevel(logging.DEBUG) load_plugins() @pytest.fixture(autouse=True) def chdir(pytestconfig, request): """ By marking test with chdir flag we will change current working directory to that module location. Task configuration can then assume this being location for relative paths """ if 'chdir' in request.fixturenames: os.chdir(os.path.dirname(request.module.__file__)) @pytest.fixture(autouse=True) def clear_caches(): """Make sure cached_input, and other caches are cleared between tests.""" from flexget.utils.tools import TimedDict TimedDict.clear_all() class CrashReport(Exception): def __init__(self, message: str, crash_log: str): self.message = message self.crash_log = crash_log class MockManager(Manager): unit_test = True def __init__(self, config_text: str, config_name: str, db_uri: Optional[str] = None): self.config_text = config_text self._db_uri = db_uri or 'sqlite:///:memory:' super().__init__(['execute']) self.config_name = config_name self.database_uri = self._db_uri logger.debug('database_uri: {}', self.database_uri) self.initialize() def _init_config(self, *args, **kwargs): """ Override configuration loading """ self.config_base = os.path.dirname(os.path.abspath(sys.path[0])) def load_config(self, *args, **kwargs): """ Just load our config from the text passed in on init """ config = yaml.safe_load(self.config_text) or {} self.update_config(config) @property def conn(self): return self.engine.connect() # no lock files with unit testing @contextmanager def acquire_lock(self, **kwargs): self._has_lock = True yield def release_lock(self): pass def crash_report(self): # We don't want to silently swallow crash reports during unit tests logger.opt(exception=True).error('Crash Report Traceback:') raise CrashReport( 'Crash report created during unit test, check log for traceback.', flexget.log.debug_buffer, ) def shutdown(self, finish_queue=True): super().shutdown(finish_queue=finish_queue) self._shutdown() # Perhaps this bit should go somewhere else... The way reruns work can be complicated, and was causing issues in # some cases. This plugin should run on all tests in the suite, to make sure certain phases aren't getting # called twice. https://github.com/Flexget/Flexget/issues/3254 class DoublePhaseChecker: @staticmethod def on_phase(task, phase): if getattr(task, f'did_{phase}', None): raise Exception(f'{phase} phase should not run twice') setattr(task, f'did_{phase}', True) def on_task_start(self, task, config): self.on_phase(task, 'start') def on_task_prepare(self, task, config): self.on_phase(task, 'prepare') def on_task_exit(self, task, config): self.on_phase(task, 'exit') @event('plugin.register') def register_plugin(): plugin.register(DoublePhaseChecker, 'test_dobule_phase', api_ver=2, debug=True, builtin=True) class APIClient: def __init__(self, api_key: str) -> None: self.api_key = api_key self.client = api_app.test_client() def _append_header(self, key, value, kwargs): if 'headers' not in kwargs: kwargs['headers'] = {} kwargs['headers'][key] = value def json_post(self, *args, **kwargs) -> flask.Response: self._append_header('Content-Type', 'application/json', kwargs) if kwargs.get('auth', True): self._append_header('Authorization', 'Token %s' % self.api_key, kwargs) return self.client.post(*args, **kwargs) def json_put(self, *args, **kwargs) -> flask.Response: self._append_header('Content-Type', 'application/json', kwargs) if kwargs.get('auth', True): self._append_header('Authorization', 'Token %s' % self.api_key, kwargs) return self.client.put(*args, **kwargs) def json_patch(self, *args, **kwargs) -> flask.Response: self._append_header('Content-Type', 'application/json', kwargs) if kwargs.get('auth', True): self._append_header('Authorization', 'Token %s' % self.api_key, kwargs) return self.client.patch(*args, **kwargs) def get(self, *args, **kwargs) -> flask.Response: if kwargs.get('auth', True): self._append_header('Authorization', 'Token %s' % self.api_key, kwargs) return self.client.get(*args, **kwargs) def delete(self, *args, **kwargs) -> flask.Response: if kwargs.get('auth', True): self._append_header('Authorization', 'Token %s' % self.api_key, kwargs) return self.client.delete(*args, **kwargs) def json_delete(self, *args, **kwargs) -> flask.Response: self._append_header('Content-Type', 'application/json', kwargs) if kwargs.get('auth', True): self._append_header('Authorization', 'Token %s' % self.api_key, kwargs) return self.client.delete(*args, **kwargs) def head(self, *args, **kwargs) -> flask.Response: if kwargs.get('auth', True): self._append_header('Authorization', 'Token %s' % self.api_key, kwargs) return self.client.head(*args, **kwargs)
32.988938
118
0.64382
import itertools import logging import os import re import shutil import sys from contextlib import contextmanager from http import client from pathlib import Path from typing import Any, Callable, Dict, List, Optional from unittest import mock import flask import jsonschema import pytest import requests import yaml from _pytest.logging import caplog as _caplog from loguru import logger from vcr import VCR from vcr.stubs import VCRHTTPConnection, VCRHTTPSConnection import flexget.log from flexget import plugin from flexget.api import api_app from flexget.event import event from flexget.manager import Manager, Session from flexget.plugin import load_plugins from flexget.task import Task, TaskAbort from flexget.webserver import User logger = logger.bind(name='tests') VCR_CASSETTE_DIR = os.path.join(os.path.dirname(__file__), 'cassettes') VCR_RECORD_MODE = os.environ.get('VCR_RECORD_MODE', 'once') vcr = VCR( cassette_library_dir=VCR_CASSETTE_DIR, record_mode=VCR_RECORD_MODE, custom_patches=( (client, 'HTTPSConnection', VCRHTTPSConnection), (client, 'HTTPConnection', VCRHTTPConnection), ), ) @pytest.fixture(scope='class') def config(request): return request.cls.config @pytest.fixture() def manager( request, config, caplog, monkeypatch, filecopy ): if 'tmpdir' in request.fixturenames: config = config.replace('__tmp__', request.getfixturevalue('tmpdir').strpath) try: mockmanager = MockManager(config, request.cls.__name__) except Exception: print(caplog.text) raise yield mockmanager mockmanager.shutdown() @pytest.fixture() def execute_task(manager: Manager) -> Callable[..., Task]: def execute(task_name: str, abort: bool = False, options: bool = None) -> Task: logger.info('********** Running task: {} ********** ', task_name) config = manager.config['tasks'][task_name] task = Task(manager, task_name, config=config, options=options) try: if abort: with pytest.raises(TaskAbort): task.execute() else: task.execute() finally: try: task.session.close() except Exception: pass return task return execute @pytest.fixture() def use_vcr(request, monkeypatch): if VCR_RECORD_MODE == 'off': yield None else: module = request.module.__name__.split('tests.')[-1] class_name = request.cls.__name__ cassette_name = '.'.join([module, class_name, request.function.__name__]) cassette_path = os.path.join(VCR_CASSETTE_DIR, cassette_name) online = True if vcr.record_mode == 'none': online = False elif vcr.record_mode == 'once': online = not os.path.exists(cassette_path) if not online: logger.debug('Disabling domain limiters during VCR playback.') monkeypatch.setattr('flexget.utils.requests.limit_domains', mock.Mock()) with vcr.use_cassette(path=cassette_path) as cassette: yield cassette @pytest.fixture() def api_client(manager) -> 'APIClient': with Session() as session: user = session.query(User).first() if not user: user = User(name='flexget', password='flexget') session.add(user) session.commit() return APIClient(user.token) @pytest.fixture() def schema_match(manager) -> Callable[[dict, Any], List[dict]]: def match(schema: dict, response: Any) -> List[dict]: validator = jsonschema.Draft4Validator(schema) errors = list(validator.iter_errors(response)) return [dict(value=list(e.path), message=e.message) for e in errors] return match @pytest.fixture() def link_headers(manager) -> Callable[[flask.Response], Dict[str, dict]]: def headers(response: flask.Response) -> Dict[str, dict]: links = {} for link in requests.utils.parse_header_links(response.headers.get('link')): url = link['url'] page = int(re.search(r'(?<!per_)page=(\d)', url).group(1)) links[link['rel']] = dict(url=url, page=page) return links return headers @pytest.fixture(autouse=True) def caplog(pytestconfig, _caplog): level = logger.level('DEBUG') if pytestconfig.getoption('verbose') == 1: level = logger.level('TRACE') elif pytestconfig.getoption('quiet', None) == 1: level = logger.level('INFO') class PropagateHandler(logging.Handler): def emit(self, record): logging.getLogger(record.name).handle(record) handler_id = logger.add(PropagateHandler(), level=level.no, format="{message}", catch=False) _caplog.set_level(level.no) yield _caplog logger.remove(handler_id) def pytest_configure(config): config.addinivalue_line( 'markers', 'filecopy(src, dst): mark test to copy a file from `src` to `dst` before running.', ) config.addinivalue_line( 'markers', 'online: mark a test that goes online. VCR will automatically be used.' ) def pytest_runtest_setup(item): if item.get_closest_marker('filecopy'): item.fixturenames.append('filecopy') if item.get_closest_marker('online'): item.fixturenames.append('use_vcr') else: item.fixturenames.append('no_requests') @pytest.fixture() def filecopy(request): out_files = [] for marker in request.node.iter_markers('filecopy'): copy_list = marker.args[0] if len(marker.args) == 1 else [marker.args] for sources, dst in copy_list: if isinstance(sources, str): sources = [sources] if 'tmpdir' in request.fixturenames: dst = dst.replace('__tmp__', request.getfixturevalue('tmpdir').strpath) dst = Path(dst) for f in itertools.chain(*(Path().glob(src) for src in sources)): dest_path = dst if dest_path.is_dir(): dest_path = dest_path / f.name logger.debug('copying {} to {}', f, dest_path) if not os.path.isdir(os.path.dirname(dest_path)): os.makedirs(os.path.dirname(dest_path)) if os.path.isdir(f): shutil.copytree(f, dest_path) else: shutil.copy(f, dest_path) out_files.append(dest_path) yield if out_files: for f in out_files: try: if os.path.isdir(f): shutil.rmtree(f) else: f.unlink() except OSError as e: print("couldn't remove %s: %s" % (f, e)) @pytest.fixture() def no_requests(monkeypatch): online_funcs = ['requests.sessions.Session.request', 'http.client.HTTPConnection.request'] # Don't monkey patch HTTPSConnection if ssl not installed as it won't exist in backports try: import ssl # noqa from ssl import SSLContext # noqa online_funcs.append('http.client.HTTPSConnection.request') except ImportError: pass online_funcs.extend( ['http.client.HTTPConnection.request', 'http.client.HTTPSConnection.request'] ) for func in online_funcs: monkeypatch.setattr( func, mock.Mock(side_effect=Exception('Online tests should use @pytest.mark.online')) ) @pytest.fixture(scope='session', autouse=True) def setup_once(pytestconfig, request): # os.chdir(os.path.join(pytestconfig.rootdir.strpath, 'flexget', 'tests')) flexget.log.initialize(True) m = MockManager( 'tasks: {}', 'init' ) # This makes sure our template environment is set up before any tests are run m.shutdown() logging.getLogger().setLevel(logging.DEBUG) load_plugins() @pytest.fixture(autouse=True) def chdir(pytestconfig, request): if 'chdir' in request.fixturenames: os.chdir(os.path.dirname(request.module.__file__)) @pytest.fixture(autouse=True) def clear_caches(): from flexget.utils.tools import TimedDict TimedDict.clear_all() class CrashReport(Exception): def __init__(self, message: str, crash_log: str): self.message = message self.crash_log = crash_log class MockManager(Manager): unit_test = True def __init__(self, config_text: str, config_name: str, db_uri: Optional[str] = None): self.config_text = config_text self._db_uri = db_uri or 'sqlite:///:memory:' super().__init__(['execute']) self.config_name = config_name self.database_uri = self._db_uri logger.debug('database_uri: {}', self.database_uri) self.initialize() def _init_config(self, *args, **kwargs): self.config_base = os.path.dirname(os.path.abspath(sys.path[0])) def load_config(self, *args, **kwargs): config = yaml.safe_load(self.config_text) or {} self.update_config(config) @property def conn(self): return self.engine.connect() # no lock files with unit testing @contextmanager def acquire_lock(self, **kwargs): self._has_lock = True yield def release_lock(self): pass def crash_report(self): # We don't want to silently swallow crash reports during unit tests logger.opt(exception=True).error('Crash Report Traceback:') raise CrashReport( 'Crash report created during unit test, check log for traceback.', flexget.log.debug_buffer, ) def shutdown(self, finish_queue=True): super().shutdown(finish_queue=finish_queue) self._shutdown() # called twice. https://github.com/Flexget/Flexget/issues/3254 class DoublePhaseChecker: @staticmethod def on_phase(task, phase): if getattr(task, f'did_{phase}', None): raise Exception(f'{phase} phase should not run twice') setattr(task, f'did_{phase}', True) def on_task_start(self, task, config): self.on_phase(task, 'start') def on_task_prepare(self, task, config): self.on_phase(task, 'prepare') def on_task_exit(self, task, config): self.on_phase(task, 'exit') @event('plugin.register') def register_plugin(): plugin.register(DoublePhaseChecker, 'test_dobule_phase', api_ver=2, debug=True, builtin=True) class APIClient: def __init__(self, api_key: str) -> None: self.api_key = api_key self.client = api_app.test_client() def _append_header(self, key, value, kwargs): if 'headers' not in kwargs: kwargs['headers'] = {} kwargs['headers'][key] = value def json_post(self, *args, **kwargs) -> flask.Response: self._append_header('Content-Type', 'application/json', kwargs) if kwargs.get('auth', True): self._append_header('Authorization', 'Token %s' % self.api_key, kwargs) return self.client.post(*args, **kwargs) def json_put(self, *args, **kwargs) -> flask.Response: self._append_header('Content-Type', 'application/json', kwargs) if kwargs.get('auth', True): self._append_header('Authorization', 'Token %s' % self.api_key, kwargs) return self.client.put(*args, **kwargs) def json_patch(self, *args, **kwargs) -> flask.Response: self._append_header('Content-Type', 'application/json', kwargs) if kwargs.get('auth', True): self._append_header('Authorization', 'Token %s' % self.api_key, kwargs) return self.client.patch(*args, **kwargs) def get(self, *args, **kwargs) -> flask.Response: if kwargs.get('auth', True): self._append_header('Authorization', 'Token %s' % self.api_key, kwargs) return self.client.get(*args, **kwargs) def delete(self, *args, **kwargs) -> flask.Response: if kwargs.get('auth', True): self._append_header('Authorization', 'Token %s' % self.api_key, kwargs) return self.client.delete(*args, **kwargs) def json_delete(self, *args, **kwargs) -> flask.Response: self._append_header('Content-Type', 'application/json', kwargs) if kwargs.get('auth', True): self._append_header('Authorization', 'Token %s' % self.api_key, kwargs) return self.client.delete(*args, **kwargs) def head(self, *args, **kwargs) -> flask.Response: if kwargs.get('auth', True): self._append_header('Authorization', 'Token %s' % self.api_key, kwargs) return self.client.head(*args, **kwargs)
true
true
f7fe7452ae0237857a9b68aa5dbd9cc51bd907e4
3,984
py
Python
Image/download.py
c11/earthengine-py-notebooks
144b57e4d952da095ba73c3cc8ce2f36291162ff
[ "MIT" ]
1
2020-05-31T14:19:59.000Z
2020-05-31T14:19:59.000Z
Image/download.py
c11/earthengine-py-notebooks
144b57e4d952da095ba73c3cc8ce2f36291162ff
[ "MIT" ]
null
null
null
Image/download.py
c11/earthengine-py-notebooks
144b57e4d952da095ba73c3cc8ce2f36291162ff
[ "MIT" ]
null
null
null
# %% """ <table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Image/download.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a target="_blank" href="https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/Image/download.ipynb"><img width=26px src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png" />Notebook Viewer</a></td> <td><a target="_blank" href="https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/Image/download.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a></td> </table> """ # %% """ ## Install Earth Engine API and geemap Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://github.com/giswqs/geemap). The **geemap** Python package is built upon the [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet) and [folium](https://github.com/python-visualization/folium) packages and implements several methods for interacting with Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, and `Map.centerObject()`. The following script checks if the geemap package has been installed. If not, it will install geemap, which automatically installs its [dependencies](https://github.com/giswqs/geemap#dependencies), including earthengine-api, folium, and ipyleaflet. **Important note**: A key difference between folium and ipyleaflet is that ipyleaflet is built upon ipywidgets and allows bidirectional communication between the front-end and the backend enabling the use of the map to capture user input, while folium is meant for displaying static data only ([source](https://blog.jupyter.org/interactive-gis-in-jupyter-with-ipyleaflet-52f9657fa7a)). Note that [Google Colab](https://colab.research.google.com/) currently does not support ipyleaflet ([source](https://github.com/googlecolab/colabtools/issues/60#issuecomment-596225619)). Therefore, if you are using geemap with Google Colab, you should use [`import geemap.eefolium`](https://github.com/giswqs/geemap/blob/master/geemap/eefolium.py). If you are using geemap with [binder](https://mybinder.org/) or a local Jupyter notebook server, you can use [`import geemap`](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py), which provides more functionalities for capturing user input (e.g., mouse-clicking and moving). """ # %% # Installs geemap package import subprocess try: import geemap except ImportError: print('geemap package not installed. Installing ...') subprocess.check_call(["python", '-m', 'pip', 'install', 'geemap']) # Checks whether this notebook is running on Google Colab try: import google.colab import geemap.eefolium as emap except: import geemap as emap # Authenticates and initializes Earth Engine import ee try: ee.Initialize() except Exception as e: ee.Authenticate() ee.Initialize() # %% """ ## Create an interactive map The default basemap is `Google Satellite`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py#L13) can be added using the `Map.add_basemap()` function. """ # %% Map = emap.Map(center=[40,-100], zoom=4) Map.add_basemap('ROADMAP') # Add Google Map Map # %% """ ## Add Earth Engine Python script """ # %% # Add Earth Engine dataset # Get a download URL for an image. image1 = ee.Image('srtm90_v4') path = image1.getDownloadUrl({ 'scale': 30, 'crs': 'EPSG:4326', 'region': '[[-120, 35], [-119, 35], [-119, 34], [-120, 34]]' }) print(path) vis_params = {'min': 0, 'max': 3000} Map.addLayer(image1, vis_params) # %% """ ## Display Earth Engine data layers """ # %% Map.addLayerControl() # This line is not needed for ipyleaflet-based Map. Map
48
1,021
0.735944
import subprocess try: import geemap except ImportError: print('geemap package not installed. Installing ...') subprocess.check_call(["python", '-m', 'pip', 'install', 'geemap']) try: import google.colab import geemap.eefolium as emap except: import geemap as emap import ee try: ee.Initialize() except Exception as e: ee.Authenticate() ee.Initialize() Map = emap.Map(center=[40,-100], zoom=4) Map.add_basemap('ROADMAP') Map image1 = ee.Image('srtm90_v4') path = image1.getDownloadUrl({ 'scale': 30, 'crs': 'EPSG:4326', 'region': '[[-120, 35], [-119, 35], [-119, 34], [-120, 34]]' }) print(path) vis_params = {'min': 0, 'max': 3000} Map.addLayer(image1, vis_params) Map.addLayerControl() Map
true
true
f7fe74a15292c234d13cbd919f84484b57430357
580
py
Python
molecule/common/tests/test_pacemaker.py
incubateur-pe/pacemaker
4b4bd65be4f87ba147a4a5a0739c0689e6ec5671
[ "BSD-3-Clause" ]
null
null
null
molecule/common/tests/test_pacemaker.py
incubateur-pe/pacemaker
4b4bd65be4f87ba147a4a5a0739c0689e6ec5671
[ "BSD-3-Clause" ]
null
null
null
molecule/common/tests/test_pacemaker.py
incubateur-pe/pacemaker
4b4bd65be4f87ba147a4a5a0739c0689e6ec5671
[ "BSD-3-Clause" ]
null
null
null
"""Role testing files using testinfra.""" import pytest @pytest.mark.parametrize("name", [ "pcsd", "corosync", "pacemaker" ]) def test_cluster_services(host, name): service = host.service(name) # assert service.is_valid assert service.is_enabled assert service.is_running def test_cluster_status(host): cmd = host.run("pcs status") assert "2 nodes configured" in cmd.stdout assert "Online: [ vm-1 vm-2 ]" in cmd.stdout def test_resource_listening(host): socket = host.socket('tcp://0.0.0.0:8080') assert socket.is_listening
20
48
0.684483
import pytest @pytest.mark.parametrize("name", [ "pcsd", "corosync", "pacemaker" ]) def test_cluster_services(host, name): service = host.service(name) assert service.is_enabled assert service.is_running def test_cluster_status(host): cmd = host.run("pcs status") assert "2 nodes configured" in cmd.stdout assert "Online: [ vm-1 vm-2 ]" in cmd.stdout def test_resource_listening(host): socket = host.socket('tcp://0.0.0.0:8080') assert socket.is_listening
true
true
f7fe75f8e1e49e4cb85cb1a2e452d03481eb2601
6,044
py
Python
BouncingBall014.py
BrianDunneKK/BouncingBall
bd491e4615b86c16179c7aac6c5e348ff85122b8
[ "MIT" ]
null
null
null
BouncingBall014.py
BrianDunneKK/BouncingBall
bd491e4615b86c16179c7aac6c5e348ff85122b8
[ "MIT" ]
null
null
null
BouncingBall014.py
BrianDunneKK/BouncingBall
bd491e4615b86c16179c7aac6c5e348ff85122b8
[ "MIT" ]
null
null
null
import cdkk import pygame import random # -------------------------------------------------- class Sprite_Ball(cdkk.Sprite): files = ["ball_red.png", "ball_yellow.png", "ball_green.png", "ball_brown.png", "ball_blue.png", "ball_pink.png", "ball_black.png"] def __init__(self, value, limits): super().__init__() self.load_image_from_file(self.files[value - 1]) self.rect.left = random.randint(limits.width * 0.2, limits.width * 0.8) self.rect.top = 10 speed = value * 3 + 5 angle = random.randint(45, 135) self.rect.set_speed_angle(speed, angle) self.rect.bounce_cor = self.rect.perfect_bounce bounce_event = cdkk.EventManager.gc_event( "Boundary", ball_id=self.uuid) self.rect.add_limit(cdkk.Physics_Limit( limits, cdkk.LIMIT_KEEP_INSIDE, cdkk.AT_LIMIT_BOUNCE, bounce_event)) self.rect.go() def update(self): super().update() self.rect.move_physics() # -------------------------------------------------- class Manager_Ball(cdkk.SpriteManager): def __init__(self, limits, total, at_a_time): super().__init__("Ball Manager") self._limits = limits self._at_a_time = at_a_time self._total = total self.balls_left = total self.add_balls() def add_balls(self): current_balls = len(self.sprites()) new_balls = self._at_a_time - current_balls if new_balls > self.balls_left: new_balls = self.balls_left for i in range(new_balls): value = random.randint(1, len(Sprite_Ball.files)) ball = Sprite_Ball(value, self._limits) self.add(ball) self.balls_left -= 1 def event(self, e): dealt_with = super().event(e) if not dealt_with and e.type == cdkk.EVENT_GAME_CONTROL: if e.action == "Boundary": if e.at_limit_y & cdkk.AT_LIMIT_BOTTOM: self.kill_uuid(e.info["ball_id"]) self.add_balls() return dealt_with def check_bat_hits(self, bat): for ball in self.sprites(): ball.rect.dynamic_limit(cdkk.Physics_Limit( bat.rect, cdkk.LIMIT_KEEP_OUTSIDE, cdkk.AT_LIMIT_Y_BOUNCE_Y)) # -------------------------------------------------- class Sprite_Bat(cdkk.Sprite): def __init__(self, limits): super().__init__("Bat") self.load_image_from_file("bat.png") self.rect.centerx = limits.width / 2 self.rect.top = limits.height * 0.9 self.rect.add_limit(cdkk.Physics_Limit( limits, cdkk.LIMIT_KEEP_INSIDE, cdkk.AT_LIMIT_X_HOLD_POS_X)) # -------------------------------------------------- class Manager_Bat(cdkk.SpriteManager): def __init__(self, limits, name="Bat Manager"): super().__init__(name) self._bat = Sprite_Bat(limits) self.add(self._bat) def event(self, e): dealt_with = False if e.type == cdkk.EVENT_GAME_CONTROL: if e.action == "MouseMotion": x, y = e.info["pos"] self._bat.rect.move_to(x, None) dealt_with = True return dealt_with # -------------------------------------------------- class Manager_Scoreboard(cdkk.SpriteManager): def __init__(self, limits, game_time): super().__init__("Scoreboard Manager") self._game_time = game_time text_style = {"fillcolour": None, "outlinecolour": None, "align_horiz": "L", "width": 200, "height": 35} tb_score = cdkk.Sprite_TextBox("Score", style=text_style) tb_score.set_text_format("Score: {0}", 0) tb_score.rect.midleft = (limits.width * 0.1, limits.height * 0.05) self.add(tb_score) self.score = 0 self._timer = cdkk.Timer(self._game_time, cdkk.EVENT_GAME_TIMER_1) tb_time_left = cdkk.Sprite_TextBox("Time Left", style=text_style) tb_time_left.set_text_format("Time Left: {0:0.1f}", 0) tb_time_left.rect.center = (limits.width * 0.45, limits.height * 0.05) self.add(tb_time_left) tb_balls_left = cdkk.Sprite_TextBox("Balls Left", style=text_style) tb_balls_left.set_text_format("Balls Left: {0}", 0) tb_balls_left.rect.midright = ( limits.width * 0.85, limits.height * 0.05) self.add(tb_balls_left) self.balls_left = 0 @property def score(self): return self._score @score.setter def score(self, new_score): self._score = new_score self.sprite("Score").set_text(self.score) @property def balls_left(self): return self._balls_left @balls_left.setter def balls_left(self, new_balls_left): self._balls_left = new_balls_left self.sprite("Balls Left").set_text(self.balls_left) def update(self): super().update() self.sprite("Time Left").set_text(self._timer.time_left) # -------------------------------------------------- class MyGame(cdkk.PyGameApp): def init(self): super().init() self._ball_mgr = Manager_Ball(self.boundary, 10, 3) self.add_sprite_mgr(self._ball_mgr) self._bat_mgr = Manager_Bat(self.boundary) self.add_sprite_mgr(self._bat_mgr) self._scoreboard_mgr = Manager_Scoreboard(self.boundary, 15) self.add_sprite_mgr(self._scoreboard_mgr) key_map = { pygame.K_q: "Quit", pygame.K_s: "StartGame" } self.event_mgr.event_map(key_event_map=key_map) def update(self): super().update() bat = self.sprite("Bat Manager", "Bat") self._ball_mgr.check_bat_hits(bat) self._scoreboard_mgr.balls_left = self._ball_mgr.balls_left app_config = { "width": 1200, "height": 920, "background_fill": "burlywood", "caption": "Bouncing Ball", "image_path": "BouncingBall\\Images\\", "auto_start": False, } MyGame(app_config).execute()
32.320856
83
0.587359
import cdkk import pygame import random class Sprite_Ball(cdkk.Sprite): files = ["ball_red.png", "ball_yellow.png", "ball_green.png", "ball_brown.png", "ball_blue.png", "ball_pink.png", "ball_black.png"] def __init__(self, value, limits): super().__init__() self.load_image_from_file(self.files[value - 1]) self.rect.left = random.randint(limits.width * 0.2, limits.width * 0.8) self.rect.top = 10 speed = value * 3 + 5 angle = random.randint(45, 135) self.rect.set_speed_angle(speed, angle) self.rect.bounce_cor = self.rect.perfect_bounce bounce_event = cdkk.EventManager.gc_event( "Boundary", ball_id=self.uuid) self.rect.add_limit(cdkk.Physics_Limit( limits, cdkk.LIMIT_KEEP_INSIDE, cdkk.AT_LIMIT_BOUNCE, bounce_event)) self.rect.go() def update(self): super().update() self.rect.move_physics() class Manager_Ball(cdkk.SpriteManager): def __init__(self, limits, total, at_a_time): super().__init__("Ball Manager") self._limits = limits self._at_a_time = at_a_time self._total = total self.balls_left = total self.add_balls() def add_balls(self): current_balls = len(self.sprites()) new_balls = self._at_a_time - current_balls if new_balls > self.balls_left: new_balls = self.balls_left for i in range(new_balls): value = random.randint(1, len(Sprite_Ball.files)) ball = Sprite_Ball(value, self._limits) self.add(ball) self.balls_left -= 1 def event(self, e): dealt_with = super().event(e) if not dealt_with and e.type == cdkk.EVENT_GAME_CONTROL: if e.action == "Boundary": if e.at_limit_y & cdkk.AT_LIMIT_BOTTOM: self.kill_uuid(e.info["ball_id"]) self.add_balls() return dealt_with def check_bat_hits(self, bat): for ball in self.sprites(): ball.rect.dynamic_limit(cdkk.Physics_Limit( bat.rect, cdkk.LIMIT_KEEP_OUTSIDE, cdkk.AT_LIMIT_Y_BOUNCE_Y)) class Sprite_Bat(cdkk.Sprite): def __init__(self, limits): super().__init__("Bat") self.load_image_from_file("bat.png") self.rect.centerx = limits.width / 2 self.rect.top = limits.height * 0.9 self.rect.add_limit(cdkk.Physics_Limit( limits, cdkk.LIMIT_KEEP_INSIDE, cdkk.AT_LIMIT_X_HOLD_POS_X)) class Manager_Bat(cdkk.SpriteManager): def __init__(self, limits, name="Bat Manager"): super().__init__(name) self._bat = Sprite_Bat(limits) self.add(self._bat) def event(self, e): dealt_with = False if e.type == cdkk.EVENT_GAME_CONTROL: if e.action == "MouseMotion": x, y = e.info["pos"] self._bat.rect.move_to(x, None) dealt_with = True return dealt_with class Manager_Scoreboard(cdkk.SpriteManager): def __init__(self, limits, game_time): super().__init__("Scoreboard Manager") self._game_time = game_time text_style = {"fillcolour": None, "outlinecolour": None, "align_horiz": "L", "width": 200, "height": 35} tb_score = cdkk.Sprite_TextBox("Score", style=text_style) tb_score.set_text_format("Score: {0}", 0) tb_score.rect.midleft = (limits.width * 0.1, limits.height * 0.05) self.add(tb_score) self.score = 0 self._timer = cdkk.Timer(self._game_time, cdkk.EVENT_GAME_TIMER_1) tb_time_left = cdkk.Sprite_TextBox("Time Left", style=text_style) tb_time_left.set_text_format("Time Left: {0:0.1f}", 0) tb_time_left.rect.center = (limits.width * 0.45, limits.height * 0.05) self.add(tb_time_left) tb_balls_left = cdkk.Sprite_TextBox("Balls Left", style=text_style) tb_balls_left.set_text_format("Balls Left: {0}", 0) tb_balls_left.rect.midright = ( limits.width * 0.85, limits.height * 0.05) self.add(tb_balls_left) self.balls_left = 0 @property def score(self): return self._score @score.setter def score(self, new_score): self._score = new_score self.sprite("Score").set_text(self.score) @property def balls_left(self): return self._balls_left @balls_left.setter def balls_left(self, new_balls_left): self._balls_left = new_balls_left self.sprite("Balls Left").set_text(self.balls_left) def update(self): super().update() self.sprite("Time Left").set_text(self._timer.time_left) class MyGame(cdkk.PyGameApp): def init(self): super().init() self._ball_mgr = Manager_Ball(self.boundary, 10, 3) self.add_sprite_mgr(self._ball_mgr) self._bat_mgr = Manager_Bat(self.boundary) self.add_sprite_mgr(self._bat_mgr) self._scoreboard_mgr = Manager_Scoreboard(self.boundary, 15) self.add_sprite_mgr(self._scoreboard_mgr) key_map = { pygame.K_q: "Quit", pygame.K_s: "StartGame" } self.event_mgr.event_map(key_event_map=key_map) def update(self): super().update() bat = self.sprite("Bat Manager", "Bat") self._ball_mgr.check_bat_hits(bat) self._scoreboard_mgr.balls_left = self._ball_mgr.balls_left app_config = { "width": 1200, "height": 920, "background_fill": "burlywood", "caption": "Bouncing Ball", "image_path": "BouncingBall\\Images\\", "auto_start": False, } MyGame(app_config).execute()
true
true
f7fe760bdb51e989ee04ce549c78f9ce71ef5afe
2,976
py
Python
examples/config/settings.py
oliver-zhou/django-templated-mail
bcadd81e414aa53ba27dd42030bb85896688dc09
[ "MIT" ]
89
2017-09-19T10:04:51.000Z
2022-02-10T08:29:40.000Z
examples/config/settings.py
oliver-zhou/django-templated-mail
bcadd81e414aa53ba27dd42030bb85896688dc09
[ "MIT" ]
21
2018-01-02T12:21:18.000Z
2022-02-23T11:50:08.000Z
examples/config/settings.py
oliver-zhou/django-templated-mail
bcadd81e414aa53ba27dd42030bb85896688dc09
[ "MIT" ]
18
2018-01-17T11:01:31.000Z
2021-12-17T03:39:36.000Z
import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '()!xq2ufm%j@n^!v^p08&w87vvg)rk^=aoj8u1(4xho5iuh-)l' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'templated_mail', 'simple', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'config.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'config.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.' 'UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.' 'MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.' 'CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.' 'NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/'
25.220339
79
0.672379
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '()!xq2ufm%j@n^!v^p08&w87vvg)rk^=aoj8u1(4xho5iuh-)l' DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'templated_mail', 'simple', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'config.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'config.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.' 'UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.' 'MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.' 'CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.' 'NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/'
true
true
f7fe76988824699de105fb6240a54558dbfcb8b2
3,931
py
Python
tests/modules/test_macho.py
CLEAR-seclab/viper
58189220119a85c7a660f160cc664822de2c8412
[ "BSD-3-Clause" ]
2
2015-12-17T20:25:09.000Z
2017-10-08T19:14:57.000Z
tests/modules/test_macho.py
detrojones/viper
045e0952552fe29bb5e9780568486b36fd12e9ab
[ "BSD-3-Clause" ]
1
2015-01-05T18:07:13.000Z
2015-01-07T21:43:57.000Z
tests/modules/test_macho.py
detrojones/viper
045e0952552fe29bb5e9780568486b36fd12e9ab
[ "BSD-3-Clause" ]
3
2017-10-18T00:56:53.000Z
2020-05-24T09:38:54.000Z
# -*- coding: utf-8 -*- # This file is part of Viper - https://github.com/viper-framework/viper # See the file 'LICENSE' for copying permission. import os import re import pytest from tests.conftest import FIXTURE_DIR from viper.modules.macho import Macho, HAVE_MACHO from viper.common.abstracts import Module from viper.common.abstracts import ArgumentErrorCallback from viper.core.session import __sessions__ class TestMacho: def teardown_method(self): __sessions__.close() def test_init(self): instance = Macho() assert isinstance(instance, Macho) assert isinstance(instance, Module) def test_have_macho(self): assert HAVE_MACHO is True def test_args_exception(self): instance = Macho() with pytest.raises(ArgumentErrorCallback) as excinfo: instance.parser.parse_args(["-h"]) excinfo.match(r".*Get Macho OSX Headers.*") @pytest.mark.usefixtures("cleandir") def test_no_session(self, capsys): instance = Macho() instance.command_line = ["-a"] instance.run() out, err = capsys.readouterr() assert re.search(r".*No open session.*", out) @pytest.mark.parametrize("filename", ["whoami.exe"]) def test_no_macho_file(self, capsys, filename): __sessions__.new(os.path.join(FIXTURE_DIR, filename)) instance = Macho() instance.command_line = ["-hd"] instance.run() out, err = capsys.readouterr() lines = out.split("\n") assert re.search(r".*Not a Mach-O file.*", lines[1]) @pytest.mark.parametrize("filename", ["MachO-OSX-x86-ls"]) def test_no_argument(self, capsys, filename): __sessions__.new(os.path.join(FIXTURE_DIR, filename)) instance = Macho() instance.run() out, err = capsys.readouterr() lines = out.split("\n") assert re.search(r".*Session opened on.*", lines[0]) @pytest.mark.parametrize("filename,magic,cputype", [ ("MachO-OSX-x86-ls", "0xfeedface - 32 bits", "0x7 - i386"), ("MachO-OSX-x64-ls", "0xfeedfacf - 64 bits", "0x1000007 - x86_64") ]) def test_headers(self, capsys, filename, magic, cputype): __sessions__.new(os.path.join(FIXTURE_DIR, filename)) instance = Macho() instance.command_line = ["-hd"] instance.run() out, err = capsys.readouterr() lines = out.split("\n") assert re.search(r".*Headers", lines[1]) assert re.search(r".*{}.*".format(magic), out) assert re.search(r".*{}.*".format(cputype), out) @pytest.mark.parametrize("filename,amount_segments", [ ("MachO-OSX-x86-ls", 4) ]) def test_segments(self, capsys, filename, amount_segments): __sessions__.new(os.path.join(FIXTURE_DIR, filename)) instance = Macho() instance.command_line = ["-sg"] instance.run() out, err = capsys.readouterr() lines = out.split("\n") assert re.search(r".*Segments \({}\)".format(amount_segments), lines[1]) @pytest.mark.parametrize("filename,amount_commands", [ ("MachO-OSX-x86-ls", 12), ]) def test_load_commands(self, capsys, filename, amount_commands): __sessions__.new(os.path.join(FIXTURE_DIR, filename)) instance = Macho() instance.command_line = ["-lc"] instance.run() out, err = capsys.readouterr() lines = out.split("\n") assert re.search(r".*Load Commands \({}\)".format(amount_commands), lines[1]) @pytest.mark.parametrize("filename", ["MachO-OSX-x86-ls"]) def test_all(self, capsys, filename): __sessions__.new(os.path.join(FIXTURE_DIR, filename)) instance = Macho() instance.command_line = ["-a"] instance.run() out, err = capsys.readouterr() lines = out.split("\n") assert re.search(r".*Headers", lines[1])
31.198413
85
0.622488
import os import re import pytest from tests.conftest import FIXTURE_DIR from viper.modules.macho import Macho, HAVE_MACHO from viper.common.abstracts import Module from viper.common.abstracts import ArgumentErrorCallback from viper.core.session import __sessions__ class TestMacho: def teardown_method(self): __sessions__.close() def test_init(self): instance = Macho() assert isinstance(instance, Macho) assert isinstance(instance, Module) def test_have_macho(self): assert HAVE_MACHO is True def test_args_exception(self): instance = Macho() with pytest.raises(ArgumentErrorCallback) as excinfo: instance.parser.parse_args(["-h"]) excinfo.match(r".*Get Macho OSX Headers.*") @pytest.mark.usefixtures("cleandir") def test_no_session(self, capsys): instance = Macho() instance.command_line = ["-a"] instance.run() out, err = capsys.readouterr() assert re.search(r".*No open session.*", out) @pytest.mark.parametrize("filename", ["whoami.exe"]) def test_no_macho_file(self, capsys, filename): __sessions__.new(os.path.join(FIXTURE_DIR, filename)) instance = Macho() instance.command_line = ["-hd"] instance.run() out, err = capsys.readouterr() lines = out.split("\n") assert re.search(r".*Not a Mach-O file.*", lines[1]) @pytest.mark.parametrize("filename", ["MachO-OSX-x86-ls"]) def test_no_argument(self, capsys, filename): __sessions__.new(os.path.join(FIXTURE_DIR, filename)) instance = Macho() instance.run() out, err = capsys.readouterr() lines = out.split("\n") assert re.search(r".*Session opened on.*", lines[0]) @pytest.mark.parametrize("filename,magic,cputype", [ ("MachO-OSX-x86-ls", "0xfeedface - 32 bits", "0x7 - i386"), ("MachO-OSX-x64-ls", "0xfeedfacf - 64 bits", "0x1000007 - x86_64") ]) def test_headers(self, capsys, filename, magic, cputype): __sessions__.new(os.path.join(FIXTURE_DIR, filename)) instance = Macho() instance.command_line = ["-hd"] instance.run() out, err = capsys.readouterr() lines = out.split("\n") assert re.search(r".*Headers", lines[1]) assert re.search(r".*{}.*".format(magic), out) assert re.search(r".*{}.*".format(cputype), out) @pytest.mark.parametrize("filename,amount_segments", [ ("MachO-OSX-x86-ls", 4) ]) def test_segments(self, capsys, filename, amount_segments): __sessions__.new(os.path.join(FIXTURE_DIR, filename)) instance = Macho() instance.command_line = ["-sg"] instance.run() out, err = capsys.readouterr() lines = out.split("\n") assert re.search(r".*Segments \({}\)".format(amount_segments), lines[1]) @pytest.mark.parametrize("filename,amount_commands", [ ("MachO-OSX-x86-ls", 12), ]) def test_load_commands(self, capsys, filename, amount_commands): __sessions__.new(os.path.join(FIXTURE_DIR, filename)) instance = Macho() instance.command_line = ["-lc"] instance.run() out, err = capsys.readouterr() lines = out.split("\n") assert re.search(r".*Load Commands \({}\)".format(amount_commands), lines[1]) @pytest.mark.parametrize("filename", ["MachO-OSX-x86-ls"]) def test_all(self, capsys, filename): __sessions__.new(os.path.join(FIXTURE_DIR, filename)) instance = Macho() instance.command_line = ["-a"] instance.run() out, err = capsys.readouterr() lines = out.split("\n") assert re.search(r".*Headers", lines[1])
true
true
f7fe76ab269b44c25fcc74c3b8d338ad3b600d39
4,439
py
Python
stateoftheuniverse/widgets/constellations.py
Pratere/stateoftheuniverse
2ad341cb9f0a45b8a624ba23a2dc3224e03de455
[ "MIT" ]
null
null
null
stateoftheuniverse/widgets/constellations.py
Pratere/stateoftheuniverse
2ad341cb9f0a45b8a624ba23a2dc3224e03de455
[ "MIT" ]
null
null
null
stateoftheuniverse/widgets/constellations.py
Pratere/stateoftheuniverse
2ad341cb9f0a45b8a624ba23a2dc3224e03de455
[ "MIT" ]
null
null
null
""" Get a list of constellations that will be visible from a location on the earth as a given time. """ # ------------------------- # Imports # ------------------------ from astropy.utils.exceptions import AstropyDeprecationWarning import warnings from datetime import datetime as dt from astropy import units as u from astropy.coordinates import SkyCoord, AltAz, get_constellation, EarthLocation from astropy.time import Time import numpy as np from typing import Optional from stateoftheuniverse.widgets.prototypes import WidgetPrototype from stateoftheuniverse.widgets.utils import stringdecorator warnings.filterwarnings('ignore', category=AstropyDeprecationWarning) # ------------------------- # Function Definitions # ------------------------ class ConstellationsWidget(WidgetPrototype): """ A widget that collects and holds list of constellations which will be in the sky at the users location at midnight Args: longitude: the longitude of the user latitude: the latitude of the user datetime: a datetime.datetime object in UTC """ def __init__(self, longitude: Optional[float] = None, latitude: Optional[float] = None, datetime: Optional[dt] = None): super().__init__(longitude=longitude, latitude=latitude, datetime=datetime) self.height = 1500 self.location = EarthLocation.from_geodetic(lon=self.longitude * u.degree, lat=self.latitude * u.degree, height=self.height * u.meter) if self.datetime is None: self.datetime = dt.now() self.datetime = str(self.datetime)[:10] + ' 23:00:00' self.time = Time(self.datetime) else: self.time = Time(str(self.datetime)[:10]+' 23:00:00') self.alt, self.az = np.meshgrid(np.arange(5, 85, 5), np.arange(5, 355, 5)) self.alt = self.alt.ravel() self.az = self.az.ravel() self.dome = SkyCoord(az=self.az * u.degree, alt=self.alt * u.degree, frame=AltAz(obstime=self.time, location=self.location)) self.constellations = None self.name = "TONIGHT'S CONSTELLATIONS" self.dict_name = "consts" def get_data(self): """ Update and store list of tonight's constellations, based on the users location. Uses a matrix of points on the sky to retrieve constellations that they are located in. """ self.constellations = list(set(get_constellation(self.dome))) self.constellations.sort() return self.constellations @stringdecorator def get_string(self): """ Return formatted output string of visible constellations. """ if self.constellations is None: self.get_data() string = '\n\t'.join(self.constellations) return string def check_const(self, const_check): """ Return bool or list of bools for if a given constellation will be in visible on data. """ if self.constellations is None: self.get_data() if type(const_check) == str: if const_check.lower() in [constellation.lower() for constellation in self.constellations]: return f"{const_check} will be visible tonight." else: return f"{const_check} will not be visible tonight." elif type(const_check) == list: avail_consts = [] for const in const_check: if const.lower() in [constellation.lower() for constellation in self.constellations]: avail_consts.append(f"{const} will be visible tonight.") else: avail_consts.append(f"{const} will not be visible tonight.") return avail_consts else: print("Function takes string or list of stings") return False if __name__ == "__main__": const = ConstellationsWidget(longitude=52.2053, latitude=0.1218) print(const.get_string()) for constellation in const.constellations: if not const.check_const(str(constellation)): print("Failed to find " + constellation) print(const.check_const(const.constellations))
35.230159
103
0.601487
from astropy.utils.exceptions import AstropyDeprecationWarning import warnings from datetime import datetime as dt from astropy import units as u from astropy.coordinates import SkyCoord, AltAz, get_constellation, EarthLocation from astropy.time import Time import numpy as np from typing import Optional from stateoftheuniverse.widgets.prototypes import WidgetPrototype from stateoftheuniverse.widgets.utils import stringdecorator warnings.filterwarnings('ignore', category=AstropyDeprecationWarning) class ConstellationsWidget(WidgetPrototype): def __init__(self, longitude: Optional[float] = None, latitude: Optional[float] = None, datetime: Optional[dt] = None): super().__init__(longitude=longitude, latitude=latitude, datetime=datetime) self.height = 1500 self.location = EarthLocation.from_geodetic(lon=self.longitude * u.degree, lat=self.latitude * u.degree, height=self.height * u.meter) if self.datetime is None: self.datetime = dt.now() self.datetime = str(self.datetime)[:10] + ' 23:00:00' self.time = Time(self.datetime) else: self.time = Time(str(self.datetime)[:10]+' 23:00:00') self.alt, self.az = np.meshgrid(np.arange(5, 85, 5), np.arange(5, 355, 5)) self.alt = self.alt.ravel() self.az = self.az.ravel() self.dome = SkyCoord(az=self.az * u.degree, alt=self.alt * u.degree, frame=AltAz(obstime=self.time, location=self.location)) self.constellations = None self.name = "TONIGHT'S CONSTELLATIONS" self.dict_name = "consts" def get_data(self): self.constellations = list(set(get_constellation(self.dome))) self.constellations.sort() return self.constellations @stringdecorator def get_string(self): if self.constellations is None: self.get_data() string = '\n\t'.join(self.constellations) return string def check_const(self, const_check): if self.constellations is None: self.get_data() if type(const_check) == str: if const_check.lower() in [constellation.lower() for constellation in self.constellations]: return f"{const_check} will be visible tonight." else: return f"{const_check} will not be visible tonight." elif type(const_check) == list: avail_consts = [] for const in const_check: if const.lower() in [constellation.lower() for constellation in self.constellations]: avail_consts.append(f"{const} will be visible tonight.") else: avail_consts.append(f"{const} will not be visible tonight.") return avail_consts else: print("Function takes string or list of stings") return False if __name__ == "__main__": const = ConstellationsWidget(longitude=52.2053, latitude=0.1218) print(const.get_string()) for constellation in const.constellations: if not const.check_const(str(constellation)): print("Failed to find " + constellation) print(const.check_const(const.constellations))
true
true
f7fe7748462965c14b63197643cfb9d0ea77e413
32
py
Python
examples/python/mypackage/module.py
ech0-de/popper
58b994660c954ab267407820e30d76a739a4d2df
[ "MIT" ]
179
2016-11-19T22:38:07.000Z
2020-05-24T10:42:30.000Z
examples/python/mypackage/module.py
ech0-de/popper
58b994660c954ab267407820e30d76a739a4d2df
[ "MIT" ]
739
2016-10-05T21:31:13.000Z
2020-05-22T20:42:55.000Z
examples/python/mypackage/module.py
ech0-de/popper
58b994660c954ab267407820e30d76a739a4d2df
[ "MIT" ]
51
2016-10-14T05:42:10.000Z
2020-05-15T19:05:33.000Z
def myfunc(x): return x + 1
10.666667
16
0.5625
def myfunc(x): return x + 1
true
true
f7fe78db2738e5fc116176b624b1d6a2f4e865bb
580
py
Python
script/python3/util/__init__.py
setminami/IrControl
bcdd44b7f6aeca75226cdcfc611dc63032c38949
[ "MIT" ]
null
null
null
script/python3/util/__init__.py
setminami/IrControl
bcdd44b7f6aeca75226cdcfc611dc63032c38949
[ "MIT" ]
2
2018-09-21T11:53:28.000Z
2018-12-30T03:37:23.000Z
script/python3/util/__init__.py
setminami/IrControl
bcdd44b7f6aeca75226cdcfc611dc63032c38949
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # this made for python3 import logging, os def is_debug(sysname='Darwin'): """ for device debug """ return os.uname().sysname == sysname def module_logger(modname): logger = logging.getLogger(modname) handler = logging.StreamHandler() formatter = logging.Formatter('[%(asctime)s | %(name)s | %(levelname)s] %(message)s', datefmt='%y%m%dT%H%M%S') handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.DEBUG if is_debug() else logging.INFO) return logger
32.222222
89
0.639655
import logging, os def is_debug(sysname='Darwin'): return os.uname().sysname == sysname def module_logger(modname): logger = logging.getLogger(modname) handler = logging.StreamHandler() formatter = logging.Formatter('[%(asctime)s | %(name)s | %(levelname)s] %(message)s', datefmt='%y%m%dT%H%M%S') handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.DEBUG if is_debug() else logging.INFO) return logger
true
true
f7fe7906d343fc6cf019096931c1533d5633140d
690
py
Python
test/timing.py
plotnick/prettyprinter
edde630011ad5eada6476366a2b2da422f4a9d74
[ "MIT" ]
null
null
null
test/timing.py
plotnick/prettyprinter
edde630011ad5eada6476366a2b2da422f4a9d74
[ "MIT" ]
null
null
null
test/timing.py
plotnick/prettyprinter
edde630011ad5eada6476366a2b2da422f4a9d74
[ "MIT" ]
null
null
null
from __future__ import with_statement import timeit setup = """ import pprint import prettyprinter as pp from format import format, parse_control_string null = open("/dev/null", "w") tupler = "(~{~A,~^ ~@{~A~^, ~}~})" l = tuple(xrange(1000)) d = dict(zip(range(100), range(100, 200))) """[1:] stmts = (("parse", """tuple(parse_control_string(tupler))"""), ("format", """format(null, "~~foo: ~D pon~:@P~%", 3)"""), ("iteration", """format(null, tupler, l)"""), ("prettyprinter", """pp.pprint(l, stream=null)"""), ("pprint", """pprint.pprint(l, null)""")) for name, stmt in stmts: print ">> %s" % name timeit.main(["-s", setup, stmt]) print
28.75
66
0.573913
from __future__ import with_statement import timeit setup = """ import pprint import prettyprinter as pp from format import format, parse_control_string null = open("/dev/null", "w") tupler = "(~{~A,~^ ~@{~A~^, ~}~})" l = tuple(xrange(1000)) d = dict(zip(range(100), range(100, 200))) """[1:] stmts = (("parse", """tuple(parse_control_string(tupler))"""), ("format", """format(null, "~~foo: ~D pon~:@P~%", 3)"""), ("iteration", """format(null, tupler, l)"""), ("prettyprinter", """pp.pprint(l, stream=null)"""), ("pprint", """pprint.pprint(l, null)""")) for name, stmt in stmts: print ">> %s" % name timeit.main(["-s", setup, stmt]) print
false
true
f7fe7998d90376bfcb58386941deaf7b073ff2a4
3,812
py
Python
archive/transfer_learning_runresults2.py
marjanin/tendon_stiffness
b1dc379b09bbf9c044410a6bc51afbee0cba2e05
[ "MIT" ]
1
2020-07-20T02:04:46.000Z
2020-07-20T02:04:46.000Z
archive/transfer_learning_runresults2.py
marjanin/tendon_stiffness
b1dc379b09bbf9c044410a6bc51afbee0cba2e05
[ "MIT" ]
null
null
null
archive/transfer_learning_runresults2.py
marjanin/tendon_stiffness
b1dc379b09bbf9c044410a6bc51afbee0cba2e05
[ "MIT" ]
1
2020-05-11T11:41:39.000Z
2020-05-11T11:41:39.000Z
# next is to add accel and see the difference # add stiffness too import numpy as np from scipy import signal, stats from matplotlib import pyplot as plt from all_functions import * import pickle from warnings import simplefilter simplefilter(action='ignore', category=FutureWarning) experiment_ID = "transfer_learning_6" errors_all_A_A = np.load("./results/{}/errors_all_A_A.npy".format(experiment_ID)) errors_all_A_B = np.load("./results/{}/errors_all_A_B.npy".format(experiment_ID)) errors_all_B_B = np.load("./results/{}/errors_all_B_B.npy".format(experiment_ID)) ## printing the results print("errors_mean: ",errors_all_A_A.mean(2)) print("errors_std: ",errors_all_A_A.std(2)) print("errors_mean: ",errors_all_A_B.mean(2)) print("errors_std: ",errors_all_A_B.std(2)) print("errors_mean: ",errors_all_B_B.mean(2)) print("errors_std: ",errors_all_B_B.std(2)) [f_ow, p_val_avg] = stats.f_oneway(errors_all_A_A.mean(0)[0],errors_all_A_B.mean(0)[0]) print("p-value (babbling/average/A_A vs A_B): ", p_val_avg) [f_ow, p_val_avg] = stats.f_oneway(errors_all_A_A.mean(0)[1],errors_all_A_B.mean(0)[1]) print("p-value (refined/average/A_A vs A_B): ", p_val_avg) [f_ow, p_val_avg] = stats.f_oneway(errors_all_A_A.mean(0)[1],errors_all_B_B.mean(0)[1]) print("p-value (refined/average/A_A vs B_B): ", p_val_avg) # [f_ow, p_val_q0] = stats.f_oneway(errors_all_A_A[0,:],errors_all_A_B[0,:]) # print("p-value (q0): ", p_val_q0) # [f_ow, p_val_q1] = stats.f_oneway(errors_all_A_A[1,:],errors_all_A_B[1,:]) # print("p-value (q1): ", p_val_q1) y_lim=[0, 0.9] fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(12, 5)) p0 = axes[0][0].boxplot( [errors_all_A_A.mean(0)[0], errors_all_A_B.mean(0)[0], errors_all_B_B.mean(0)[0]], notch=True, patch_artist=True) axes[0][0].set_title(r'$(q_0+q_1)/2$',fontsize=12) axes[0][0].set_ylim(y_lim) #axes[0].set_xlabel('stiffness') axes[0][0].set_xticklabels(["A_A", "A_B", "B_B"], rotation=45, fontsize=8) axes[0][0].set_ylabel('RMSE') p1 = axes[0][1].boxplot( [errors_all_A_A[0,0,:], errors_all_A_B[0,0,:], errors_all_B_B[0,0,:]], notch=True, patch_artist=True) axes[0][1].set_title('$q_0$', fontsize=12) axes[0][1].set_ylim(y_lim) axes[0][1].set_yticklabels([]) #axes[1].set_xlabel('stiffness') axes[0][1].set_xticklabels(["A_A", "A_B", "B_B"], rotation=45, fontsize=8) p2 = axes[0][2].boxplot( [errors_all_A_A[1,0,:], errors_all_A_B[1,0,:], errors_all_B_B[1,0,:]], notch=True, patch_artist=True) axes[0][2].set_title('$q_1$', fontsize=12) axes[0][2].set_ylim(y_lim) axes[0][2].set_yticklabels([]) #axes[2].set_xlabel('stiffness') axes[0][2].set_xticklabels(["A_A", "A_B", "B_B"], rotation=45, fontsize=8) p3 = axes[1][0].boxplot( [errors_all_A_A.mean(0)[-1], errors_all_A_B.mean(0)[-1], errors_all_B_B.mean(0)[-1]], notch=True, patch_artist=True) #axes[1][0].set_title(r'$(q_0+q_1)/2$',fontsize=12) axes[1][0].set_ylim(y_lim) #axes[0].set_xlabel('stiffness') axes[1][0].set_xticklabels(["A_A", "A_B", "B_B"], rotation=45, fontsize=8) axes[1][0].set_ylabel('RMSE') p4 = axes[1][1].boxplot( [errors_all_A_A[0,-1,:], errors_all_A_B[0,-1,:], errors_all_B_B[0,-1,:]], notch=True, patch_artist=True) #axes[1][1].set_title('$q_0$', fontsize=12) axes[1][1].set_ylim(y_lim) axes[1][1].set_yticklabels([]) #axes[1].set_xlabel('stiffness') axes[1][1].set_xticklabels(["A_A","A_B", "B_B"], rotation=45, fontsize=8) p5 = axes[1][2].boxplot( [errors_all_A_A[1,-1,:], errors_all_A_B[1,-1,:], errors_all_B_B[1,-1,:]], notch=True, patch_artist=True) #axes[1][2].set_title('$q_1$', fontsize=12) axes[1][2].set_ylim(y_lim) axes[1][2].set_yticklabels([]) #axes[2].set_xlabel('stiffness') axes[1][2].set_xticklabels(["A_A","A_B","B_B"], rotation=45, fontsize=8) for i_row in range(2): for j_col in range(3): axes[i_row][j_col].grid(True) plt.show() #import pdb; pdb.set_trace()
38.505051
87
0.705142
import numpy as np from scipy import signal, stats from matplotlib import pyplot as plt from all_functions import * import pickle from warnings import simplefilter simplefilter(action='ignore', category=FutureWarning) experiment_ID = "transfer_learning_6" errors_all_A_A = np.load("./results/{}/errors_all_A_A.npy".format(experiment_ID)) errors_all_A_B = np.load("./results/{}/errors_all_A_B.npy".format(experiment_ID)) errors_all_B_B = np.load("./results/{}/errors_all_B_B.npy".format(experiment_ID)) ,errors_all_A_A.mean(2)) print("errors_std: ",errors_all_A_A.std(2)) print("errors_mean: ",errors_all_A_B.mean(2)) print("errors_std: ",errors_all_A_B.std(2)) print("errors_mean: ",errors_all_B_B.mean(2)) print("errors_std: ",errors_all_B_B.std(2)) [f_ow, p_val_avg] = stats.f_oneway(errors_all_A_A.mean(0)[0],errors_all_A_B.mean(0)[0]) print("p-value (babbling/average/A_A vs A_B): ", p_val_avg) [f_ow, p_val_avg] = stats.f_oneway(errors_all_A_A.mean(0)[1],errors_all_A_B.mean(0)[1]) print("p-value (refined/average/A_A vs A_B): ", p_val_avg) [f_ow, p_val_avg] = stats.f_oneway(errors_all_A_A.mean(0)[1],errors_all_B_B.mean(0)[1]) print("p-value (refined/average/A_A vs B_B): ", p_val_avg) y_lim=[0, 0.9] fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(12, 5)) p0 = axes[0][0].boxplot( [errors_all_A_A.mean(0)[0], errors_all_A_B.mean(0)[0], errors_all_B_B.mean(0)[0]], notch=True, patch_artist=True) axes[0][0].set_title(r'$(q_0+q_1)/2$',fontsize=12) axes[0][0].set_ylim(y_lim) axes[0][0].set_xticklabels(["A_A", "A_B", "B_B"], rotation=45, fontsize=8) axes[0][0].set_ylabel('RMSE') p1 = axes[0][1].boxplot( [errors_all_A_A[0,0,:], errors_all_A_B[0,0,:], errors_all_B_B[0,0,:]], notch=True, patch_artist=True) axes[0][1].set_title('$q_0$', fontsize=12) axes[0][1].set_ylim(y_lim) axes[0][1].set_yticklabels([]) axes[0][1].set_xticklabels(["A_A", "A_B", "B_B"], rotation=45, fontsize=8) p2 = axes[0][2].boxplot( [errors_all_A_A[1,0,:], errors_all_A_B[1,0,:], errors_all_B_B[1,0,:]], notch=True, patch_artist=True) axes[0][2].set_title('$q_1$', fontsize=12) axes[0][2].set_ylim(y_lim) axes[0][2].set_yticklabels([]) axes[0][2].set_xticklabels(["A_A", "A_B", "B_B"], rotation=45, fontsize=8) p3 = axes[1][0].boxplot( [errors_all_A_A.mean(0)[-1], errors_all_A_B.mean(0)[-1], errors_all_B_B.mean(0)[-1]], notch=True, patch_artist=True) axes[1][0].set_ylim(y_lim) axes[1][0].set_xticklabels(["A_A", "A_B", "B_B"], rotation=45, fontsize=8) axes[1][0].set_ylabel('RMSE') p4 = axes[1][1].boxplot( [errors_all_A_A[0,-1,:], errors_all_A_B[0,-1,:], errors_all_B_B[0,-1,:]], notch=True, patch_artist=True) axes[1][1].set_ylim(y_lim) axes[1][1].set_yticklabels([]) axes[1][1].set_xticklabels(["A_A","A_B", "B_B"], rotation=45, fontsize=8) p5 = axes[1][2].boxplot( [errors_all_A_A[1,-1,:], errors_all_A_B[1,-1,:], errors_all_B_B[1,-1,:]], notch=True, patch_artist=True) axes[1][2].set_ylim(y_lim) axes[1][2].set_yticklabels([]) axes[1][2].set_xticklabels(["A_A","A_B","B_B"], rotation=45, fontsize=8) for i_row in range(2): for j_col in range(3): axes[i_row][j_col].grid(True) plt.show()
true
true
f7fe79e0ea2f62e8e12d449296f3fa9492d3b1cc
11,653
py
Python
tf_agents/policies/actor_policy_test.py
ayansengupta17/agents
c5a2f1f57d4fd0070eb75204aa0b1663de3e2c0a
[ "Apache-2.0" ]
2
2021-02-02T06:56:58.000Z
2021-04-21T08:39:45.000Z
tf_agents/policies/actor_policy_test.py
MarioBonse/agents
c727141f67051b86d2564c4bd5fbc080623bfe19
[ "Apache-2.0" ]
null
null
null
tf_agents/policies/actor_policy_test.py
MarioBonse/agents
c727141f67051b86d2564c4bd5fbc080623bfe19
[ "Apache-2.0" ]
6
2020-10-09T06:33:23.000Z
2022-02-03T16:16:36.000Z
# coding=utf-8 # Copyright 2018 The TF-Agents Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for tf_agents.policies.actor_policy.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import import tensorflow_probability as tfp from tf_agents.networks import actor_distribution_network from tf_agents.networks import network from tf_agents.policies import actor_policy from tf_agents.specs import tensor_spec from tf_agents.trajectories import time_step as ts from tf_agents.utils import test_utils class DummyActionNet(network.Network): def __init__(self, input_tensor_spec, output_tensor_spec): super(DummyActionNet, self).__init__( input_tensor_spec=input_tensor_spec, state_spec=(), name='DummyActionNet') single_action_spec = tf.nest.flatten(output_tensor_spec)[0] self._output_tensor_spec = output_tensor_spec self._sub_layers = [ tf.keras.layers.Dense( single_action_spec.shape.num_elements(), activation=tf.nn.tanh, kernel_initializer=tf.compat.v1.initializers.constant([2, 1]), bias_initializer=tf.compat.v1.initializers.constant([5]), ), ] def call(self, observations, step_type, network_state): del step_type states = tf.cast(tf.nest.flatten(observations)[0], tf.float32) for layer in self._sub_layers: states = layer(states) single_action_spec = tf.nest.flatten(self._output_tensor_spec)[0] means = tf.reshape(states, [-1] + single_action_spec.shape.as_list()) spec_means = (single_action_spec.maximum + single_action_spec.minimum) / 2.0 spec_ranges = ( single_action_spec.maximum - single_action_spec.minimum) / 2.0 action_means = spec_means + spec_ranges * means return (tf.nest.pack_sequence_as(self._output_tensor_spec, [action_means]), network_state) class DummyActionDistributionNet(DummyActionNet): def call(self, observations, step_type, network_state): action_means, network_state = super(DummyActionDistributionNet, self).call( observations, step_type, network_state) def _action_distribution(action_mean): action_std = tf.ones_like(action_mean) return tfp.distributions.Normal(action_mean, action_std) return tf.nest.map_structure(_action_distribution, action_means), network_state def test_cases(): return parameterized.named_parameters({ 'testcase_name': 'SimpleNet', 'network_ctor': DummyActionNet, }, { 'testcase_name': 'DistributionNet', 'network_ctor': DummyActionDistributionNet, }) class ActorPolicyTest(parameterized.TestCase, test_utils.TestCase): def setUp(self): super(ActorPolicyTest, self).setUp() self._obs_spec = tensor_spec.TensorSpec([2], tf.float32) self._time_step_spec = ts.time_step_spec(self._obs_spec) self._action_spec = tensor_spec.BoundedTensorSpec([1], tf.float32, 2, 3) @property def _time_step(self): return ts.restart(tf.constant([1, 2], dtype=tf.float32)) @property def _time_step_batch(self): return ts.TimeStep( tf.constant( ts.StepType.FIRST, dtype=tf.int32, shape=[2], name='step_type'), tf.constant(0.0, dtype=tf.float32, shape=[2], name='reward'), tf.constant(1.0, dtype=tf.float32, shape=[2], name='discount'), tf.constant([[1, 2], [3, 4]], dtype=tf.float32, name='observation')) @test_cases() def testBuild(self, network_ctor): actor_network = network_ctor(self._obs_spec, self._action_spec) policy = actor_policy.ActorPolicy( self._time_step_spec, self._action_spec, actor_network=actor_network) self.assertEqual(policy.time_step_spec, self._time_step_spec) self.assertEqual(policy.action_spec, self._action_spec) self.assertLen(policy.variables(), 2) @test_cases() def testActionBatch(self, network_ctor): actor_network = network_ctor(self._obs_spec, self._action_spec) policy = actor_policy.ActorPolicy( self._time_step_spec, self._action_spec, actor_network=actor_network) action_step = policy.action(self._time_step_batch) self.assertEqual(action_step.action.shape.as_list(), [2, 1]) self.assertEqual(action_step.action.dtype, tf.float32) self.evaluate(tf.compat.v1.global_variables_initializer()) actions_ = self.evaluate(action_step.action) self.assertTrue(np.all(actions_ >= self._action_spec.minimum)) self.assertTrue(np.all(actions_ <= self._action_spec.maximum)) def testUpdate(self): tf.compat.v1.set_random_seed(1) actor_network = DummyActionNet(self._obs_spec, self._action_spec) policy = actor_policy.ActorPolicy( self._time_step_spec, self._action_spec, actor_network=actor_network) self.assertLen(policy.variables(), 2) new_policy = actor_policy.ActorPolicy( self._time_step_spec, self._action_spec, actor_network=actor_network) action_step = policy.action(self._time_step_batch) self.assertLen(policy.variables(), 2) new_action_step = new_policy.action(self._time_step_batch) self.assertLen(new_policy.variables(), 2) self.assertEqual(action_step.action.shape, new_action_step.action.shape) self.assertEqual(action_step.action.dtype, new_action_step.action.dtype) self.evaluate(tf.compat.v1.global_variables_initializer()) self.evaluate(new_policy.update(policy)) actions_, new_actions_ = self.evaluate( [action_step.action, new_action_step.action]) self.assertAllEqual(actions_, new_actions_) def testDeterministicDistribution(self): actor_network = DummyActionNet(self._obs_spec, self._action_spec) policy = actor_policy.ActorPolicy( self._time_step_spec, self._action_spec, actor_network=actor_network) action_step = policy.action(self._time_step_batch) distribution_step = policy.distribution(self._time_step_batch) self.assertIsInstance(distribution_step.action, tfp.distributions.Deterministic) distribution_mean = distribution_step.action.mean() self.evaluate(tf.compat.v1.global_variables_initializer()) actions_ = self.evaluate(action_step.action) distribution_mean_ = self.evaluate(distribution_mean) self.assertNear(actions_[0], distribution_mean_[0], 1e-6) def testGaussianDistribution(self): actor_network = DummyActionDistributionNet(self._obs_spec, self._action_spec) policy = actor_policy.ActorPolicy( self._time_step_spec, self._action_spec, actor_network=actor_network) distribution_step = policy.distribution(self._time_step_batch) self.assertIsInstance(distribution_step.action, tfp.distributions.Normal) class ActorPolicyDiscreteActionsTest(test_utils.TestCase): def setUp(self): super(ActorPolicyDiscreteActionsTest, self).setUp() self._obs_spec = tensor_spec.TensorSpec([2], tf.float32) self._time_step_spec = ts.time_step_spec(self._obs_spec) self._action_spec = tensor_spec.BoundedTensorSpec([1], tf.int32, 0, 7) @property def _time_step(self): return ts.restart(tf.constant([1, 2], dtype=tf.float32)) @property def _time_step_batch(self): return ts.TimeStep( tf.constant( ts.StepType.FIRST, dtype=tf.int32, shape=[2], name='step_type'), tf.constant(0.0, dtype=tf.float32, shape=[2], name='reward'), tf.constant(1.0, dtype=tf.float32, shape=[2], name='discount'), tf.constant([[1, 2], [3, 4]], dtype=tf.float32, name='observation')) def testBuild(self): actor_network = actor_distribution_network.ActorDistributionNetwork( self._obs_spec, self._action_spec, fc_layer_params=(2, 1)) policy = actor_policy.ActorPolicy( self._time_step_spec, self._action_spec, actor_network=actor_network) self.assertEqual(policy.time_step_spec, self._time_step_spec) self.assertEqual(policy.action_spec, self._action_spec) def testActionBatch(self): actor_network = actor_distribution_network.ActorDistributionNetwork( self._obs_spec, self._action_spec, fc_layer_params=(2, 1)) policy = actor_policy.ActorPolicy( self._time_step_spec, self._action_spec, actor_network=actor_network) action_step = policy.action(self._time_step_batch) self.assertEqual(action_step.action.shape.as_list(), [2, 1]) self.assertEqual(action_step.action.dtype, self._action_spec.dtype) self.evaluate(tf.compat.v1.global_variables_initializer()) actions_ = self.evaluate(action_step.action) self.assertTrue(np.all(actions_ >= self._action_spec.minimum)) self.assertTrue(np.all(actions_ <= self._action_spec.maximum)) def testActionDistribution(self): actor_network = actor_distribution_network.ActorDistributionNetwork( self._obs_spec, self._action_spec, fc_layer_params=(2, 1)) policy = actor_policy.ActorPolicy( self._time_step_spec, self._action_spec, actor_network=actor_network) # Force creation of variables before global_variables_initializer. policy.variables() self.evaluate(tf.compat.v1.global_variables_initializer()) distribution = policy.distribution(self._time_step_batch) actions_ = self.evaluate(distribution.action.sample()) self.assertTrue(np.all(actions_ >= self._action_spec.minimum)) self.assertTrue(np.all(actions_ <= self._action_spec.maximum)) def testMasking(self): batch_size = 1000 num_state_dims = 5 num_actions = 8 observations = tf.random.uniform([batch_size, num_state_dims]) time_step = ts.restart(observations, batch_size=batch_size) input_tensor_spec = tensor_spec.TensorSpec([num_state_dims], tf.float32) time_step_spec = ts.time_step_spec(input_tensor_spec) action_spec = tensor_spec.BoundedTensorSpec( [1], tf.int32, 0, num_actions - 1) # We create a fixed mask here for testing purposes. Normally the mask would # be part of the observation. mask = [0, 1, 0, 1, 0, 0, 1, 0] np_mask = np.array(mask) tf_mask = tf.constant([mask for _ in range(batch_size)]) actor_network = actor_distribution_network.ActorDistributionNetwork( input_tensor_spec, action_spec, fc_layer_params=(2, 1)) policy = actor_policy.ActorPolicy( time_step_spec, action_spec, actor_network=actor_network, observation_and_action_constraint_splitter=( lambda observation: (observation, tf_mask))) # Force creation of variables before global_variables_initializer. policy.variables() self.evaluate(tf.compat.v1.global_variables_initializer()) # Sample from the policy 1000 times, and ensure that actions considered # invalid according to the mask are never chosen. action_step = policy.action(time_step) action = self.evaluate(action_step.action) self.assertEqual(action.shape, (batch_size, 1)) self.assertAllEqual(np_mask[action], np.ones([batch_size, 1])) if __name__ == '__main__': tf.test.main()
41.322695
80
0.73878
from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np import tensorflow as tf import tensorflow_probability as tfp from tf_agents.networks import actor_distribution_network from tf_agents.networks import network from tf_agents.policies import actor_policy from tf_agents.specs import tensor_spec from tf_agents.trajectories import time_step as ts from tf_agents.utils import test_utils class DummyActionNet(network.Network): def __init__(self, input_tensor_spec, output_tensor_spec): super(DummyActionNet, self).__init__( input_tensor_spec=input_tensor_spec, state_spec=(), name='DummyActionNet') single_action_spec = tf.nest.flatten(output_tensor_spec)[0] self._output_tensor_spec = output_tensor_spec self._sub_layers = [ tf.keras.layers.Dense( single_action_spec.shape.num_elements(), activation=tf.nn.tanh, kernel_initializer=tf.compat.v1.initializers.constant([2, 1]), bias_initializer=tf.compat.v1.initializers.constant([5]), ), ] def call(self, observations, step_type, network_state): del step_type states = tf.cast(tf.nest.flatten(observations)[0], tf.float32) for layer in self._sub_layers: states = layer(states) single_action_spec = tf.nest.flatten(self._output_tensor_spec)[0] means = tf.reshape(states, [-1] + single_action_spec.shape.as_list()) spec_means = (single_action_spec.maximum + single_action_spec.minimum) / 2.0 spec_ranges = ( single_action_spec.maximum - single_action_spec.minimum) / 2.0 action_means = spec_means + spec_ranges * means return (tf.nest.pack_sequence_as(self._output_tensor_spec, [action_means]), network_state) class DummyActionDistributionNet(DummyActionNet): def call(self, observations, step_type, network_state): action_means, network_state = super(DummyActionDistributionNet, self).call( observations, step_type, network_state) def _action_distribution(action_mean): action_std = tf.ones_like(action_mean) return tfp.distributions.Normal(action_mean, action_std) return tf.nest.map_structure(_action_distribution, action_means), network_state def test_cases(): return parameterized.named_parameters({ 'testcase_name': 'SimpleNet', 'network_ctor': DummyActionNet, }, { 'testcase_name': 'DistributionNet', 'network_ctor': DummyActionDistributionNet, }) class ActorPolicyTest(parameterized.TestCase, test_utils.TestCase): def setUp(self): super(ActorPolicyTest, self).setUp() self._obs_spec = tensor_spec.TensorSpec([2], tf.float32) self._time_step_spec = ts.time_step_spec(self._obs_spec) self._action_spec = tensor_spec.BoundedTensorSpec([1], tf.float32, 2, 3) @property def _time_step(self): return ts.restart(tf.constant([1, 2], dtype=tf.float32)) @property def _time_step_batch(self): return ts.TimeStep( tf.constant( ts.StepType.FIRST, dtype=tf.int32, shape=[2], name='step_type'), tf.constant(0.0, dtype=tf.float32, shape=[2], name='reward'), tf.constant(1.0, dtype=tf.float32, shape=[2], name='discount'), tf.constant([[1, 2], [3, 4]], dtype=tf.float32, name='observation')) @test_cases() def testBuild(self, network_ctor): actor_network = network_ctor(self._obs_spec, self._action_spec) policy = actor_policy.ActorPolicy( self._time_step_spec, self._action_spec, actor_network=actor_network) self.assertEqual(policy.time_step_spec, self._time_step_spec) self.assertEqual(policy.action_spec, self._action_spec) self.assertLen(policy.variables(), 2) @test_cases() def testActionBatch(self, network_ctor): actor_network = network_ctor(self._obs_spec, self._action_spec) policy = actor_policy.ActorPolicy( self._time_step_spec, self._action_spec, actor_network=actor_network) action_step = policy.action(self._time_step_batch) self.assertEqual(action_step.action.shape.as_list(), [2, 1]) self.assertEqual(action_step.action.dtype, tf.float32) self.evaluate(tf.compat.v1.global_variables_initializer()) actions_ = self.evaluate(action_step.action) self.assertTrue(np.all(actions_ >= self._action_spec.minimum)) self.assertTrue(np.all(actions_ <= self._action_spec.maximum)) def testUpdate(self): tf.compat.v1.set_random_seed(1) actor_network = DummyActionNet(self._obs_spec, self._action_spec) policy = actor_policy.ActorPolicy( self._time_step_spec, self._action_spec, actor_network=actor_network) self.assertLen(policy.variables(), 2) new_policy = actor_policy.ActorPolicy( self._time_step_spec, self._action_spec, actor_network=actor_network) action_step = policy.action(self._time_step_batch) self.assertLen(policy.variables(), 2) new_action_step = new_policy.action(self._time_step_batch) self.assertLen(new_policy.variables(), 2) self.assertEqual(action_step.action.shape, new_action_step.action.shape) self.assertEqual(action_step.action.dtype, new_action_step.action.dtype) self.evaluate(tf.compat.v1.global_variables_initializer()) self.evaluate(new_policy.update(policy)) actions_, new_actions_ = self.evaluate( [action_step.action, new_action_step.action]) self.assertAllEqual(actions_, new_actions_) def testDeterministicDistribution(self): actor_network = DummyActionNet(self._obs_spec, self._action_spec) policy = actor_policy.ActorPolicy( self._time_step_spec, self._action_spec, actor_network=actor_network) action_step = policy.action(self._time_step_batch) distribution_step = policy.distribution(self._time_step_batch) self.assertIsInstance(distribution_step.action, tfp.distributions.Deterministic) distribution_mean = distribution_step.action.mean() self.evaluate(tf.compat.v1.global_variables_initializer()) actions_ = self.evaluate(action_step.action) distribution_mean_ = self.evaluate(distribution_mean) self.assertNear(actions_[0], distribution_mean_[0], 1e-6) def testGaussianDistribution(self): actor_network = DummyActionDistributionNet(self._obs_spec, self._action_spec) policy = actor_policy.ActorPolicy( self._time_step_spec, self._action_spec, actor_network=actor_network) distribution_step = policy.distribution(self._time_step_batch) self.assertIsInstance(distribution_step.action, tfp.distributions.Normal) class ActorPolicyDiscreteActionsTest(test_utils.TestCase): def setUp(self): super(ActorPolicyDiscreteActionsTest, self).setUp() self._obs_spec = tensor_spec.TensorSpec([2], tf.float32) self._time_step_spec = ts.time_step_spec(self._obs_spec) self._action_spec = tensor_spec.BoundedTensorSpec([1], tf.int32, 0, 7) @property def _time_step(self): return ts.restart(tf.constant([1, 2], dtype=tf.float32)) @property def _time_step_batch(self): return ts.TimeStep( tf.constant( ts.StepType.FIRST, dtype=tf.int32, shape=[2], name='step_type'), tf.constant(0.0, dtype=tf.float32, shape=[2], name='reward'), tf.constant(1.0, dtype=tf.float32, shape=[2], name='discount'), tf.constant([[1, 2], [3, 4]], dtype=tf.float32, name='observation')) def testBuild(self): actor_network = actor_distribution_network.ActorDistributionNetwork( self._obs_spec, self._action_spec, fc_layer_params=(2, 1)) policy = actor_policy.ActorPolicy( self._time_step_spec, self._action_spec, actor_network=actor_network) self.assertEqual(policy.time_step_spec, self._time_step_spec) self.assertEqual(policy.action_spec, self._action_spec) def testActionBatch(self): actor_network = actor_distribution_network.ActorDistributionNetwork( self._obs_spec, self._action_spec, fc_layer_params=(2, 1)) policy = actor_policy.ActorPolicy( self._time_step_spec, self._action_spec, actor_network=actor_network) action_step = policy.action(self._time_step_batch) self.assertEqual(action_step.action.shape.as_list(), [2, 1]) self.assertEqual(action_step.action.dtype, self._action_spec.dtype) self.evaluate(tf.compat.v1.global_variables_initializer()) actions_ = self.evaluate(action_step.action) self.assertTrue(np.all(actions_ >= self._action_spec.minimum)) self.assertTrue(np.all(actions_ <= self._action_spec.maximum)) def testActionDistribution(self): actor_network = actor_distribution_network.ActorDistributionNetwork( self._obs_spec, self._action_spec, fc_layer_params=(2, 1)) policy = actor_policy.ActorPolicy( self._time_step_spec, self._action_spec, actor_network=actor_network) policy.variables() self.evaluate(tf.compat.v1.global_variables_initializer()) distribution = policy.distribution(self._time_step_batch) actions_ = self.evaluate(distribution.action.sample()) self.assertTrue(np.all(actions_ >= self._action_spec.minimum)) self.assertTrue(np.all(actions_ <= self._action_spec.maximum)) def testMasking(self): batch_size = 1000 num_state_dims = 5 num_actions = 8 observations = tf.random.uniform([batch_size, num_state_dims]) time_step = ts.restart(observations, batch_size=batch_size) input_tensor_spec = tensor_spec.TensorSpec([num_state_dims], tf.float32) time_step_spec = ts.time_step_spec(input_tensor_spec) action_spec = tensor_spec.BoundedTensorSpec( [1], tf.int32, 0, num_actions - 1) mask = [0, 1, 0, 1, 0, 0, 1, 0] np_mask = np.array(mask) tf_mask = tf.constant([mask for _ in range(batch_size)]) actor_network = actor_distribution_network.ActorDistributionNetwork( input_tensor_spec, action_spec, fc_layer_params=(2, 1)) policy = actor_policy.ActorPolicy( time_step_spec, action_spec, actor_network=actor_network, observation_and_action_constraint_splitter=( lambda observation: (observation, tf_mask))) policy.variables() self.evaluate(tf.compat.v1.global_variables_initializer()) action_step = policy.action(time_step) action = self.evaluate(action_step.action) self.assertEqual(action.shape, (batch_size, 1)) self.assertAllEqual(np_mask[action], np.ones([batch_size, 1])) if __name__ == '__main__': tf.test.main()
true
true
f7fe7b39823cb214a93650991b086952e666f36c
308
py
Python
feedz/users/apps.py
Dimercel/feedz
d1f0ab1558b6df63452d1ac12847e3e816c83c31
[ "MIT" ]
null
null
null
feedz/users/apps.py
Dimercel/feedz
d1f0ab1558b6df63452d1ac12847e3e816c83c31
[ "MIT" ]
null
null
null
feedz/users/apps.py
Dimercel/feedz
d1f0ab1558b6df63452d1ac12847e3e816c83c31
[ "MIT" ]
null
null
null
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class UsersConfig(AppConfig): name = "feedz.users" verbose_name = _("Users") def ready(self): try: import feedz.users.signals # noqa F401 except ImportError: pass
22
54
0.649351
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class UsersConfig(AppConfig): name = "feedz.users" verbose_name = _("Users") def ready(self): try: import feedz.users.signals except ImportError: pass
true
true
f7fe7b7cddac60490fd507db0067a3b0e0cf4da2
2,858
py
Python
janitor/functions/collapse_levels.py
thatlittleboy/pyjanitor
f7977e00d3d9bf49aebeaa62db2965a668c50c90
[ "MIT" ]
null
null
null
janitor/functions/collapse_levels.py
thatlittleboy/pyjanitor
f7977e00d3d9bf49aebeaa62db2965a668c50c90
[ "MIT" ]
null
null
null
janitor/functions/collapse_levels.py
thatlittleboy/pyjanitor
f7977e00d3d9bf49aebeaa62db2965a668c50c90
[ "MIT" ]
null
null
null
"""Implementation of the `collapse_levels` function.""" import pandas as pd import pandas_flavor as pf from janitor.utils import check @pf.register_dataframe_method def collapse_levels(df: pd.DataFrame, sep: str = "_") -> pd.DataFrame: """Flatten multi-level column dataframe to a single level. This method mutates the original DataFrame. Given a DataFrame containing multi-level columns, flatten to single-level by string-joining the column labels in each level. After a `groupby` / `aggregate` operation where `.agg()` is passed a list of multiple aggregation functions, a multi-level DataFrame is returned with the name of the function applied in the second level. It is sometimes convenient for later indexing to flatten out this multi-level configuration back into a single level. This function does this through a simple string-joining of all the names across different levels in a single column. Example: >>> import pandas as pd >>> import janitor >>> df = pd.DataFrame({ ... "class": ["bird", "bird", "bird", "mammal", "mammal"], ... "max_speed": [389, 389, 24, 80, 21], ... "type": ["falcon", "falcon", "parrot", "Lion", "Monkey"], ... }) >>> df class max_speed type 0 bird 389 falcon 1 bird 389 falcon 2 bird 24 parrot 3 mammal 80 Lion 4 mammal 21 Monkey >>> grouped_df = df.groupby("class").agg(["mean", "median"]) >>> grouped_df # doctest: +NORMALIZE_WHITESPACE max_speed mean median class bird 267.333333 389.0 mammal 50.500000 50.5 >>> grouped_df.collapse_levels(sep="_") # doctest: +NORMALIZE_WHITESPACE max_speed_mean max_speed_median class bird 267.333333 389.0 mammal 50.500000 50.5 Before applying `.collapse_levels`, the `.agg` operation returns a multi-level column DataFrame whose columns are `(level 1, level 2)`: [("max_speed", "mean"), ("max_speed", "median")] `.collapse_levels` then flattens the column MultiIndex into a single level index with names: ["max_speed_mean", "max_speed_median"] :param df: A pandas DataFrame. :param sep: String separator used to join the column level names. :returns: A pandas DataFrame with single-level column index. """ # noqa: E501 check("sep", sep, [str]) # if already single-level, just return the DataFrame if not isinstance(df.columns, pd.MultiIndex): return df df.columns = [ sep.join(str(el) for el in tup if str(el) != "") for tup in df # noqa: PD011 ] return df
35.283951
81
0.607068
import pandas as pd import pandas_flavor as pf from janitor.utils import check @pf.register_dataframe_method def collapse_levels(df: pd.DataFrame, sep: str = "_") -> pd.DataFrame: check("sep", sep, [str]) if not isinstance(df.columns, pd.MultiIndex): return df df.columns = [ sep.join(str(el) for el in tup if str(el) != "") for tup in df ] return df
true
true
f7fe7be8107302b407a6207200066210a6ed92fc
847
py
Python
Chapter09/extract_stats.py
marcjour303/PytML
cd1391976167a7a671e98a1f588898c01585cee9
[ "MIT" ]
36
2019-04-05T00:58:57.000Z
2022-03-12T09:25:04.000Z
Chapter09/extract_stats.py
ClauPorto/Python-Machine-Learning-Cookbook-Second-Edition
99d8b799dbfe1d9a82f0bcc3648aaeb147b7298f
[ "MIT" ]
null
null
null
Chapter09/extract_stats.py
ClauPorto/Python-Machine-Learning-Cookbook-Second-Edition
99d8b799dbfe1d9a82f0bcc3648aaeb147b7298f
[ "MIT" ]
37
2019-04-16T00:50:20.000Z
2022-02-28T18:14:41.000Z
import pandas as pd import matplotlib.pyplot as plt from convert_to_timeseries import convert_data_to_timeseries # Input file containing data input_file = 'data_timeseries.txt' # Load data data1 = convert_data_to_timeseries(input_file, 2) data2 = convert_data_to_timeseries(input_file, 3) dataframe = pd.DataFrame({'first': data1, 'second': data2}) # Print max and min print('Maximum:\n', dataframe.max()) print('Minimum:\n', dataframe.min()) # Print mean print('Mean:\n', dataframe.mean()) print('Mean row-wise:\n', dataframe.mean(1)[:10]) # Plot rolling mean DFMean = dataframe.rolling(window=24).mean() plt.plot(DFMean) # Print correlation coefficients print('Correlation coefficients:\n', dataframe.corr()) # Plot rolling correlation plt.figure() DFCorr= dataframe.rolling(window=60).corr(pairwise=False) plt.plot(DFCorr) plt.show()
23.527778
60
0.75915
import pandas as pd import matplotlib.pyplot as plt from convert_to_timeseries import convert_data_to_timeseries input_file = 'data_timeseries.txt' data1 = convert_data_to_timeseries(input_file, 2) data2 = convert_data_to_timeseries(input_file, 3) dataframe = pd.DataFrame({'first': data1, 'second': data2}) print('Maximum:\n', dataframe.max()) print('Minimum:\n', dataframe.min()) print('Mean:\n', dataframe.mean()) print('Mean row-wise:\n', dataframe.mean(1)[:10]) DFMean = dataframe.rolling(window=24).mean() plt.plot(DFMean) print('Correlation coefficients:\n', dataframe.corr()) plt.figure() DFCorr= dataframe.rolling(window=60).corr(pairwise=False) plt.plot(DFCorr) plt.show()
true
true
f7fe7c3e9a50e5313f3c1ed8e488b4a3eb47b65e
332
py
Python
school/migrations/0018_auto_20200610_0808.py
ankit986/school-management
cdffab5280199856397cdef36d18e84def841f93
[ "MIT" ]
null
null
null
school/migrations/0018_auto_20200610_0808.py
ankit986/school-management
cdffab5280199856397cdef36d18e84def841f93
[ "MIT" ]
6
2021-03-19T04:29:01.000Z
2021-09-22T19:09:31.000Z
school/migrations/0018_auto_20200610_0808.py
ankit986/school-management
cdffab5280199856397cdef36d18e84def841f93
[ "MIT" ]
null
null
null
# Generated by Django 3.0.5 on 2020-06-10 08:08 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('school', '0017_auto_20200610_0807'), ] operations = [ migrations.RenameModel( old_name='Subjects', new_name='Subject', ), ]
18.444444
47
0.596386
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('school', '0017_auto_20200610_0807'), ] operations = [ migrations.RenameModel( old_name='Subjects', new_name='Subject', ), ]
true
true
f7fe7fb8c35219db1d8d21029b362a1bc08ef011
781
py
Python
venv/bin/rst2html4.py
anthodemorais/spaces
e2f4b70bf2438a39ce1e1bd954f8dc98bea5280d
[ "MIT" ]
null
null
null
venv/bin/rst2html4.py
anthodemorais/spaces
e2f4b70bf2438a39ce1e1bd954f8dc98bea5280d
[ "MIT" ]
null
null
null
venv/bin/rst2html4.py
anthodemorais/spaces
e2f4b70bf2438a39ce1e1bd954f8dc98bea5280d
[ "MIT" ]
null
null
null
#!/Users/anthonydemorais/Documents/travail/supinternet/python/spaces/venv/bin/python3 # $Id: rst2html4.py 7994 2016-12-10 17:41:45Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ A minimal front end to the Docutils Publisher, producing (X)HTML. The output conforms to XHTML 1.0 transitional and almost to HTML 4.01 transitional (except for closing empty tags). """ try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description description = ('Generates (X)HTML documents from standalone reStructuredText ' 'sources. ' + default_description) publish_cmdline(writer_name='html4', description=description)
28.925926
85
0.754161
try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description description = ('Generates (X)HTML documents from standalone reStructuredText ' 'sources. ' + default_description) publish_cmdline(writer_name='html4', description=description)
true
true
f7fe7fe0ec0ed226b6d14b0fd44f387f10cebd93
10,897
py
Python
custom_components/awox/config_flow.py
valentingc/home-assistant-awox
3015f524404962b66bad961b446a37263b717882
[ "MIT" ]
null
null
null
custom_components/awox/config_flow.py
valentingc/home-assistant-awox
3015f524404962b66bad961b446a37263b717882
[ "MIT" ]
null
null
null
custom_components/awox/config_flow.py
valentingc/home-assistant-awox
3015f524404962b66bad961b446a37263b717882
[ "MIT" ]
null
null
null
"""Config flow for AwoX MESH lights""" from typing import Mapping, Optional import logging import pygatt import voluptuous as vol from homeassistant import config_entries from homeassistant.const import ( CONF_USERNAME, CONF_PASSWORD ) from .scanner import DeviceScanner from .const import DOMAIN, CONF_MESH_NAME, CONF_MESH_PASSWORD, CONF_MESH_KEY from .awox_connect import AwoxConnect from bluepy.btle import BTLEManagementError _LOGGER = logging.getLogger(__name__) def create_awox_connect_object(username, password) -> AwoxConnect: return AwoxConnect(username, password) class AwoxMeshFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Handle a Awox config flow.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL config: Optional[Mapping] = {} def __init__(self): """Initialize the UPnP/IGD config flow.""" self._discoveries: Optional[Mapping] = None self._mesh_info: Optional[Mapping] = None async def async_step_user(self, user_input: Optional[Mapping] = None): return await self.async_step_awox_connect() # todo: fix manual connect _LOGGER.debug("async_step_user: user_input: %s", user_input) if self._mesh_info is None: return await self.async_step_mesh_info() if user_input is not None and user_input.get('mac'): # Ensure wanted device is available test_ok = await DeviceScanner.connect_device( user_input.get('mac'), self._mesh_info.get(CONF_MESH_NAME), self._mesh_info.get(CONF_MESH_PASSWORD), self._mesh_info.get(CONF_MESH_KEY) ) if not test_ok: return self.async_abort(reason="device_not_found") await self.async_set_unique_id( self._mesh_info.get(CONF_MESH_NAME), raise_on_progress=False ) return await self._async_create_entry_from_discovery( user_input.get('mac'), user_input.get('name'), self._mesh_info.get(CONF_MESH_NAME), self._mesh_info.get(CONF_MESH_PASSWORD), self._mesh_info.get(CONF_MESH_KEY) ) # Scan for devices scan_successful = False try: discoveries = await DeviceScanner.find_devices( self._mesh_info.get(CONF_MESH_NAME), self._mesh_info.get(CONF_MESH_PASSWORD) ) scan_successful = True except (RuntimeError, pygatt.exceptions.BLEError) as e: _LOGGER.exception("Failed while scanning for devices [%s]", str(e)) if not scan_successful: return self.async_show_form( step_id="manual", data_schema=vol.Schema({ vol.Required('mac'): str, vol.Required("name", description={"suggested_value": "AwoX light"}): str, }), ) # Store discoveries which have not been configured, add name for each discovery. current_devices = {entry.unique_id for entry in self._async_current_entries()} self._discoveries = [ { **discovery, 'name': discovery['name'], } for discovery in discoveries if discovery['mac'] not in current_devices ] # Ensure anything to add. if not self._discoveries: return self.async_abort(reason="no_devices_found") data_schema = vol.Schema( { vol.Required("mac"): vol.In( { discovery['mac']: discovery['name'] for discovery in self._discoveries } ), vol.Required("name", description={"suggested_value": "AwoX light"}): str, } ) return self.async_show_form( step_id="select_device", data_schema=data_schema, ) async def async_step_awox_connect(self, user_input: Optional[Mapping] = None): errors = {} username: str = '' password: str = '' awox_connect = None if user_input is not None: username = user_input.get(CONF_USERNAME) password = user_input.get(CONF_PASSWORD) if username and password: try: awox_connect = await self.hass.async_add_executor_job(create_awox_connect_object, username, password) except Exception as e: _LOGGER.error('Can not login to AwoX Smart Connect [%s]', e) errors[CONF_PASSWORD] = 'cannot_connect' if user_input is None or awox_connect is None or errors: return self.async_show_form( step_id="awox_connect", data_schema=vol.Schema({ vol.Required(CONF_USERNAME, default=username): str, vol.Required(CONF_PASSWORD, default=password): str, }), errors=errors, ) devices = [] for device in await self.hass.async_add_executor_job(awox_connect.devices): _LOGGER.debug('Processing device - %s', device) if 'type' not in device: _LOGGER.warning('Skipped device, missing type - %s', device) continue if 'address' not in device: _LOGGER.warning('Skipped device, missing address - %s', device) continue if 'macAddress' not in device: _LOGGER.warning('Skipped device, missing macAddress - %s', device) continue if 'displayName' not in device: _LOGGER.warning('Skipped device, missing displayName - %s', device) continue if 'modelName' not in device: device['modelName'] = 'unknown' if 'vendor' not in device: device['vendor'] = 'unknown' if 'version' not in device: device['version'] = 'unknown' if 'hardwareVersion' not in device: device['hardwareVersion'] = None devices.append({ 'mesh_id': int(device['address']), 'name': device['displayName'], 'mac': device['macAddress'], 'model': device['modelName'], 'manufacturer': device['vendor'], 'firmware': device['version'], 'hardware': device['hardwareVersion'], 'type': device['type'] }) if len(devices) == 0: return self.async_abort(reason="no_devices_found") credentials = await self.hass.async_add_executor_job(awox_connect.credentials) data = { CONF_MESH_NAME: credentials['client_id'], CONF_MESH_PASSWORD: credentials['access_token'], CONF_MESH_KEY: credentials['refresh_token'], # 'awox_connect': { # CONF_USERNAME: user_input[CONF_USERNAME], # CONF_PASSWORD: user_input[CONF_PASSWORD] # }, 'devices': devices } return self.async_create_entry(title='AwoX Smart Connect', data=data) async def async_step_mesh_info(self, user_input: Optional[Mapping] = None): _LOGGER.debug("async_step_mesh_info: user_input: %s", user_input) errors = {} name: str = '' password: str = '' key: str = '' if user_input is not None: name = user_input.get(CONF_MESH_NAME) password = user_input.get(CONF_MESH_PASSWORD) key = user_input.get(CONF_MESH_KEY) if len(user_input.get(CONF_MESH_NAME)) > 16: errors[CONF_MESH_NAME] = 'max_length_16' if len(user_input.get(CONF_MESH_PASSWORD)) > 16: errors[CONF_MESH_PASSWORD] = 'max_length_16' if len(user_input.get(CONF_MESH_KEY)) > 16: errors[CONF_MESH_KEY] = 'max_length_16' if user_input is None or errors: return self.async_show_form( step_id="mesh_info", data_schema=vol.Schema({ vol.Required(CONF_MESH_NAME, default=name): str, vol.Required(CONF_MESH_PASSWORD, default=password): str, vol.Required(CONF_MESH_KEY, default=key): str }), errors=errors, ) self._mesh_info = user_input return await self.async_step_user() async def async_step_manual(self, user_input: Optional[Mapping] = None): """Forward result of manual input form to step user""" return await self.async_step_user(user_input) async def async_step_select_device(self, user_input: Optional[Mapping] = None): """Forward result of device select form to step user""" return await self.async_step_user(user_input) # @staticmethod # @callback # def async_get_options_flow(config_entry): # """Define the config flow to handle options.""" # return UpnpOptionsFlowHandler(config_entry) async def _async_create_entry_from_discovery( self, mac: str, name: str, mesh_name: str, mesh_pass: str, mesh_key: str ): """Create an entry from discovery.""" _LOGGER.debug( "_async_create_entry_from_discovery: device: %s [%s]", name, mac ) data = { CONF_MESH_NAME: mesh_name, CONF_MESH_PASSWORD: mesh_pass, CONF_MESH_KEY: mesh_key, 'devices': [ { 'mac': mac, 'name': name, } ] } return self.async_create_entry(title=name, data=data) # # async def _async_get_name_for_discovery(self, discovery: Mapping): # """Get the name of the device from a discovery.""" # _LOGGER.debug("_async_get_name_for_discovery: discovery: %s", discovery) # device = await Device.async_create_device( # self.hass, discovery[DISCOVERY_LOCATION] # ) # return device.name # # # async def _async_get_name_for_discovery(self, discovery: Mapping): # """Get the name of the device from a discovery.""" # _LOGGER.debug("_async_get_name_for_discovery: discovery: %s", discovery) # device = await Device.async_create_device( # self.hass, discovery['name'] # ) # return device.name # # async def _async_has_devices(hass) -> bool: # """Return if there are devices that can be discovered.""" # devices = await DeviceScanner.find_devices() # return len(devices) > 0
35.611111
117
0.578691
from typing import Mapping, Optional import logging import pygatt import voluptuous as vol from homeassistant import config_entries from homeassistant.const import ( CONF_USERNAME, CONF_PASSWORD ) from .scanner import DeviceScanner from .const import DOMAIN, CONF_MESH_NAME, CONF_MESH_PASSWORD, CONF_MESH_KEY from .awox_connect import AwoxConnect from bluepy.btle import BTLEManagementError _LOGGER = logging.getLogger(__name__) def create_awox_connect_object(username, password) -> AwoxConnect: return AwoxConnect(username, password) class AwoxMeshFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL config: Optional[Mapping] = {} def __init__(self): self._discoveries: Optional[Mapping] = None self._mesh_info: Optional[Mapping] = None async def async_step_user(self, user_input: Optional[Mapping] = None): return await self.async_step_awox_connect() _LOGGER.debug("async_step_user: user_input: %s", user_input) if self._mesh_info is None: return await self.async_step_mesh_info() if user_input is not None and user_input.get('mac'): test_ok = await DeviceScanner.connect_device( user_input.get('mac'), self._mesh_info.get(CONF_MESH_NAME), self._mesh_info.get(CONF_MESH_PASSWORD), self._mesh_info.get(CONF_MESH_KEY) ) if not test_ok: return self.async_abort(reason="device_not_found") await self.async_set_unique_id( self._mesh_info.get(CONF_MESH_NAME), raise_on_progress=False ) return await self._async_create_entry_from_discovery( user_input.get('mac'), user_input.get('name'), self._mesh_info.get(CONF_MESH_NAME), self._mesh_info.get(CONF_MESH_PASSWORD), self._mesh_info.get(CONF_MESH_KEY) ) scan_successful = False try: discoveries = await DeviceScanner.find_devices( self._mesh_info.get(CONF_MESH_NAME), self._mesh_info.get(CONF_MESH_PASSWORD) ) scan_successful = True except (RuntimeError, pygatt.exceptions.BLEError) as e: _LOGGER.exception("Failed while scanning for devices [%s]", str(e)) if not scan_successful: return self.async_show_form( step_id="manual", data_schema=vol.Schema({ vol.Required('mac'): str, vol.Required("name", description={"suggested_value": "AwoX light"}): str, }), ) current_devices = {entry.unique_id for entry in self._async_current_entries()} self._discoveries = [ { **discovery, 'name': discovery['name'], } for discovery in discoveries if discovery['mac'] not in current_devices ] if not self._discoveries: return self.async_abort(reason="no_devices_found") data_schema = vol.Schema( { vol.Required("mac"): vol.In( { discovery['mac']: discovery['name'] for discovery in self._discoveries } ), vol.Required("name", description={"suggested_value": "AwoX light"}): str, } ) return self.async_show_form( step_id="select_device", data_schema=data_schema, ) async def async_step_awox_connect(self, user_input: Optional[Mapping] = None): errors = {} username: str = '' password: str = '' awox_connect = None if user_input is not None: username = user_input.get(CONF_USERNAME) password = user_input.get(CONF_PASSWORD) if username and password: try: awox_connect = await self.hass.async_add_executor_job(create_awox_connect_object, username, password) except Exception as e: _LOGGER.error('Can not login to AwoX Smart Connect [%s]', e) errors[CONF_PASSWORD] = 'cannot_connect' if user_input is None or awox_connect is None or errors: return self.async_show_form( step_id="awox_connect", data_schema=vol.Schema({ vol.Required(CONF_USERNAME, default=username): str, vol.Required(CONF_PASSWORD, default=password): str, }), errors=errors, ) devices = [] for device in await self.hass.async_add_executor_job(awox_connect.devices): _LOGGER.debug('Processing device - %s', device) if 'type' not in device: _LOGGER.warning('Skipped device, missing type - %s', device) continue if 'address' not in device: _LOGGER.warning('Skipped device, missing address - %s', device) continue if 'macAddress' not in device: _LOGGER.warning('Skipped device, missing macAddress - %s', device) continue if 'displayName' not in device: _LOGGER.warning('Skipped device, missing displayName - %s', device) continue if 'modelName' not in device: device['modelName'] = 'unknown' if 'vendor' not in device: device['vendor'] = 'unknown' if 'version' not in device: device['version'] = 'unknown' if 'hardwareVersion' not in device: device['hardwareVersion'] = None devices.append({ 'mesh_id': int(device['address']), 'name': device['displayName'], 'mac': device['macAddress'], 'model': device['modelName'], 'manufacturer': device['vendor'], 'firmware': device['version'], 'hardware': device['hardwareVersion'], 'type': device['type'] }) if len(devices) == 0: return self.async_abort(reason="no_devices_found") credentials = await self.hass.async_add_executor_job(awox_connect.credentials) data = { CONF_MESH_NAME: credentials['client_id'], CONF_MESH_PASSWORD: credentials['access_token'], CONF_MESH_KEY: credentials['refresh_token'], 'devices': devices } return self.async_create_entry(title='AwoX Smart Connect', data=data) async def async_step_mesh_info(self, user_input: Optional[Mapping] = None): _LOGGER.debug("async_step_mesh_info: user_input: %s", user_input) errors = {} name: str = '' password: str = '' key: str = '' if user_input is not None: name = user_input.get(CONF_MESH_NAME) password = user_input.get(CONF_MESH_PASSWORD) key = user_input.get(CONF_MESH_KEY) if len(user_input.get(CONF_MESH_NAME)) > 16: errors[CONF_MESH_NAME] = 'max_length_16' if len(user_input.get(CONF_MESH_PASSWORD)) > 16: errors[CONF_MESH_PASSWORD] = 'max_length_16' if len(user_input.get(CONF_MESH_KEY)) > 16: errors[CONF_MESH_KEY] = 'max_length_16' if user_input is None or errors: return self.async_show_form( step_id="mesh_info", data_schema=vol.Schema({ vol.Required(CONF_MESH_NAME, default=name): str, vol.Required(CONF_MESH_PASSWORD, default=password): str, vol.Required(CONF_MESH_KEY, default=key): str }), errors=errors, ) self._mesh_info = user_input return await self.async_step_user() async def async_step_manual(self, user_input: Optional[Mapping] = None): return await self.async_step_user(user_input) async def async_step_select_device(self, user_input: Optional[Mapping] = None): return await self.async_step_user(user_input) async def _async_create_entry_from_discovery( self, mac: str, name: str, mesh_name: str, mesh_pass: str, mesh_key: str ): _LOGGER.debug( "_async_create_entry_from_discovery: device: %s [%s]", name, mac ) data = { CONF_MESH_NAME: mesh_name, CONF_MESH_PASSWORD: mesh_pass, CONF_MESH_KEY: mesh_key, 'devices': [ { 'mac': mac, 'name': name, } ] } return self.async_create_entry(title=name, data=data)
true
true
f7fe80cc025cab2659f427cb5a3aa43e110f43d1
992
py
Python
samples/v1beta1/test_create_entry_group.py
LaudateCorpus1/python-datacatalog
7d8c3bc9bf540d3e5c0b0bd80a619792162c4fe2
[ "Apache-2.0" ]
41
2020-05-12T08:00:04.000Z
2022-03-28T22:54:06.000Z
samples/v1beta1/test_create_entry_group.py
LaudateCorpus1/python-datacatalog
7d8c3bc9bf540d3e5c0b0bd80a619792162c4fe2
[ "Apache-2.0" ]
114
2020-02-07T02:48:37.000Z
2022-03-23T00:46:01.000Z
samples/v1beta1/test_create_entry_group.py
LaudateCorpus1/python-datacatalog
7d8c3bc9bf540d3e5c0b0bd80a619792162c4fe2
[ "Apache-2.0" ]
21
2020-01-31T21:14:59.000Z
2022-02-15T07:26:39.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import create_entry_group def test_create_entry_group(capsys, client, project_id, random_entry_group_id): create_entry_group.create_entry_group(project_id, random_entry_group_id) out, err = capsys.readouterr() assert ( "Created entry group" " projects/{}/locations/{}/entryGroups/{}".format( project_id, "us-central1", random_entry_group_id ) in out )
33.066667
79
0.729839
import create_entry_group def test_create_entry_group(capsys, client, project_id, random_entry_group_id): create_entry_group.create_entry_group(project_id, random_entry_group_id) out, err = capsys.readouterr() assert ( "Created entry group" " projects/{}/locations/{}/entryGroups/{}".format( project_id, "us-central1", random_entry_group_id ) in out )
true
true
f7fe80e8482fbcf1ea81dec053a2c1afcba45fd1
497
py
Python
samples/python/preview.py
tmq902005/RealSenseID
b6882748cc7f47e041089c09a40eab6b0043fc9f
[ "Apache-2.0" ]
63
2020-12-27T16:56:36.000Z
2022-03-25T06:20:36.000Z
samples/python/preview.py
tmq902005/RealSenseID
b6882748cc7f47e041089c09a40eab6b0043fc9f
[ "Apache-2.0" ]
122
2021-01-14T11:14:28.000Z
2022-03-08T06:15:29.000Z
samples/python/preview.py
Surfndez/RealSenseID
f29171b8a5aba828d40e0ab120550730e5fbc080
[ "Apache-2.0" ]
39
2020-12-30T09:58:24.000Z
2022-03-18T01:58:40.000Z
""" License: Apache 2.0. See LICENSE file in root directory. Copyright(c) 2020-2021 Intel Corporation. All Rights Reserved. """ import time import os import rsid_py def on_image(frame): print(f'got_frame #{frame.number} {frame.width}x{frame.height}') if frame.number > 10: os._exit(0) if __name__ == '__main__': preview_cfg = rsid_py.PreviewConfig() preview_cfg.camera_number = 0 p = rsid_py.Preview(preview_cfg) p.start(on_image) while True: time.sleep(10)
23.666667
68
0.698189
import time import os import rsid_py def on_image(frame): print(f'got_frame #{frame.number} {frame.width}x{frame.height}') if frame.number > 10: os._exit(0) if __name__ == '__main__': preview_cfg = rsid_py.PreviewConfig() preview_cfg.camera_number = 0 p = rsid_py.Preview(preview_cfg) p.start(on_image) while True: time.sleep(10)
true
true
f7fe80f2f6670205bcd2605e627c18a2e743f195
3,753
py
Python
test/jobTest.py
harvardinformatics/jobTree
b4bdaeb2462b90ab8251713d4d2d8130c842cbe0
[ "MIT" ]
10
2015-02-05T16:02:06.000Z
2020-07-17T06:12:42.000Z
test/jobTest.py
harvardinformatics/jobTree
b4bdaeb2462b90ab8251713d4d2d8130c842cbe0
[ "MIT" ]
16
2015-01-06T05:56:58.000Z
2015-10-07T01:03:37.000Z
test/jobTest.py
benedictpaten/jobTree
072be69f6214e06bd8588b5e73a60b758c191663
[ "MIT" ]
14
2015-01-05T23:34:12.000Z
2019-03-07T17:45:17.000Z
#!/usr/bin/env python """Test Job class """ import unittest import os import time import sys import random from sonLib.bioio import parseSuiteTestOptions from sonLib.bioio import logger, system from jobTree.src.job import Job class TestCase(unittest.TestCase): def testJobReadWriteAndDelete(self): jobDir = os.path.join(os.getcwd(), "testJobDir") os.mkdir(jobDir) #If directory already exists then the test will fail command = "by your command" memory = 2^32 cpu = 1 tryCount = 100 for i in xrange(10): startTime = time.time() for j in xrange(100): j = Job(command, memory, cpu, tryCount, jobDir) self.assertEquals(j.remainingRetryCount, tryCount) self.assertEquals(j.jobDir, jobDir) self.assertEquals(j.children, []) self.assertEquals(j.followOnCommands, [ (command, memory, cpu, 0)]) self.assertEquals(j.messages, []) j.write() j = Job.read(j.getJobFileName()) self.assertEquals(j.remainingRetryCount, tryCount) self.assertEquals(j.jobDir, jobDir) self.assertEquals(j.children, []) self.assertEquals(j.followOnCommands, [ (command, memory, cpu, 0)]) self.assertEquals(j.messages, []) self.assertTrue(os.path.exists(j.getJobFileName())) j.delete() self.assertTrue(not os.path.exists(j.getJobFileName())) print "It took %f seconds to load/unload jobs" % (time.time() - startTime) #We've just used it for benchmarking, so far #Would be good to extend this trivial test system("rm -rf %s" % jobDir) def testJobUpdate(self): jobDir = os.path.join(os.getcwd(), "testJobDir") os.mkdir(jobDir) #If directory already exists then the test will fail command = "by your command" memory = 2^32 cpu = 1 tryCount = 100 for i in xrange(40): startTime = time.time() j = Job(command, memory, cpu, tryCount, jobDir) childNumber = random.choice(range(20)) for k in xrange(childNumber): j.children.append((command, memory, cpu)) self.assertEquals(len(j.children), childNumber) j.update(tryCount=tryCount, depth=0) j = Job.read(j.getJobFileName()) self.assertEquals(len(j.children) + len(j.followOnCommands), childNumber + 1) for childJobFile, memory, cpu in j.children: cJ = Job.read(childJobFile) self.assertEquals(cJ.remainingRetryCount, tryCount) #self.assertEquals(cJ.jobDir, os.path.split(cJ)[0]) self.assertEquals(cJ.children, []) self.assertEquals(cJ.followOnCommands, [ (command, memory, cpu, 0)]) self.assertEquals(cJ.messages, []) self.assertTrue(os.path.exists(cJ.getJobFileName())) cJ.delete() self.assertTrue(not os.path.exists(cJ.getJobFileName())) self.assertEquals(os.listdir(jobDir), [ "job" ]) j.delete() print "It took %f seconds to update jobs" % (time.time() - startTime) #We've just used it for benchmarking, so far system("rm -rf %s" % jobDir) def main(): parseSuiteTestOptions() sys.argv = sys.argv[:1] unittest.main() if __name__ == '__main__': #import cProfile #cProfile.run('main()', "fooprof") #import pstats #p = pstats.Stats('fooprof') #p.strip_dirs().sort_stats(-1).print_stats() #print p main()
39.09375
132
0.57927
"""Test Job class """ import unittest import os import time import sys import random from sonLib.bioio import parseSuiteTestOptions from sonLib.bioio import logger, system from jobTree.src.job import Job class TestCase(unittest.TestCase): def testJobReadWriteAndDelete(self): jobDir = os.path.join(os.getcwd(), "testJobDir") os.mkdir(jobDir) command = "by your command" memory = 2^32 cpu = 1 tryCount = 100 for i in xrange(10): startTime = time.time() for j in xrange(100): j = Job(command, memory, cpu, tryCount, jobDir) self.assertEquals(j.remainingRetryCount, tryCount) self.assertEquals(j.jobDir, jobDir) self.assertEquals(j.children, []) self.assertEquals(j.followOnCommands, [ (command, memory, cpu, 0)]) self.assertEquals(j.messages, []) j.write() j = Job.read(j.getJobFileName()) self.assertEquals(j.remainingRetryCount, tryCount) self.assertEquals(j.jobDir, jobDir) self.assertEquals(j.children, []) self.assertEquals(j.followOnCommands, [ (command, memory, cpu, 0)]) self.assertEquals(j.messages, []) self.assertTrue(os.path.exists(j.getJobFileName())) j.delete() self.assertTrue(not os.path.exists(j.getJobFileName())) print "It took %f seconds to load/unload jobs" % (time.time() - startTime) #Would be good to extend this trivial test system("rm -rf %s" % jobDir) def testJobUpdate(self): jobDir = os.path.join(os.getcwd(), "testJobDir") os.mkdir(jobDir) #If directory already exists then the test will fail command = "by your command" memory = 2^32 cpu = 1 tryCount = 100 for i in xrange(40): startTime = time.time() j = Job(command, memory, cpu, tryCount, jobDir) childNumber = random.choice(range(20)) for k in xrange(childNumber): j.children.append((command, memory, cpu)) self.assertEquals(len(j.children), childNumber) j.update(tryCount=tryCount, depth=0) j = Job.read(j.getJobFileName()) self.assertEquals(len(j.children) + len(j.followOnCommands), childNumber + 1) for childJobFile, memory, cpu in j.children: cJ = Job.read(childJobFile) self.assertEquals(cJ.remainingRetryCount, tryCount) #self.assertEquals(cJ.jobDir, os.path.split(cJ)[0]) self.assertEquals(cJ.children, []) self.assertEquals(cJ.followOnCommands, [ (command, memory, cpu, 0)]) self.assertEquals(cJ.messages, []) self.assertTrue(os.path.exists(cJ.getJobFileName())) cJ.delete() self.assertTrue(not os.path.exists(cJ.getJobFileName())) self.assertEquals(os.listdir(jobDir), [ "job" ]) j.delete() print "It took %f seconds to update jobs" % (time.time() - startTime) #We've just used it for benchmarking, so far system("rm -rf %s" % jobDir) def main(): parseSuiteTestOptions() sys.argv = sys.argv[:1] unittest.main() if __name__ == '__main__': main()
false
true
f7fe81eb8b18aea5e9f85788db3c3c72624547db
1,278
py
Python
hs_core/tests/api/rest/test_resource_meta.py
hydroshare/hydroshare
bf9888bbe61507aff070b1dfcec2fdec1921468d
[ "BSD-3-Clause" ]
178
2015-01-08T23:03:36.000Z
2022-03-03T13:56:45.000Z
hs_core/tests/api/rest/test_resource_meta.py
hydroshare/hydroshare
bf9888bbe61507aff070b1dfcec2fdec1921468d
[ "BSD-3-Clause" ]
4,125
2015-01-01T14:26:15.000Z
2022-03-31T16:38:55.000Z
hs_core/tests/api/rest/test_resource_meta.py
hydroshare/hydroshare
bf9888bbe61507aff070b1dfcec2fdec1921468d
[ "BSD-3-Clause" ]
53
2015-03-15T17:56:51.000Z
2022-03-17T00:32:16.000Z
import os import json import tempfile import shutil from lxml import etree from rest_framework import status from hs_core.hydroshare import resource from .base import HSRESTTestCase class TestResourceMetadata(HSRESTTestCase): def setUp(self): super(TestResourceMetadata, self).setUp() self.rtype = 'GenericResource' self.title = 'My Test resource' res = resource.create_resource(self.rtype, self.user, self.title) self.pid = res.short_id self.resources_to_delete.append(self.pid) def test_get_sysmeta(self): # Get the resource system metadata sysmeta_url = "/hsapi/resource/{res_id}/sysmeta/".format(res_id=self.pid) response = self.client.get(sysmeta_url) self.assertEqual(response.status_code, status.HTTP_200_OK) content = json.loads(response.content.decode()) self.assertEqual(content['resource_type'], self.rtype) self.assertEqual(content['resource_title'], self.title) res_tail = '/' + os.path.join('resource', self.pid) + '/' self.assertTrue(content['resource_url'].startswith('http://')) self.assertTrue(content['resource_url'].endswith(res_tail))
33.631579
81
0.656495
import os import json import tempfile import shutil from lxml import etree from rest_framework import status from hs_core.hydroshare import resource from .base import HSRESTTestCase class TestResourceMetadata(HSRESTTestCase): def setUp(self): super(TestResourceMetadata, self).setUp() self.rtype = 'GenericResource' self.title = 'My Test resource' res = resource.create_resource(self.rtype, self.user, self.title) self.pid = res.short_id self.resources_to_delete.append(self.pid) def test_get_sysmeta(self): sysmeta_url = "/hsapi/resource/{res_id}/sysmeta/".format(res_id=self.pid) response = self.client.get(sysmeta_url) self.assertEqual(response.status_code, status.HTTP_200_OK) content = json.loads(response.content.decode()) self.assertEqual(content['resource_type'], self.rtype) self.assertEqual(content['resource_title'], self.title) res_tail = '/' + os.path.join('resource', self.pid) + '/' self.assertTrue(content['resource_url'].startswith('http://')) self.assertTrue(content['resource_url'].endswith(res_tail))
true
true
f7fe822d158e70215afe6a1961af6b057bea9abb
875
py
Python
setup.py
jialuechen/raptor
bac516a45dfee9d21ac14221a2d9d5bef810cbd0
[ "MIT" ]
null
null
null
setup.py
jialuechen/raptor
bac516a45dfee9d21ac14221a2d9d5bef810cbd0
[ "MIT" ]
null
null
null
setup.py
jialuechen/raptor
bac516a45dfee9d21ac14221a2d9d5bef810cbd0
[ "MIT" ]
null
null
null
from distutils.core import setup setup( name="raptor", packages=["raptor"], version="0.1.0", description="Technical Analysis Library", long_description="It is a Technical Analysis library to financial time series datasets.", author="Julius Chen", author_email="quantchen@protonmail.com", url="https://github.com/jialuechen/raptor", maintainer="Julius Chen", maintainer_email="quantchen@protonmail.com", install_requires=[ "dask", ], download_url="https://github.com/jialuechen/raptor/raptor/0.1.0", keywords=["technical analysis", "python3", "dask"], license="The MIT License (MIT)", classifiers=[ "Intended Audience :: Quantitative Finance Industry", "Programming Language :: Python :: 3.9", "License :: OSI Approved :: MIT License", ], project_urls={ }, )
31.25
93
0.649143
from distutils.core import setup setup( name="raptor", packages=["raptor"], version="0.1.0", description="Technical Analysis Library", long_description="It is a Technical Analysis library to financial time series datasets.", author="Julius Chen", author_email="quantchen@protonmail.com", url="https://github.com/jialuechen/raptor", maintainer="Julius Chen", maintainer_email="quantchen@protonmail.com", install_requires=[ "dask", ], download_url="https://github.com/jialuechen/raptor/raptor/0.1.0", keywords=["technical analysis", "python3", "dask"], license="The MIT License (MIT)", classifiers=[ "Intended Audience :: Quantitative Finance Industry", "Programming Language :: Python :: 3.9", "License :: OSI Approved :: MIT License", ], project_urls={ }, )
true
true
f7fe82420c012cc1f5bb4fa6be66f74146bdf04f
13,963
py
Python
lib/interface.py
Messer4/electrum-cash
531547ec2b0f26569caddbf6f1037095c200d4e6
[ "MIT" ]
1
2018-01-15T04:34:53.000Z
2018-01-15T04:34:53.000Z
lib/interface.py
Messer4/electrum-cash
531547ec2b0f26569caddbf6f1037095c200d4e6
[ "MIT" ]
null
null
null
lib/interface.py
Messer4/electrum-cash
531547ec2b0f26569caddbf6f1037095c200d4e6
[ "MIT" ]
null
null
null
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2011 thomasv@gitorious # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os import re import socket import ssl import sys import threading import time import traceback import requests from .util import print_error ca_path = requests.certs.where() from . import util from . import x509 from . import pem def Connection(server, queue, config_path): """Makes asynchronous connections to a remote electrum server. Returns the running thread that is making the connection. Once the thread has connected, it finishes, placing a tuple on the queue of the form (server, socket), where socket is None if connection failed. """ host, port, protocol = server.rsplit(':', 2) if not protocol in 'st': raise Exception('Unknown protocol: %s' % protocol) c = TcpConnection(server, queue, config_path) c.start() return c class TcpConnection(threading.Thread, util.PrintError): def __init__(self, server, queue, config_path): threading.Thread.__init__(self) self.config_path = config_path self.queue = queue self.server = server self.host, self.port, self.protocol = self.server.rsplit(':', 2) self.host = str(self.host) self.port = int(self.port) self.use_ssl = (self.protocol == 's') self.daemon = True def diagnostic_name(self): return self.host def check_host_name(self, peercert, name): """Simple certificate/host name checker. Returns True if the certificate matches, False otherwise. Does not support wildcards.""" # Check that the peer has supplied a certificate. # None/{} is not acceptable. if not peercert: return False if 'subjectAltName' in peercert: for typ, val in peercert["subjectAltName"]: if typ == "DNS" and val == name: return True else: # Only check the subject DN if there is no subject alternative # name. cn = None for attr, val in peercert["subject"]: # Use most-specific (last) commonName attribute. if attr == "commonName": cn = val if cn is not None: return cn == name return False def get_simple_socket(self): try: l = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM) except socket.gaierror: self.print_error("cannot resolve hostname") return e = None for res in l: try: s = socket.socket(res[0], socket.SOCK_STREAM) s.settimeout(10) s.connect(res[4]) s.settimeout(2) s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) return s except BaseException as _e: e = _e continue else: self.print_error("failed to connect", str(e)) @staticmethod def get_ssl_context(cert_reqs, ca_certs): context = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH, cafile=ca_certs) context.check_hostname = False context.verify_mode = cert_reqs context.options |= ssl.OP_NO_SSLv2 context.options |= ssl.OP_NO_SSLv3 context.options |= ssl.OP_NO_TLSv1 return context def get_socket(self): if self.use_ssl: cert_path = os.path.join(self.config_path, 'certs', self.host) if not os.path.exists(cert_path): is_new = True s = self.get_simple_socket() if s is None: return # try with CA first try: context = self.get_ssl_context(cert_reqs=ssl.CERT_REQUIRED, ca_certs=ca_path) s = context.wrap_socket(s, do_handshake_on_connect=True) except ssl.SSLError as e: self.print_error(e) s = None except: return if s and self.check_host_name(s.getpeercert(), self.host): self.print_error("SSL certificate signed by CA") return s # get server certificate. # Do not use ssl.get_server_certificate because it does not work with proxy s = self.get_simple_socket() if s is None: return try: context = self.get_ssl_context(cert_reqs=ssl.CERT_NONE, ca_certs=None) s = context.wrap_socket(s) except ssl.SSLError as e: self.print_error("SSL error retrieving SSL certificate:", e) return except: return dercert = s.getpeercert(True) s.close() cert = ssl.DER_cert_to_PEM_cert(dercert) # workaround android bug cert = re.sub("([^\n])-----END CERTIFICATE-----","\\1\n-----END CERTIFICATE-----",cert) temporary_path = cert_path + '.temp' with open(temporary_path,"w") as f: f.write(cert) else: is_new = False s = self.get_simple_socket() if s is None: return if self.use_ssl: try: context = self.get_ssl_context(cert_reqs=ssl.CERT_REQUIRED, ca_certs=(temporary_path if is_new else cert_path)) s = context.wrap_socket(s, do_handshake_on_connect=True) except socket.timeout: self.print_error('timeout') return except ssl.SSLError as e: self.print_error("SSL error:", e) if e.errno != 1: return if is_new: rej = cert_path + '.rej' if os.path.exists(rej): os.unlink(rej) os.rename(temporary_path, rej) else: with open(cert_path) as f: cert = f.read() try: b = pem.dePem(cert, 'CERTIFICATE') x = x509.X509(b) except: traceback.print_exc(file=sys.stderr) self.print_error("wrong certificate") return try: x.check_date() except: self.print_error("certificate has expired:", cert_path) os.unlink(cert_path) return self.print_error("wrong certificate") if e.errno == 104: return return except BaseException as e: self.print_error(e) traceback.print_exc(file=sys.stderr) return if is_new: self.print_error("saving certificate") os.rename(temporary_path, cert_path) return s def run(self): socket = self.get_socket() if socket: self.print_error("connected") self.queue.put((self.server, socket)) class Interface(util.PrintError): """The Interface class handles a socket connected to a single remote electrum server. It's exposed API is: - Member functions close(), fileno(), get_responses(), has_timed_out(), ping_required(), queue_request(), send_requests() - Member variable server. """ def __init__(self, server, socket): self.server = server self.host, _, _ = server.rsplit(':', 2) self.socket = socket self.pipe = util.SocketPipe(socket) self.pipe.set_timeout(0.0) # Don't wait for data # Dump network messages. Set at runtime from the console. self.debug = False self.unsent_requests = [] self.unanswered_requests = {} # Set last ping to zero to ensure immediate ping self.last_request = time.time() self.last_ping = 0 self.closed_remotely = False def diagnostic_name(self): return self.host def fileno(self): # Needed for select return self.socket.fileno() def close(self): if not self.closed_remotely: try: self.socket.shutdown(socket.SHUT_RDWR) except socket.error: pass self.socket.close() def queue_request(self, *args): # method, params, _id '''Queue a request, later to be send with send_requests when the socket is available for writing. ''' self.request_time = time.time() self.unsent_requests.append(args) def num_requests(self): '''Keep unanswered requests below 100''' n = 100 - len(self.unanswered_requests) return min(n, len(self.unsent_requests)) def send_requests(self): '''Sends queued requests. Returns False on failure.''' make_dict = lambda m, p, i: {'method': m, 'params': p, 'id': i} n = self.num_requests() wire_requests = self.unsent_requests[0:n] try: self.pipe.send_all([make_dict(*r) for r in wire_requests]) except socket.error as e: self.print_error("socket error:", e) return False self.unsent_requests = self.unsent_requests[n:] for request in wire_requests: if self.debug: self.print_error("-->", request) self.unanswered_requests[request[2]] = request return True def ping_required(self): '''Maintains time since last ping. Returns True if a ping should be sent. ''' now = time.time() if now - self.last_ping > 60: self.last_ping = now return True return False def has_timed_out(self): '''Returns True if the interface has timed out.''' if (self.unanswered_requests and time.time() - self.request_time > 10 and self.pipe.idle_time() > 10): self.print_error("timeout", len(self.unanswered_requests)) return True return False def get_responses(self): '''Call if there is data available on the socket. Returns a list of (request, response) pairs. Notifications are singleton unsolicited responses presumably as a result of prior subscriptions, so request is None and there is no 'id' member. Otherwise it is a response, which has an 'id' member and a corresponding request. If the connection was closed remotely or the remote server is misbehaving, a (None, None) will appear. ''' responses = [] while True: try: response = self.pipe.get() except util.timeout: break if not type(response) is dict: responses.append((None, None)) if response is None: self.closed_remotely = True self.print_error("connection closed remotely") break if self.debug: self.print_error("<--", response) wire_id = response.get('id', None) if wire_id is None: # Notification responses.append((None, response)) else: request = self.unanswered_requests.pop(wire_id, None) if request: responses.append((request, response)) else: self.print_error("unknown wire ID", wire_id) responses.append((None, None)) # Signal break return responses def check_cert(host, cert): try: b = pem.dePem(cert, 'CERTIFICATE') x = x509.X509(b) except: traceback.print_exc(file=sys.stdout) return try: x.check_date() expired = False except: expired = True m = "host: %s\n"%host m += "has_expired: %s\n"% expired util.print_msg(m) # Used by tests def _match_hostname(name, val): if val == name: return True return val.startswith('*.') and name.endswith(val[1:]) def test_certificates(): from .simple_config import SimpleConfig config = SimpleConfig() mydir = os.path.join(config.path, "certs") certs = os.listdir(mydir) for c in certs: p = os.path.join(mydir,c) with open(p) as f: cert = f.read() check_cert(c, cert) if __name__ == "__main__": test_certificates()
34.476543
103
0.563919
import os import re import socket import ssl import sys import threading import time import traceback import requests from .util import print_error ca_path = requests.certs.where() from . import util from . import x509 from . import pem def Connection(server, queue, config_path): host, port, protocol = server.rsplit(':', 2) if not protocol in 'st': raise Exception('Unknown protocol: %s' % protocol) c = TcpConnection(server, queue, config_path) c.start() return c class TcpConnection(threading.Thread, util.PrintError): def __init__(self, server, queue, config_path): threading.Thread.__init__(self) self.config_path = config_path self.queue = queue self.server = server self.host, self.port, self.protocol = self.server.rsplit(':', 2) self.host = str(self.host) self.port = int(self.port) self.use_ssl = (self.protocol == 's') self.daemon = True def diagnostic_name(self): return self.host def check_host_name(self, peercert, name): if not peercert: return False if 'subjectAltName' in peercert: for typ, val in peercert["subjectAltName"]: if typ == "DNS" and val == name: return True else: cn = None for attr, val in peercert["subject"]: if attr == "commonName": cn = val if cn is not None: return cn == name return False def get_simple_socket(self): try: l = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM) except socket.gaierror: self.print_error("cannot resolve hostname") return e = None for res in l: try: s = socket.socket(res[0], socket.SOCK_STREAM) s.settimeout(10) s.connect(res[4]) s.settimeout(2) s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) return s except BaseException as _e: e = _e continue else: self.print_error("failed to connect", str(e)) @staticmethod def get_ssl_context(cert_reqs, ca_certs): context = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH, cafile=ca_certs) context.check_hostname = False context.verify_mode = cert_reqs context.options |= ssl.OP_NO_SSLv2 context.options |= ssl.OP_NO_SSLv3 context.options |= ssl.OP_NO_TLSv1 return context def get_socket(self): if self.use_ssl: cert_path = os.path.join(self.config_path, 'certs', self.host) if not os.path.exists(cert_path): is_new = True s = self.get_simple_socket() if s is None: return try: context = self.get_ssl_context(cert_reqs=ssl.CERT_REQUIRED, ca_certs=ca_path) s = context.wrap_socket(s, do_handshake_on_connect=True) except ssl.SSLError as e: self.print_error(e) s = None except: return if s and self.check_host_name(s.getpeercert(), self.host): self.print_error("SSL certificate signed by CA") return s s = self.get_simple_socket() if s is None: return try: context = self.get_ssl_context(cert_reqs=ssl.CERT_NONE, ca_certs=None) s = context.wrap_socket(s) except ssl.SSLError as e: self.print_error("SSL error retrieving SSL certificate:", e) return except: return dercert = s.getpeercert(True) s.close() cert = ssl.DER_cert_to_PEM_cert(dercert) cert = re.sub("([^\n])-----END CERTIFICATE-----","\\1\n-----END CERTIFICATE-----",cert) temporary_path = cert_path + '.temp' with open(temporary_path,"w") as f: f.write(cert) else: is_new = False s = self.get_simple_socket() if s is None: return if self.use_ssl: try: context = self.get_ssl_context(cert_reqs=ssl.CERT_REQUIRED, ca_certs=(temporary_path if is_new else cert_path)) s = context.wrap_socket(s, do_handshake_on_connect=True) except socket.timeout: self.print_error('timeout') return except ssl.SSLError as e: self.print_error("SSL error:", e) if e.errno != 1: return if is_new: rej = cert_path + '.rej' if os.path.exists(rej): os.unlink(rej) os.rename(temporary_path, rej) else: with open(cert_path) as f: cert = f.read() try: b = pem.dePem(cert, 'CERTIFICATE') x = x509.X509(b) except: traceback.print_exc(file=sys.stderr) self.print_error("wrong certificate") return try: x.check_date() except: self.print_error("certificate has expired:", cert_path) os.unlink(cert_path) return self.print_error("wrong certificate") if e.errno == 104: return return except BaseException as e: self.print_error(e) traceback.print_exc(file=sys.stderr) return if is_new: self.print_error("saving certificate") os.rename(temporary_path, cert_path) return s def run(self): socket = self.get_socket() if socket: self.print_error("connected") self.queue.put((self.server, socket)) class Interface(util.PrintError): def __init__(self, server, socket): self.server = server self.host, _, _ = server.rsplit(':', 2) self.socket = socket self.pipe = util.SocketPipe(socket) self.pipe.set_timeout(0.0) # Dump network messages. Set at runtime from the console. self.debug = False self.unsent_requests = [] self.unanswered_requests = {} # Set last ping to zero to ensure immediate ping self.last_request = time.time() self.last_ping = 0 self.closed_remotely = False def diagnostic_name(self): return self.host def fileno(self): # Needed for select return self.socket.fileno() def close(self): if not self.closed_remotely: try: self.socket.shutdown(socket.SHUT_RDWR) except socket.error: pass self.socket.close() def queue_request(self, *args): # method, params, _id self.request_time = time.time() self.unsent_requests.append(args) def num_requests(self): n = 100 - len(self.unanswered_requests) return min(n, len(self.unsent_requests)) def send_requests(self): make_dict = lambda m, p, i: {'method': m, 'params': p, 'id': i} n = self.num_requests() wire_requests = self.unsent_requests[0:n] try: self.pipe.send_all([make_dict(*r) for r in wire_requests]) except socket.error as e: self.print_error("socket error:", e) return False self.unsent_requests = self.unsent_requests[n:] for request in wire_requests: if self.debug: self.print_error("-->", request) self.unanswered_requests[request[2]] = request return True def ping_required(self): now = time.time() if now - self.last_ping > 60: self.last_ping = now return True return False def has_timed_out(self): if (self.unanswered_requests and time.time() - self.request_time > 10 and self.pipe.idle_time() > 10): self.print_error("timeout", len(self.unanswered_requests)) return True return False def get_responses(self): responses = [] while True: try: response = self.pipe.get() except util.timeout: break if not type(response) is dict: responses.append((None, None)) if response is None: self.closed_remotely = True self.print_error("connection closed remotely") break if self.debug: self.print_error("<--", response) wire_id = response.get('id', None) if wire_id is None: # Notification responses.append((None, response)) else: request = self.unanswered_requests.pop(wire_id, None) if request: responses.append((request, response)) else: self.print_error("unknown wire ID", wire_id) responses.append((None, None)) # Signal break return responses def check_cert(host, cert): try: b = pem.dePem(cert, 'CERTIFICATE') x = x509.X509(b) except: traceback.print_exc(file=sys.stdout) return try: x.check_date() expired = False except: expired = True m = "host: %s\n"%host m += "has_expired: %s\n"% expired util.print_msg(m) # Used by tests def _match_hostname(name, val): if val == name: return True return val.startswith('*.') and name.endswith(val[1:]) def test_certificates(): from .simple_config import SimpleConfig config = SimpleConfig() mydir = os.path.join(config.path, "certs") certs = os.listdir(mydir) for c in certs: p = os.path.join(mydir,c) with open(p) as f: cert = f.read() check_cert(c, cert) if __name__ == "__main__": test_certificates()
true
true
f7fe83299a66644de31003a17d8b9e1d748891ee
1,334
py
Python
spanner/tests/system/utils/scrub_instances.py
jo2y/google-cloud-python
1b76727be16bc4335276f793340bb72d32be7166
[ "Apache-2.0" ]
1
2018-06-29T17:53:28.000Z
2018-06-29T17:53:28.000Z
spanner/tests/system/utils/scrub_instances.py
jo2y/google-cloud-python
1b76727be16bc4335276f793340bb72d32be7166
[ "Apache-2.0" ]
4
2018-11-13T22:15:36.000Z
2018-12-07T18:31:38.000Z
spanner/tests/system/utils/scrub_instances.py
jo2y/google-cloud-python
1b76727be16bc4335276f793340bb72d32be7166
[ "Apache-2.0" ]
1
2021-06-30T11:44:03.000Z
2021-06-30T11:44:03.000Z
# Copyright 2017 Google LLC All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from google.cloud.spanner import Client from .streaming_utils import INSTANCE_NAME as STREAMING_INSTANCE STANDARD_INSTANCE = 'google-cloud-python-systest' def scrub_instances(client): for instance in client.list_instances(): if instance.name == STREAMING_INSTANCE: print('Not deleting streaming instance: {}'.format( STREAMING_INSTANCE)) continue elif instance.name == STANDARD_INSTANCE: print('Not deleting standard instance: {}'.format( STANDARD_INSTANCE)) else: print("deleting instance: {}".format(instance.name)) instance.delete() if __name__ == '__main__': client = Client() scrub_instances(client)
35.105263
74
0.703148
from google.cloud.spanner import Client from .streaming_utils import INSTANCE_NAME as STREAMING_INSTANCE STANDARD_INSTANCE = 'google-cloud-python-systest' def scrub_instances(client): for instance in client.list_instances(): if instance.name == STREAMING_INSTANCE: print('Not deleting streaming instance: {}'.format( STREAMING_INSTANCE)) continue elif instance.name == STANDARD_INSTANCE: print('Not deleting standard instance: {}'.format( STANDARD_INSTANCE)) else: print("deleting instance: {}".format(instance.name)) instance.delete() if __name__ == '__main__': client = Client() scrub_instances(client)
true
true
f7fe8377430d72eab44fd5820adc26aa07a46ba2
6,769
py
Python
models/sequential_model.py
aasseman/mi-prometheus
c655c88cc6aec4d0724c19ea95209f1c2dd6770d
[ "Apache-2.0" ]
null
null
null
models/sequential_model.py
aasseman/mi-prometheus
c655c88cc6aec4d0724c19ea95209f1c2dd6770d
[ "Apache-2.0" ]
null
null
null
models/sequential_model.py
aasseman/mi-prometheus
c655c88cc6aec4d0724c19ea95209f1c2dd6770d
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (C) IBM Corporation 2018 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """sequential_model.py: contains base model for all sequential models""" __author__ = "Tomasz Kornuta" import numpy as np import logging import torch from models.model import Model from problems.problem import DataTuple class SequentialModel(Model): """ Class representing base class for all sequential models. Provides basic plotting functionality. """ def __init__(self, params): """ Initializes application state and sets plot if visualization flag is turned on. :param params: Parameters read from configuration file. """ super(SequentialModel, self).__init__(params) def plot(self, data_tuple, predictions, sample_number=0): """ Creates a default interactive visualization, with a slider enabling to move forth and back along the time axis (iteration in a given episode). The default visualizatoin contains input, output and target sequences. For more model/problem dependent visualization please overwrite this method in the derived model class. :param data_tuple: Data tuple containing - input [BATCH_SIZE x SEQUENCE_LENGTH x INPUT_DATA_SIZE] and - target sequences [BATCH_SIZE x SEQUENCE_LENGTH x OUTPUT_DATA_SIZE] :param predictions: Prediction sequence [BATCH_SIZE x SEQUENCE_LENGTH x OUTPUT_DATA_SIZE] :param sample_number: Number of sample in batch (DEFAULT: 0) """ # Check if we are supposed to visualize at all. if not self.app_state.visualize: return False # Initialize timePlot window - if required. if self.plotWindow is None: from utils.time_plot import TimePlot self.plotWindow = TimePlot() from matplotlib.figure import Figure import matplotlib.ticker as ticker # Change fonts globally - for all figures/subsplots at once. #from matplotlib import rc #rc('font', **{'family': 'Times New Roman'}) import matplotlib.pylab as pylab params = { # 'legend.fontsize': '28', 'axes.titlesize': 'large', 'axes.labelsize': 'large', 'xtick.labelsize': 'medium', 'ytick.labelsize': 'medium'} pylab.rcParams.update(params) # Create a single "figure layout" for all displayed frames. fig = Figure() axes = fig.subplots(3, 1, sharex=True, sharey=False, gridspec_kw={ 'width_ratios': [predictions.shape[0]]}) # Set ticks. axes[0].xaxis.set_major_locator(ticker.MaxNLocator(integer=True)) axes[0].yaxis.set_major_locator(ticker.MaxNLocator(integer=True)) axes[1].yaxis.set_major_locator(ticker.MaxNLocator(integer=True)) axes[2].yaxis.set_major_locator(ticker.MaxNLocator(integer=True)) # Set labels. axes[0].set_title('Inputs') axes[0].set_ylabel('Control/Data bits') axes[1].set_title('Targets') axes[1].set_ylabel('Data bits') axes[2].set_title('Predictions') axes[2].set_ylabel('Data bits') axes[2].set_xlabel('Item number') fig.set_tight_layout(True) # Detach a sample from batch and copy it to CPU. inputs_seq = data_tuple.inputs[sample_number].cpu().detach().numpy() targets_seq = data_tuple.targets[sample_number].cpu().detach().numpy() predictions_seq = predictions[sample_number].cpu().detach().numpy() # Create empty matrices. x = np.transpose(np.zeros(inputs_seq.shape)) y = np.transpose(np.zeros(predictions_seq.shape)) z = np.transpose(np.zeros(targets_seq.shape)) # Log sequence length - so the user can understand what is going on. logger = logging.getLogger('ModelBase') logger.info( "Generating dynamic visualization of {} figures, please wait...".format( inputs_seq.shape[0])) # Create frames - a list of lists, where each row is a list of artists # used to draw a given frame. frames = [] for i, (input_word, prediction_word, target_word) in enumerate( zip(inputs_seq, predictions_seq, targets_seq)): # Display information every 10% of figures. if (inputs_seq.shape[0] > 10) and (i % (inputs_seq.shape[0] // 10) == 0): logger.info( "Generating figure {}/{}".format(i, inputs_seq.shape[0])) # Add words to adequate positions. x[:, i] = input_word y[:, i] = target_word z[:, i] = prediction_word # Create "Artists" drawing data on "ImageAxes". artists = [None] * len(fig.axes) # Tell artists what to do;) artists[0] = axes[0].imshow( x, interpolation='nearest', aspect='auto') artists[1] = axes[1].imshow( y, interpolation='nearest', aspect='auto') artists[2] = axes[2].imshow( z, interpolation='nearest', aspect='auto') # Add "frame". frames.append(artists) # Plot figure and list of frames. self.plotWindow.update(fig, frames) # Return True if user closed the window. return self.plotWindow.is_closed if __name__ == '__main__': # Set logging level. logging.basicConfig(level=logging.DEBUG) # Set visualization. AppState().visualize = True # Test sequential model. test = SequentialModel() while True: # Generate new sequence. x = np.random.binomial(1, 0.5, (1, 8, 15)) y = np.random.binomial(1, 0.5, (1, 8, 15)) z = np.random.binomial(1, 0.5, (1, 8, 15)) # Transform to PyTorch. x = torch.from_numpy(x).type(torch.FloatTensor) y = torch.from_numpy(y).type(torch.FloatTensor) z = torch.from_numpy(z).type(torch.FloatTensor) dt = DataTuple(x, y) # Plot it and check whether window was closed or not. if test.plot(dt, z): break
36.589189
97
0.622987
__author__ = "Tomasz Kornuta" import numpy as np import logging import torch from models.model import Model from problems.problem import DataTuple class SequentialModel(Model): def __init__(self, params): super(SequentialModel, self).__init__(params) def plot(self, data_tuple, predictions, sample_number=0): if not self.app_state.visualize: return False if self.plotWindow is None: from utils.time_plot import TimePlot self.plotWindow = TimePlot() from matplotlib.figure import Figure import matplotlib.ticker as ticker import matplotlib.pylab as pylab params = { 'axes.titlesize': 'large', 'axes.labelsize': 'large', 'xtick.labelsize': 'medium', 'ytick.labelsize': 'medium'} pylab.rcParams.update(params) fig = Figure() axes = fig.subplots(3, 1, sharex=True, sharey=False, gridspec_kw={ 'width_ratios': [predictions.shape[0]]}) axes[0].xaxis.set_major_locator(ticker.MaxNLocator(integer=True)) axes[0].yaxis.set_major_locator(ticker.MaxNLocator(integer=True)) axes[1].yaxis.set_major_locator(ticker.MaxNLocator(integer=True)) axes[2].yaxis.set_major_locator(ticker.MaxNLocator(integer=True)) axes[0].set_title('Inputs') axes[0].set_ylabel('Control/Data bits') axes[1].set_title('Targets') axes[1].set_ylabel('Data bits') axes[2].set_title('Predictions') axes[2].set_ylabel('Data bits') axes[2].set_xlabel('Item number') fig.set_tight_layout(True) inputs_seq = data_tuple.inputs[sample_number].cpu().detach().numpy() targets_seq = data_tuple.targets[sample_number].cpu().detach().numpy() predictions_seq = predictions[sample_number].cpu().detach().numpy() x = np.transpose(np.zeros(inputs_seq.shape)) y = np.transpose(np.zeros(predictions_seq.shape)) z = np.transpose(np.zeros(targets_seq.shape)) logger = logging.getLogger('ModelBase') logger.info( "Generating dynamic visualization of {} figures, please wait...".format( inputs_seq.shape[0])) frames = [] for i, (input_word, prediction_word, target_word) in enumerate( zip(inputs_seq, predictions_seq, targets_seq)): if (inputs_seq.shape[0] > 10) and (i % (inputs_seq.shape[0] // 10) == 0): logger.info( "Generating figure {}/{}".format(i, inputs_seq.shape[0])) x[:, i] = input_word y[:, i] = target_word z[:, i] = prediction_word artists = [None] * len(fig.axes) artists[0] = axes[0].imshow( x, interpolation='nearest', aspect='auto') artists[1] = axes[1].imshow( y, interpolation='nearest', aspect='auto') artists[2] = axes[2].imshow( z, interpolation='nearest', aspect='auto') frames.append(artists) self.plotWindow.update(fig, frames) return self.plotWindow.is_closed if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) AppState().visualize = True test = SequentialModel() while True: x = np.random.binomial(1, 0.5, (1, 8, 15)) y = np.random.binomial(1, 0.5, (1, 8, 15)) z = np.random.binomial(1, 0.5, (1, 8, 15)) x = torch.from_numpy(x).type(torch.FloatTensor) y = torch.from_numpy(y).type(torch.FloatTensor) z = torch.from_numpy(z).type(torch.FloatTensor) dt = DataTuple(x, y) if test.plot(dt, z): break
true
true
f7fe8399b91c10eca23e3b1a1abbacc1912f9d54
1,591
py
Python
county_boundaries/python/main.py
CrunchyData/crunchy-foss4g-demodata
1d8f92a07faf9bc1c6468e00c8e9148ae2ba8dfc
[ "Apache-2.0" ]
9
2019-08-03T01:08:53.000Z
2021-12-30T21:01:28.000Z
county_boundaries/python/main.py
CrunchyData/crunchy-foss4g-demodata
1d8f92a07faf9bc1c6468e00c8e9148ae2ba8dfc
[ "Apache-2.0" ]
11
2019-04-04T13:56:29.000Z
2020-07-15T18:29:13.000Z
county_boundaries/python/main.py
CrunchyData/crunchy-foss4g-demodata
1d8f92a07faf9bc1c6468e00c8e9148ae2ba8dfc
[ "Apache-2.0" ]
2
2020-10-23T00:31:06.000Z
2020-12-26T10:38:31.000Z
import fiona from shapely.geometry import shape from shapely.geometry import Point from shapely.geometry import Polygon from shapely.geometry import MultiPolygon from shapely.wkb import dumps import pprint with fiona.open("../shapefile/tl_2018_us_county.shp", "r") as features: pprint.pprint(next(features)) pprint.pprint(features.crs) with open("../output/county_boundaries_copy.txt", "w") as output: for item in features: #pprint.pprint(item['id']) output.write('"'+ item['properties']['STATEFP'] + '","') output.write(item['properties']['COUNTYFP'] + '","') output.write(item['properties']['COUNTYNS'] + '","') output.write(item['properties']['GEOID'] + '","') output.write(item['properties']['NAME'] + '","') output.write(item['properties']['NAMELSAD'] + '","') output.write(item['properties']['FUNCSTAT'] + '",') output.write(str(item['properties']['ALAND']) + ',') output.write(str(item['properties']['AWATER']) + ',') lat = float(item['properties']['INTPTLAT']) lon = float(item['properties']['INTPTLON']) the_point = Point(lon, lat) output.write(dumps(the_point, hex=True) + ',') geom = None try: geom = MultiPolygon(item['geometry']) except: tempgeom = shape(item['geometry']) geom = MultiPolygon([tempgeom]) output.write(dumps(geom, hex=True)) output.write('\n') print("Done")
36.159091
71
0.568196
import fiona from shapely.geometry import shape from shapely.geometry import Point from shapely.geometry import Polygon from shapely.geometry import MultiPolygon from shapely.wkb import dumps import pprint with fiona.open("../shapefile/tl_2018_us_county.shp", "r") as features: pprint.pprint(next(features)) pprint.pprint(features.crs) with open("../output/county_boundaries_copy.txt", "w") as output: for item in features: output.write('"'+ item['properties']['STATEFP'] + '","') output.write(item['properties']['COUNTYFP'] + '","') output.write(item['properties']['COUNTYNS'] + '","') output.write(item['properties']['GEOID'] + '","') output.write(item['properties']['NAME'] + '","') output.write(item['properties']['NAMELSAD'] + '","') output.write(item['properties']['FUNCSTAT'] + '",') output.write(str(item['properties']['ALAND']) + ',') output.write(str(item['properties']['AWATER']) + ',') lat = float(item['properties']['INTPTLAT']) lon = float(item['properties']['INTPTLON']) the_point = Point(lon, lat) output.write(dumps(the_point, hex=True) + ',') geom = None try: geom = MultiPolygon(item['geometry']) except: tempgeom = shape(item['geometry']) geom = MultiPolygon([tempgeom]) output.write(dumps(geom, hex=True)) output.write('\n') print("Done")
true
true
f7fe83d525177aa784e9d88b687bc0ef6c672ca1
26,304
py
Python
src/consensus.py
isovic/samscripts
4b8c122220ee7bc5909903e3ecabb8ed6a72965d
[ "MIT" ]
4
2015-09-30T13:17:47.000Z
2019-03-13T14:25:15.000Z
src/consensus.py
isovic/samscripts
4b8c122220ee7bc5909903e3ecabb8ed6a72965d
[ "MIT" ]
5
2015-11-09T09:21:44.000Z
2016-08-18T09:18:44.000Z
src/consensus.py
isovic/samscripts
4b8c122220ee7bc5909903e3ecabb8ed6a72965d
[ "MIT" ]
6
2015-05-11T09:04:52.000Z
2020-06-08T21:47:51.000Z
#! /usr/bin/env python # Copyright Ivan Sovic, 2015. www.sovic.org # # Creates a pileup from a given SAM/BAM file, and calls consensus bases (or variants). import os; import sys; import operator; import subprocess; def increase_in_dict(dict_counter, value): try: dict_counter[value] += 1; except: dict_counter[value] = 1; def process_mpileup_line(line, line_number, ret_variant_list, ret_vcf_list, ret_snp_count, ret_insertion_count, ret_deletion_count, ret_num_undercovered_bases, ret_num_called_bases, ret_num_correct_bases, ret_coverage_sum, coverage_threshold, verbose=False): # Split the line, and perform a sanity check. split_line = line.strip().split('\t'); if (len(split_line) < 5 or len(split_line) > 6): sys.stderr.write(line + '\n'); return 0; ref_name = split_line[0]; position = split_line[1]; ref_base = split_line[2]; coverage = split_line[3]; original_bases = split_line[4]; if (len(split_line) == 6): qualities = split_line[5]; bases = ''; # Replace the '.' and ',' signs with the actual reference base. i = 0; while (i < len(original_bases)): if (original_bases[i] == '.' or original_bases[i] == ','): bases += ref_base; else: bases += original_bases[i]; i += 1; base_counts = {}; insertion_count = 0; current_base_deletion_count = 0; deletion_count = 0; insertion_event_counts = {}; deletion_event_counts = {}; end_counts = 0; # print 'position: %s' % position; # print 'bases: "%s"' % bases; # print 'line_number: %d' % line_number; # print line; # print ''; # sys.stdout.flush(); i = 0; while (i < len(bases)): base = bases[i]; if (base == r'^'): # This is the starting position of a read. It encodes two # symbols: '^' marking the read start and a char marking the # mapping quality of the read. #increase_in_dict(base_counts, bases[i + 1].upper()); i += 1; # Increase only by 1, because we have i += 1 down there. elif (base == r'$'): # This marks the end of a read. end_counts += 1; elif (base == r'*'): # This is a deletion, just count it. current_base_deletion_count += 1; elif (base == r'-'): # This marks the occurance of deletions. It is a composite object # consisting of: the special character '-', the number of the deleted bases # and the actual bases that are deleted (these bases follow the current position). # In our approach, we ignore this case, because we count deletions one by one # through the '*' character. # Get the number of bases that need to be skipped in the string. j = (i + 1); while (bases[j] in '0123456789'): j += 1; num_bases = int(bases[(i + 1):j]); skip_bases = (j - i) + num_bases - 1; deletion_count += 1; deletion = bases[j : (j + num_bases)].upper(); increase_in_dict(deletion_event_counts, deletion); # Skip the length of the numeric entry plus the actual number of bases # that need to be skipped. i += skip_bases; elif (base == r'+'): # This marks the occurance of an insertion. It is a composite object # consisting of: the special character '+', the number of the inserted bases # and the actual bases that are inserted (these bases follow the current position). # Similar to the deletion marking, but here we actually care about the bases, # and we need to make an allele aware count. # Get the number of bases that are inserted; j = (i + 1); while (bases[j] in '0123456789'): j += 1; num_bases = int(bases[(i + 1):j]); skip_bases = (j - i) + num_bases - 1; insertion_count += 1; insertion = bases[j : (j + num_bases)].upper(); increase_in_dict(insertion_event_counts, insertion); i += skip_bases; else: increase_in_dict(base_counts, bases[i].upper()); i += 1; # TODO: An additional problematic case, discovered this on 03.11.2014., when analyzing BWA-MEM's mpileup. # There are pileup bases that do not have any actual bases, but only the '*' symbols. How should this be handled properly? # Example line from the mpileup file: # gi|48994873|gb|U00096.2|_Escherichia_coli_str._K-12_substr._MG1655,_complete_genome 1938202 T 20 ******************** 8,2*#-;)$B>2$1&D- # I chose to handle them as undercovered bases. non_indel_coverage_current_base = int(coverage) - current_base_deletion_count; if (verbose == True): sys.stdout.write('%s\nbase_counts: %s\n' % (line.strip(), str(base_counts))); # EDIT: Previously I compared the total coverage of the current base with the coverage threshold. # However, the total coverage also accounts for the deletions denoted with the '*' sign, which I think # isn't relevant, as deletions are counted prior to occuring, and at that point is already decided if there is going # to be a deletion event. If we wound up at this base (i.e. this base didn't get skipped because of a deletion # consensus), then the deletions on this base are ignored. #if (int(coverage) < coverage_threshold or int(coverage) == current_base_deletion_count): # if (non_indel_coverage_current_base < coverage_threshold): if (int(coverage) < coverage_threshold): ret_num_undercovered_bases[0] += 1; # ret_coverage_sum[0] += 0; ret_coverage_sum[0] += int(coverage); # TODO: Should I count total coverage of this base, or the non_indel_coverage_current_base? sorted_base_counts = [['A', 0], ['C', 0], ['T', 0], ['G', 0]]; sorted_base_counts = sorted(base_counts.items(), key=operator.itemgetter(1)); try: most_common_base_count = sorted_base_counts[-1][1]; except Exception, e: most_common_base_count = 0; pass; #variant_line = 'undercovered1\tpos = %s\tcoverage = %d\tnon_indel_cov_curr = %d\tmost_common_base_count = %d\tref_base = %s\tcons_base = %s\tbase_counts = %s\tinsertion_counts = %s\tdeletion_counts = %s\t%s' % (position, int(coverage), non_indel_coverage_current_base, most_common_base_count, ref_base, sorted_base_counts[-1][0], str(sorted_base_counts), str(insertion_event_counts), str(deletion_event_counts), line.strip()); #ret_variant_list.append(variant_line); variant_line = 'undercovered1\tpos = %s\tref = %s\tcoverage = %d\tbase_counts = %s\tinsertion_counts = %s\tdeletion_counts = %s' % (position, ref_name, int(coverage), str(sorted_base_counts), str(insertion_event_counts), str(deletion_event_counts)); ret_variant_list.append(variant_line); ### VCF output ### qual = 1000; info = 'DP=%s;TYPE=snp' % (coverage); ref_field = ref_base; alt_field = 'N'; vcf_line = '%s\t%s\t.\t%s\t%s\t%d\tPASS\t%s' % (ref_name, position, ref_field, alt_field, qual, info); ret_vcf_list.append(vcf_line); ################## else: ret_num_called_bases[0] += 1; ret_coverage_sum[0] += int(coverage); # TODO: Should I count total coverage of this base, or the non_indel_coverage_current_base? most_common_base_count = 0; ### Handling base consensus. sorted_base_counts = sorted(base_counts.items(), key=operator.itemgetter(1)); try: most_common_base_count = sorted_base_counts[-1][1]; except Exception, e: pass; # sys.stderr.write(str(e) + '\n'); # sys.stderr.write('sorted_base_counts:\n'); # sys.stderr.write(str(sorted_base_counts) + '\n'); # sys.stderr.write('base_counts:\n'); # sys.stderr.write(str(base_counts) + '\n'); # sys.stderr.write('original_bases:\n'); # sys.stderr.write(str(original_bases) + '\n'); # sys.stderr.write('line:\n'); # sys.stderr.write(line.strip() + '\n'); # most_common_base_count = 0; # Allow for the case where there are multiple equally good choices. # In this case, we prefer the choice which is equal to the reference. is_good = False; for base_count in sorted_base_counts: if (base_count[1] == most_common_base_count): if (base_count[0] == ref_base): is_good = True; break; if (is_good == False): if (len(sorted_base_counts) > 0): ret_snp_count[0] += 1; # ret_variant_list.append(line_number); variant_line = 'SNP\tpos = %s\tref = %s\tcoverage = %d\tnon_indel_cov_curr = %d\tmost_common_base_count = %d\tref_base = %s\tcons_base = %s\tbase_counts = %s\tinsertion_counts = %s\tdeletion_counts = %s\t%s' % (position, ref_name, int(coverage), non_indel_coverage_current_base, most_common_base_count, ref_base, ('{}') if (len(sorted_base_counts) == 0) else (str(sorted_base_counts[-1][0])), str(sorted_base_counts), str(insertion_event_counts), str(deletion_event_counts), line.strip()); ret_variant_list.append(variant_line); ### VCF output ### alt_base = ('{}') if (len(sorted_base_counts) == 0) else (str(sorted_base_counts[-1][0])); qual = 1000; info = 'DP=%s;TYPE=snp' % (coverage); ref_field = ref_base; alt_field = alt_base; vcf_line = '%s\t%s\t.\t%s\t%s\t%d\tPASS\t%s' % (ref_name, position, ref_field, alt_field, qual, info); ret_vcf_list.append(vcf_line); ################## else: sys.stderr.write('\nWarning: a SNP was detected, but there were no bases in the sorted_base_counts!') variant_line = 'SNP\tpos = %s\tref = %s\tcoverage = %d\tnon_indel_cov_curr = %d\tmost_common_base_count = %d\tref_base = %s\tcons_base = %s\tbase_counts = %s\tinsertion_counts = %s\tdeletion_counts = %s\t%s' % (position, ref_name, int(coverage), non_indel_coverage_current_base, most_common_base_count, ref_base, ('{}') if (len(sorted_base_counts) == 0) else (str(sorted_base_counts[-1][0])), str(sorted_base_counts), str(insertion_event_counts), str(deletion_event_counts), line.strip()); sys.stderr.write('\n'); else: ret_num_correct_bases[0] += 1; if (verbose == True): sys.stdout.write('Reference base: %s\n' % (ref_base)); sys.stdout.write('Consensus base: %s\n\n' % (base_count[0])); #if (int(position) == 100000 or int(position) == 1000000 or int(position) == 2000000 or int(position) == 3000000 or int(position) == 4000000): #print '\nTEST\tpos = %s\tcoverage = %d\tnon_indel_cov_curr = %d\tmost_common_base_count = %d\tref_base = %s\tcons_base = %s\tbase_counts = %s\tinsertion_counts = %s\tdeletion_counts = %s\t%s\n' % (position, int(coverage), non_indel_coverage_current_base, most_common_base_count, ref_base, sorted_base_counts[-1][0], str(sorted_base_counts), str(insertion_event_counts), str(deletion_event_counts), line.strip()); ### Handling indel consensus. ### Put a different coverage threshold. Here we are interested even in the reads ### which had a '*' at the current position (because we don't know where it ends). non_indel_coverage_next_base = int(coverage) - end_counts - deletion_count - insertion_count; if ((non_indel_coverage_next_base + deletion_count + insertion_count) > coverage_threshold): # Sanity check, just to see if there actually were any insertions (to avoid index out of bounds error). # If there are insertions, get the most common one. if (len(insertion_event_counts.keys()) > 0): sorted_insertion_counts = sorted(insertion_event_counts.items(), key=operator.itemgetter(1)); most_common_insertion_count = sorted_insertion_counts[-1][1]; most_common_insertion_length = len(sorted_insertion_counts[-1][0]); insertion_unique = True if (sum([int(insertion_count[1] == most_common_insertion_count) for insertion_count in sorted_insertion_counts]) == 1) else False; else: most_common_insertion_count = 0; most_common_insertion_length = 0; insertion_unique = False; # Sanity check, just to see if there actually were any deletions (to avoid index out of bounds error). # If there are deletions, get the most common one. if (len(deletion_event_counts.keys()) > 0): sorted_deletion_counts = sorted(deletion_event_counts.items(), key=operator.itemgetter(1)); most_common_deletion_count = sorted_deletion_counts[-1][1]; most_common_deletion_length = len(sorted_deletion_counts[-1][0]); deletion_unique = True if (sum([int(deletion_count[1] == most_common_deletion_count) for deletion_count in sorted_deletion_counts]) == 1) else False; else: most_common_deletion_count = 0; most_common_deletion_length = 0; deletion_unique = False; if (most_common_insertion_count > most_common_deletion_count and most_common_insertion_count > non_indel_coverage_next_base): # In this case, insertions are a clear winner. if (insertion_unique == True): #ret_insertion_count[0] += most_common_insertion_length; ret_insertion_count[0] += 1; ret_num_called_bases[0] += most_common_insertion_length; #variant_line = 'insertion\t%d\t%s\t%s\t%s\t%s' % (most_common_insertion_count, str(sorted_base_counts), str(insertion_event_counts), str(deletion_event_counts), line.strip()); #ret_variant_list.append(variant_line); try: temp_sorted_bc = sorted_base_counts[-1][0]; except: temp_sorted_bc = 0; indel_length = most_common_insertion_length; variant_line = 'ins\tpos = %s\tref = %s\tnon_indel_cov_next = %d\tnon_indel_cov_curr = %d\tmost_common_insertion_count = %d\tref_base = %s\tcons_base = %s\tbase_counts = %s\tinsertion_counts = %s\tdeletion_counts = %s\t%s' % (position, ref_name, non_indel_coverage_next_base, non_indel_coverage_current_base, most_common_insertion_count, ref_base, temp_sorted_bc, str(sorted_base_counts), str(insertion_event_counts), str(deletion_event_counts), line.strip()); ret_variant_list.append(variant_line); ### Insertions in the VCF format specifies the position where a insertion occurs. The ref position should contain the base which is the same as ref, but the alt field contains the ref base + the insertion event. ### VCF output ### alt_base = ('{}') if (len(sorted_base_counts) == 0) else (str(sorted_base_counts[-1][0])); qual = 1000; info = 'DP=%s;TYPE=ins' % (coverage); ref_field = ref_base; alt_field = '%s%s' % (ref_base, sorted_insertion_counts[-1][0]); vcf_line = '%s\t%s\t.\t%s\t%s\t%d\tPASS\t%s' % (ref_name, position, ref_field, alt_field, qual, info); ret_vcf_list.append(vcf_line); ################## elif (most_common_deletion_count > most_common_insertion_count and most_common_deletion_count > non_indel_coverage_next_base): # In this case, deletions are a clear winner. if (deletion_unique == True): #ret_deletion_count[0] += most_common_deletion_length; ret_deletion_count[0] += 1; #variant_line = 'deletion\t%d\t%s\t%s\t%s\t%s' % (most_common_deletion_count, str(sorted_base_counts), str(insertion_event_counts), str(deletion_event_counts), line.strip()); #ret_variant_list.append(variant_line); #return most_common_deletion_length; variant_line = 'del\tpos = %s\tref = %s\tnon_indel_cov_next = %d\tnon_indel_cov_curr = %d\tmost_common_deletion_count = %d\tref_base = %s\tcons_base = %s\tbase_counts = %s\tinsertion_counts = %s\tdeletion_counts = %s\t%s' % (position, ref_name, non_indel_coverage_next_base, non_indel_coverage_current_base, most_common_deletion_count, ref_base, sorted_base_counts[-1][0], str(sorted_base_counts), str(insertion_event_counts), str(deletion_event_counts), line.strip()); ret_variant_list.append(variant_line); ### Deletions in the VCF format specifies the position where a deletion occurs, with the first base being non-deletion, and the following bases being a deletion event. ### VCF output ### alt_base = ('{}') if (len(sorted_base_counts) == 0) else (str(sorted_base_counts[-1][0])); qual = 1000; info = 'DP=%s;TYPE=del' % (coverage); ref_field = '%s%s' % (ref_base, sorted_deletion_counts[-1][0]); alt_field = ref_base; vcf_line = '%s\t%s\t.\t%s\t%s\t%d\tPASS\t%s' % (ref_name, position, ref_field, alt_field, qual, info); ret_vcf_list.append(vcf_line); ################## return most_common_deletion_length; else: # In this case, either the base count consensus wins, or the # insertion/deletion count is ambiguous. pass; return 0; def process_mpileup(alignments_path, reference_path, mpileup_path, coverage_threshold, output_prefix, thread_id=0, bed_position=''): fp = None; try: fp = open(mpileup_path, 'r'); except IOError: sys.stderr.write('ERROR: Could not open file "%s" for reading!\n' % mpileup_path); return None; ret_variant_list = []; ret_vcf_list = []; ret_snp_count = [0]; ret_insertion_count = [0]; ret_deletion_count = [0]; ret_num_undercovered_bases = [0]; ret_num_called_bases = [0]; ret_num_correct_bases = [0]; ret_coverage_sum = [0]; # lines = fp.readlines(); fp_variant = None; fp_vcf = None; if (output_prefix != ''): if (not os.path.exists(os.path.dirname(output_prefix))): os.makedirs(os.path.dirname(output_prefix)); variant_file = ('%s-cov_%d.variant.csv' % (output_prefix, coverage_threshold)); fp_variant = open(variant_file, 'w'); vcf_file = ('%s-cov_%d.variant.vcf' % (output_prefix, coverage_threshold)); fp_vcf = open(vcf_file, 'w'); fp_vcf.write('##fileformat=VCFv4.0\n'); fp_vcf.write('##fileDate=20150409\n'); fp_vcf.write('##source=%s\n' % (' '.join(sys.argv))); fp_vcf.write('##reference=%s\n' % reference_path); fp_vcf.write('##INFO=<ID=DP,Number=1,Type=Integer,Description="Raw Depth">\n'); fp_vcf.write('##INFO=<ID=TYPE,Number=A,Type=String,Description="Type of each allele (snp, ins, del, mnp, complex)">\n'); fp_vcf.write('##INFO=<ID=AF,Number=1,Type=Float,Description="Allele Frequency">\n'); fp_vcf.write('##INFO=<ID=SB,Number=1,Type=Integer,Description="Phred-scaled strand bias at this position">\n'); fp_vcf.write('##INFO=<ID=DP4,Number=4,Type=Integer,Description="Counts for ref-forward bases, ref-reverse, alt-forward and alt-reverse bases">\n'); fp_vcf.write('##INFO=<ID=INDEL,Number=0,Type=Flag,Description="Indicates that the variant is an INDEL.">\n'); fp_vcf.write('##INFO=<ID=CONSVAR,Number=0,Type=Flag,Description="Indicates that the variant is a consensus variant (as opposed to a low frequency variant).">\n'); fp_vcf.write('##INFO=<ID=HRUN,Number=1,Type=Integer,Description="Homopolymer length to the right of report indel position">\n'); fp_vcf.write('#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n'); fp_vcf.flush(); use_bed = False; bed_chromosome = ""; bed_pos_start = 0; # bed_pos_end = len(lines); bed_pos_end = -1; if (bed_position != ""): bed_split = bed_position.split(':'); if (len(bed_split) != 2): use_bed = False; else: bed_chromosome = bed_split[0]; bed_pos_split = bed_split[1].split('-'); if (len(bed_pos_split) != 2): use_bed = False; else: bed_pos_start = int(bed_pos_split[0]); bed_pos_end = int(bed_pos_split[1]); use_bed = True; sys.stderr.write('Using location specified through commandline:\n'); sys.stderr.write('\tChromosome: "%s"\n' % bed_chromosome); sys.stderr.write('\tStart: %d\n' % bed_pos_start); sys.stderr.write('\tEnd: %d\n\n' % bed_pos_end); # i = 0; i = 0 if (use_bed == False) else max((bed_pos_start - 10), 0); j = 0; # while (i < bed_pos_end): # len(lines)): num_bases_to_skip = 0; for line in fp: # line = lines[i]; if (num_bases_to_skip > 0): num_bases_to_skip -= 1; continue; if (use_bed == True): line_split = line.strip().split('\t'); if (len(line_split) > 2 and line_split[0] == bed_chromosome): current_pos = int(line_split[1]); if (current_pos < bed_pos_start or current_pos >= bed_pos_end): i += 1; j += 1; continue; else: # print line_split[0]; # print bed_chromosome; i += 1; j += 1; continue; if (thread_id == 0): if ((j % 1000) == 0): sys.stderr.write('\r[%d] snps = %d, insertions = %d, deletions = %d, undercovered = %d, coverage = %.2f' % (i, ret_snp_count[0], ret_insertion_count[0], ret_deletion_count[0], ret_num_undercovered_bases[0], (float(ret_coverage_sum[0])/float((i + 1))))); sys.stderr.flush(); variant_list_length = len(ret_variant_list); vcf_list_length = len(ret_vcf_list); num_bases_to_skip = process_mpileup_line(line, i, ret_variant_list, ret_vcf_list, ret_snp_count, ret_insertion_count, ret_deletion_count, ret_num_undercovered_bases, ret_num_called_bases, ret_num_correct_bases, ret_coverage_sum, coverage_threshold, verbose=use_bed); if (len(ret_variant_list) > variant_list_length and fp_variant != None): fp_variant.write('\n'.join(ret_variant_list[variant_list_length:]) + '\n'); fp_variant.flush(); if (len(ret_vcf_list) > vcf_list_length and fp_vcf != None): fp_vcf.write('\n'.join(ret_vcf_list[vcf_list_length:]) + '\n'); fp_vcf.flush(); i += num_bases_to_skip; i += 1; j += 1; #if (i > 10000): #break; fp.close(); sys.stderr.write('\n') if (fp_variant != None): fp_variant.close(); if (fp_vcf != None): fp_vcf.close(); summary_lines = ''; summary_lines += 'alignments_file: %s\n' % alignments_path; summary_lines += 'mpileup_file: %s\n' % mpileup_path; summary_lines += 'coverage_threshold: %d\n' % coverage_threshold; summary_lines += 'snp_count: %d\n' % ret_snp_count[0]; summary_lines += 'insertion_count: %d\n' % ret_insertion_count[0]; summary_lines += 'deletion_count: %d\n' % ret_deletion_count[0]; summary_lines += 'num_undercovered_bases: %d\n' % ret_num_undercovered_bases[0]; summary_lines += 'num_called_bases: %d\n' % ret_num_called_bases[0]; summary_lines += 'num_correct_bases: %d\n' % ret_num_correct_bases[0]; summary_lines += 'average_coverage: %.2f\n' % ((float(ret_coverage_sum[0])/float((i + 1)))); sys.stderr.write(summary_lines + '\n'); sys.stderr.write('\n'); if (output_prefix != ''): #summary_file = output_prefix + '.conssum'; summary_file = ('%s-cov_%d.variant.sum' % (output_prefix, coverage_threshold)); try: fp_sum = open(summary_file, 'w'); fp_sum.write(summary_lines); fp_sum.close(); return summary_file; except IOError: sys.stderr.write('ERROR: Could not open file "%s" for writing!\n' % (summary_file)); return None; return None; def main(alignments_path, reference_path, coverage_threshold, output_prefix, thread_id=0, bed_position=""): # Sanity checking the existence of the file, and the correctness of its extension. # Also, if input file is a SAM file, then convert it to a sorted BAM. alignments_path_bam = alignments_path; if (os.path.exists(alignments_path) == False): sys.stderr.write('ERROR: File "%s" does not exist!\n' % alignments_path); return; if (alignments_path.endswith('sam')): # Determine the path where the new BAM file will be generated. dir_name = os.path.dirname(alignments_path); if (dir_name == ''): dir_name = '.'; alignments_path_bam = dir_name + '/' + os.path.splitext(os.path.basename(alignments_path))[0] + '.bam' alignments_path_bam_exists = os.path.exists(alignments_path_bam); # Check if a BAM file with the given name already exists. if (alignments_path_bam_exists == False or (alignments_path_bam_exists == True and os.path.getmtime(alignments_path) > os.path.getmtime(alignments_path_bam))): # Convert the SAM file to a sorted BAM file. command = 'samtools view -bS %s | samtools sort - %s' % (alignments_path, os.path.splitext(alignments_path_bam)[0]); sys.stderr.write(command + '\n') subprocess.call(command, shell='True'); # Create the BAM index file. command = 'samtools index %s %s.bai' % (alignments_path_bam, alignments_path_bam); subprocess.call(command, shell='True'); elif (alignments_path.endswith('bam') == False): sys.stderr.write('ERROR: File extension needs to be either .sam or .bam! Input file path: "%s".\n' % alignments_path); return; # Convert the sorted BAM file to a mpileup file if it doesn't exist yet. mpileup_path = ('%s.mpileup' % alignments_path_bam); mpileup_exists = os.path.exists(mpileup_path); if (mpileup_exists == False or (mpileup_exists == True and os.path.getmtime(alignments_path) > os.path.getmtime(mpileup_path))): command = 'samtools mpileup -B -d 1000000 -Q 0 -A -f %s %s > %s.mpileup' % (reference_path, alignments_path_bam, alignments_path_bam); subprocess.call(command, shell='True'); sys.stderr.write('Processing file "%s"...\n' % alignments_path); sys.stderr.write('Reference file "%s"...\n' % reference_path); sys.stderr.write('Coverage threshold: %d\n' % coverage_threshold); summary_file = process_mpileup(alignments_path, reference_path, ('%s.mpileup' % alignments_path_bam), coverage_threshold, output_prefix, thread_id, bed_position); def CollectSummaries(sam_files, prefix_for_intermediate_results, collective_output_file): fp_collect = None; try: fp_collect = open(collective_output_file, 'w'); except IOError: sys.stderr.write('ERROR: Could not open file "%s" for writing!\n' % collective_output_file); return; for sam_file in sam_files: summary_file = prefix_for_intermediate_results + '.sum'; try: fp_sum = open(summary_file, 'r'); lines = fp_sum.readlines(); fp_sum.close(); except IOError: sys.stderr.write('ERROR: Could not open file "%s" for reading!\n' % summary_file); continue; fp_collect.write(''.join(lines) + '\n'); fp_collect.close(); if __name__ == "__main__": # if (len(sys.argv) < 5): # sys.stderr.write('Usage:\n'); # sys.stderr.write('\t%s <reference_file_path> coverage_threshold <collective_output_file> <{sb}am_file_1> [<{sb}am_file_2> <{sb}am_file_3> ...]\n' % sys.argv[0]); # sys.stderr.write('\t(If <collective_output_file> is equal to "-", no files will be written to disk.)\n'); # exit(1); if (len(sys.argv) < 5): sys.stderr.write('Usage:\n'); sys.stderr.write('\t%s <reference_file_path> coverage_threshold <output_prefix> <{sb}am_file_> [position]\n' % sys.argv[0]); sys.stderr.write('\t(If <collective_output_file> is equal to "-", no files will be written to disk.)\n'); sys.stderr.write('\tPosition parameter is a string specifying "chromosome:start-end"\n\n'); exit(1); reference_file = sys.argv[1]; coverage_threshold = int(sys.argv[2]); output_prefix = sys.argv[3]; sam_file = sys.argv[4]; bed_position = ''; if (len(sys.argv) > 5): bed_position = sys.argv[5]; # sys.stderr.write('bed_position: "%s"\n\n' % bed_position); processes = []; if (output_prefix == '-'): output_prefix = os.path.splitext(sam_file)[0]; main(sam_file, reference_file, coverage_threshold, output_prefix, 0, bed_position); # if (output_prefix != '-'): # CollectSummaries([sam_file], output_prefix, output_prefix + '.variant.sum');
46.555752
493
0.701718
import os; import sys; import operator; import subprocess; def increase_in_dict(dict_counter, value): try: dict_counter[value] += 1; except: dict_counter[value] = 1; def process_mpileup_line(line, line_number, ret_variant_list, ret_vcf_list, ret_snp_count, ret_insertion_count, ret_deletion_count, ret_num_undercovered_bases, ret_num_called_bases, ret_num_correct_bases, ret_coverage_sum, coverage_threshold, verbose=False): split_line = line.strip().split('\t'); if (len(split_line) < 5 or len(split_line) > 6): sys.stderr.write(line + '\n'); return 0; ref_name = split_line[0]; position = split_line[1]; ref_base = split_line[2]; coverage = split_line[3]; original_bases = split_line[4]; if (len(split_line) == 6): qualities = split_line[5]; bases = ''; i = 0; while (i < len(original_bases)): if (original_bases[i] == '.' or original_bases[i] == ','): bases += ref_base; else: bases += original_bases[i]; i += 1; base_counts = {}; insertion_count = 0; current_base_deletion_count = 0; deletion_count = 0; insertion_event_counts = {}; deletion_event_counts = {}; end_counts = 0; i = 0; while (i < len(bases)): base = bases[i]; if (base == r'^'): i += 1; elif (base == r'$'): end_counts += 1; elif (base == r'*'): current_base_deletion_count += 1; elif (base == r'-'): j = (i + 1); while (bases[j] in '0123456789'): j += 1; num_bases = int(bases[(i + 1):j]); skip_bases = (j - i) + num_bases - 1; deletion_count += 1; deletion = bases[j : (j + num_bases)].upper(); increase_in_dict(deletion_event_counts, deletion); i += skip_bases; elif (base == r'+'): j = (i + 1); while (bases[j] in '0123456789'): j += 1; num_bases = int(bases[(i + 1):j]); skip_bases = (j - i) + num_bases - 1; insertion_count += 1; insertion = bases[j : (j + num_bases)].upper(); increase_in_dict(insertion_event_counts, insertion); i += skip_bases; else: increase_in_dict(base_counts, bases[i].upper()); i += 1; # There are pileup bases that do not have any actual bases, but only the '*' symbols. How should this be handled properly? # Example line from the mpileup file: # gi|48994873|gb|U00096.2|_Escherichia_coli_str._K-12_substr._MG1655,_complete_genome 1938202 T 20 ******************** 8,2*#-;)$B>2$1&D- # I chose to handle them as undercovered bases. non_indel_coverage_current_base = int(coverage) - current_base_deletion_count; if (verbose == True): sys.stdout.write('%s\nbase_counts: %s\n' % (line.strip(), str(base_counts))); # EDIT: Previously I compared the total coverage of the current base with the coverage threshold. # However, the total coverage also accounts for the deletions denoted with the '*' sign, which I think # isn't relevant, as deletions are counted prior to occuring, and at that point is already decided if there is going # consensus), then the deletions on this base are ignored. #if (int(coverage) < coverage_threshold or int(coverage) == current_base_deletion_count): # if (non_indel_coverage_current_base < coverage_threshold): if (int(coverage) < coverage_threshold): ret_num_undercovered_bases[0] += 1; # ret_coverage_sum[0] += 0; ret_coverage_sum[0] += int(coverage); # TODO: Should I count total coverage of this base, or the non_indel_coverage_current_base? sorted_base_counts = [['A', 0], ['C', 0], ['T', 0], ['G', 0]]; sorted_base_counts = sorted(base_counts.items(), key=operator.itemgetter(1)); try: most_common_base_count = sorted_base_counts[-1][1]; except Exception, e: most_common_base_count = 0; pass; #variant_line = 'undercovered1\tpos = %s\tcoverage = %d\tnon_indel_cov_curr = %d\tmost_common_base_count = %d\tref_base = %s\tcons_base = %s\tbase_counts = %s\tinsertion_counts = %s\tdeletion_counts = %s\t%s' % (position, int(coverage), non_indel_coverage_current_base, most_common_base_count, ref_base, sorted_base_counts[-1][0], str(sorted_base_counts), str(insertion_event_counts), str(deletion_event_counts), line.strip()); #ret_variant_list.append(variant_line); variant_line = 'undercovered1\tpos = %s\tref = %s\tcoverage = %d\tbase_counts = %s\tinsertion_counts = %s\tdeletion_counts = %s' % (position, ref_name, int(coverage), str(sorted_base_counts), str(insertion_event_counts), str(deletion_event_counts)); ret_variant_list.append(variant_line); ### VCF output ### qual = 1000; info = 'DP=%s;TYPE=snp' % (coverage); ref_field = ref_base; alt_field = 'N'; vcf_line = '%s\t%s\t.\t%s\t%s\t%d\tPASS\t%s' % (ref_name, position, ref_field, alt_field, qual, info); ret_vcf_list.append(vcf_line); ################## else: ret_num_called_bases[0] += 1; ret_coverage_sum[0] += int(coverage); # TODO: Should I count total coverage of this base, or the non_indel_coverage_current_base? most_common_base_count = 0; ### Handling base consensus. sorted_base_counts = sorted(base_counts.items(), key=operator.itemgetter(1)); try: most_common_base_count = sorted_base_counts[-1][1]; except Exception, e: pass; # sys.stderr.write(str(e) + '\n'); # sys.stderr.write('sorted_base_counts:\n'); # sys.stderr.write(str(sorted_base_counts) + '\n'); # sys.stderr.write('base_counts:\n'); # sys.stderr.write(str(base_counts) + '\n'); # sys.stderr.write('original_bases:\n'); # sys.stderr.write(str(original_bases) + '\n'); # sys.stderr.write('line:\n'); # sys.stderr.write(line.strip() + '\n'); # most_common_base_count = 0; # Allow for the case where there are multiple equally good choices. # In this case, we prefer the choice which is equal to the reference. is_good = False; for base_count in sorted_base_counts: if (base_count[1] == most_common_base_count): if (base_count[0] == ref_base): is_good = True; break; if (is_good == False): if (len(sorted_base_counts) > 0): ret_snp_count[0] += 1; # ret_variant_list.append(line_number); variant_line = 'SNP\tpos = %s\tref = %s\tcoverage = %d\tnon_indel_cov_curr = %d\tmost_common_base_count = %d\tref_base = %s\tcons_base = %s\tbase_counts = %s\tinsertion_counts = %s\tdeletion_counts = %s\t%s' % (position, ref_name, int(coverage), non_indel_coverage_current_base, most_common_base_count, ref_base, ('{}') if (len(sorted_base_counts) == 0) else (str(sorted_base_counts[-1][0])), str(sorted_base_counts), str(insertion_event_counts), str(deletion_event_counts), line.strip()); ret_variant_list.append(variant_line); ### VCF output ### alt_base = ('{}') if (len(sorted_base_counts) == 0) else (str(sorted_base_counts[-1][0])); qual = 1000; info = 'DP=%s;TYPE=snp' % (coverage); ref_field = ref_base; alt_field = alt_base; vcf_line = '%s\t%s\t.\t%s\t%s\t%d\tPASS\t%s' % (ref_name, position, ref_field, alt_field, qual, info); ret_vcf_list.append(vcf_line); ################## else: sys.stderr.write('\nWarning: a SNP was detected, but there were no bases in the sorted_base_counts!') variant_line = 'SNP\tpos = %s\tref = %s\tcoverage = %d\tnon_indel_cov_curr = %d\tmost_common_base_count = %d\tref_base = %s\tcons_base = %s\tbase_counts = %s\tinsertion_counts = %s\tdeletion_counts = %s\t%s' % (position, ref_name, int(coverage), non_indel_coverage_current_base, most_common_base_count, ref_base, ('{}') if (len(sorted_base_counts) == 0) else (str(sorted_base_counts[-1][0])), str(sorted_base_counts), str(insertion_event_counts), str(deletion_event_counts), line.strip()); sys.stderr.write('\n'); else: ret_num_correct_bases[0] += 1; if (verbose == True): sys.stdout.write('Reference base: %s\n' % (ref_base)); sys.stdout.write('Consensus base: %s\n\n' % (base_count[0])); #if (int(position) == 100000 or int(position) == 1000000 or int(position) == 2000000 or int(position) == 3000000 or int(position) == 4000000): #print '\nTEST\tpos = %s\tcoverage = %d\tnon_indel_cov_curr = %d\tmost_common_base_count = %d\tref_base = %s\tcons_base = %s\tbase_counts = %s\tinsertion_counts = %s\tdeletion_counts = %s\t%s\n' % (position, int(coverage), non_indel_coverage_current_base, most_common_base_count, ref_base, sorted_base_counts[-1][0], str(sorted_base_counts), str(insertion_event_counts), str(deletion_event_counts), line.strip()); ### Handling indel consensus. ### Put a different coverage threshold. Here we are interested even in the reads ### which had a '*' at the current position (because we don't know where it ends). non_indel_coverage_next_base = int(coverage) - end_counts - deletion_count - insertion_count; if ((non_indel_coverage_next_base + deletion_count + insertion_count) > coverage_threshold): if (len(insertion_event_counts.keys()) > 0): sorted_insertion_counts = sorted(insertion_event_counts.items(), key=operator.itemgetter(1)); most_common_insertion_count = sorted_insertion_counts[-1][1]; most_common_insertion_length = len(sorted_insertion_counts[-1][0]); insertion_unique = True if (sum([int(insertion_count[1] == most_common_insertion_count) for insertion_count in sorted_insertion_counts]) == 1) else False; else: most_common_insertion_count = 0; most_common_insertion_length = 0; insertion_unique = False; if (len(deletion_event_counts.keys()) > 0): sorted_deletion_counts = sorted(deletion_event_counts.items(), key=operator.itemgetter(1)); most_common_deletion_count = sorted_deletion_counts[-1][1]; most_common_deletion_length = len(sorted_deletion_counts[-1][0]); deletion_unique = True if (sum([int(deletion_count[1] == most_common_deletion_count) for deletion_count in sorted_deletion_counts]) == 1) else False; else: most_common_deletion_count = 0; most_common_deletion_length = 0; deletion_unique = False; if (most_common_insertion_count > most_common_deletion_count and most_common_insertion_count > non_indel_coverage_next_base): if (insertion_unique == True): ret_insertion_count[0] += 1; ret_num_called_bases[0] += most_common_insertion_length; try: temp_sorted_bc = sorted_base_counts[-1][0]; except: temp_sorted_bc = 0; indel_length = most_common_insertion_length; variant_line = 'ins\tpos = %s\tref = %s\tnon_indel_cov_next = %d\tnon_indel_cov_curr = %d\tmost_common_insertion_count = %d\tref_base = %s\tcons_base = %s\tbase_counts = %s\tinsertion_counts = %s\tdeletion_counts = %s\t%s' % (position, ref_name, non_indel_coverage_next_base, non_indel_coverage_current_base, most_common_insertion_count, ref_base, temp_sorted_bc, str(sorted_base_counts), str(insertion_event_counts), str(deletion_event_counts), line.strip()); ret_variant_list.append(variant_line); variant_line = 'del\tpos = %s\tref = %s\tnon_indel_cov_next = %d\tnon_indel_cov_curr = %d\tmost_common_deletion_count = %d\tref_base = %s\tcons_base = %s\tbase_counts = %s\tinsertion_counts = %s\tdeletion_counts = %s\t%s' % (position, ref_name, non_indel_coverage_next_base, non_indel_coverage_current_base, most_common_deletion_count, ref_base, sorted_base_counts[-1][0], str(sorted_base_counts), str(insertion_event_counts), str(deletion_event_counts), line.strip()); ret_variant_list.append(variant_line); cf_list.append(vcf_line); e_threshold, output_prefix, thread_id=0, bed_position=''): fp = None; try: fp = open(mpileup_path, 'r'); except IOError: sys.stderr.write('ERROR: Could not open file "%s" for reading!\n' % mpileup_path); return None; ret_variant_list = []; ret_vcf_list = []; ret_snp_count = [0]; ret_insertion_count = [0]; ret_deletion_count = [0]; ret_num_undercovered_bases = [0]; ret_num_called_bases = [0]; ret_num_correct_bases = [0]; ret_coverage_sum = [0]; fp_variant = None; fp_vcf = None; if (output_prefix != ''): if (not os.path.exists(os.path.dirname(output_prefix))): os.makedirs(os.path.dirname(output_prefix)); variant_file = ('%s-cov_%d.variant.csv' % (output_prefix, coverage_threshold)); fp_variant = open(variant_file, 'w'); vcf_file = ('%s-cov_%d.variant.vcf' % (output_prefix, coverage_threshold)); fp_vcf = open(vcf_file, 'w'); fp_vcf.write('##fileformat=VCFv4.0\n'); fp_vcf.write('##fileDate=20150409\n'); fp_vcf.write('##source=%s\n' % (' '.join(sys.argv))); fp_vcf.write('##reference=%s\n' % reference_path); fp_vcf.write('##INFO=<ID=DP,Number=1,Type=Integer,Description="Raw Depth">\n'); fp_vcf.write('##INFO=<ID=TYPE,Number=A,Type=String,Description="Type of each allele (snp, ins, del, mnp, complex)">\n'); fp_vcf.write('##INFO=<ID=AF,Number=1,Type=Float,Description="Allele Frequency">\n'); fp_vcf.write('##INFO=<ID=SB,Number=1,Type=Integer,Description="Phred-scaled strand bias at this position">\n'); fp_vcf.write('##INFO=<ID=DP4,Number=4,Type=Integer,Description="Counts for ref-forward bases, ref-reverse, alt-forward and alt-reverse bases">\n'); fp_vcf.write('##INFO=<ID=INDEL,Number=0,Type=Flag,Description="Indicates that the variant is an INDEL.">\n'); fp_vcf.write('##INFO=<ID=CONSVAR,Number=0,Type=Flag,Description="Indicates that the variant is a consensus variant (as opposed to a low frequency variant).">\n'); fp_vcf.write('##INFO=<ID=HRUN,Number=1,Type=Integer,Description="Homopolymer length to the right of report indel position">\n'); fp_vcf.write('#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n'); fp_vcf.flush(); use_bed = False; bed_chromosome = ""; bed_pos_start = 0; bed_pos_end = -1; if (bed_position != ""): bed_split = bed_position.split(':'); if (len(bed_split) != 2): use_bed = False; else: bed_chromosome = bed_split[0]; bed_pos_split = bed_split[1].split('-'); if (len(bed_pos_split) != 2): use_bed = False; else: bed_pos_start = int(bed_pos_split[0]); bed_pos_end = int(bed_pos_split[1]); use_bed = True; sys.stderr.write('Using location specified through commandline:\n'); sys.stderr.write('\tChromosome: "%s"\n' % bed_chromosome); sys.stderr.write('\tStart: %d\n' % bed_pos_start); sys.stderr.write('\tEnd: %d\n\n' % bed_pos_end); i = 0 if (use_bed == False) else max((bed_pos_start - 10), 0); j = 0; _skip = 0; for line in fp: if (num_bases_to_skip > 0): num_bases_to_skip -= 1; continue; if (use_bed == True): line_split = line.strip().split('\t'); if (len(line_split) > 2 and line_split[0] == bed_chromosome): current_pos = int(line_split[1]); if (current_pos < bed_pos_start or current_pos >= bed_pos_end): i += 1; j += 1; continue; else: i += 1; j += 1; continue; if (thread_id == 0): if ((j % 1000) == 0): sys.stderr.write('\r[%d] snps = %d, insertions = %d, deletions = %d, undercovered = %d, coverage = %.2f' % (i, ret_snp_count[0], ret_insertion_count[0], ret_deletion_count[0], ret_num_undercovered_bases[0], (float(ret_coverage_sum[0])/float((i + 1))))); sys.stderr.flush(); variant_list_length = len(ret_variant_list); vcf_list_length = len(ret_vcf_list); num_bases_to_skip = process_mpileup_line(line, i, ret_variant_list, ret_vcf_list, ret_snp_count, ret_insertion_count, ret_deletion_count, ret_num_undercovered_bases, ret_num_called_bases, ret_num_correct_bases, ret_coverage_sum, coverage_threshold, verbose=use_bed); if (len(ret_variant_list) > variant_list_length and fp_variant != None): fp_variant.write('\n'.join(ret_variant_list[variant_list_length:]) + '\n'); fp_variant.flush(); if (len(ret_vcf_list) > vcf_list_length and fp_vcf != None): fp_vcf.write('\n'.join(ret_vcf_list[vcf_list_length:]) + '\n'); fp_vcf.flush(); i += num_bases_to_skip; i += 1; j += 1; fp.close(); sys.stderr.write('\n') if (fp_variant != None): fp_variant.close(); if (fp_vcf != None): fp_vcf.close(); summary_lines = ''; summary_lines += 'alignments_file: %s\n' % alignments_path; summary_lines += 'mpileup_file: %s\n' % mpileup_path; summary_lines += 'coverage_threshold: %d\n' % coverage_threshold; summary_lines += 'snp_count: %d\n' % ret_snp_count[0]; summary_lines += 'insertion_count: %d\n' % ret_insertion_count[0]; summary_lines += 'deletion_count: %d\n' % ret_deletion_count[0]; summary_lines += 'num_undercovered_bases: %d\n' % ret_num_undercovered_bases[0]; summary_lines += 'num_called_bases: %d\n' % ret_num_called_bases[0]; summary_lines += 'num_correct_bases: %d\n' % ret_num_correct_bases[0]; summary_lines += 'average_coverage: %.2f\n' % ((float(ret_coverage_sum[0])/float((i + 1)))); sys.stderr.write(summary_lines + '\n'); sys.stderr.write('\n'); if (output_prefix != ''): summary_file = ('%s-cov_%d.variant.sum' % (output_prefix, coverage_threshold)); try: fp_sum = open(summary_file, 'w'); fp_sum.write(summary_lines); fp_sum.close(); return summary_file; except IOError: sys.stderr.write('ERROR: Could not open file "%s" for writing!\n' % (summary_file)); return None; return None; def main(alignments_path, reference_path, coverage_threshold, output_prefix, thread_id=0, bed_position=""): alignments_path_bam = alignments_path; if (os.path.exists(alignments_path) == False): sys.stderr.write('ERROR: File "%s" does not exist!\n' % alignments_path); return; if (alignments_path.endswith('sam')): dir_name = os.path.dirname(alignments_path); if (dir_name == ''): dir_name = '.'; alignments_path_bam = dir_name + '/' + os.path.splitext(os.path.basename(alignments_path))[0] + '.bam' alignments_path_bam_exists = os.path.exists(alignments_path_bam); if (alignments_path_bam_exists == False or (alignments_path_bam_exists == True and os.path.getmtime(alignments_path) > os.path.getmtime(alignments_path_bam))): command = 'samtools view -bS %s | samtools sort - %s' % (alignments_path, os.path.splitext(alignments_path_bam)[0]); sys.stderr.write(command + '\n') subprocess.call(command, shell='True'); command = 'samtools index %s %s.bai' % (alignments_path_bam, alignments_path_bam); subprocess.call(command, shell='True'); elif (alignments_path.endswith('bam') == False): sys.stderr.write('ERROR: File extension needs to be either .sam or .bam! Input file path: "%s".\n' % alignments_path); return; mpileup_path = ('%s.mpileup' % alignments_path_bam); mpileup_exists = os.path.exists(mpileup_path); if (mpileup_exists == False or (mpileup_exists == True and os.path.getmtime(alignments_path) > os.path.getmtime(mpileup_path))): command = 'samtools mpileup -B -d 1000000 -Q 0 -A -f %s %s > %s.mpileup' % (reference_path, alignments_path_bam, alignments_path_bam); subprocess.call(command, shell='True'); sys.stderr.write('Processing file "%s"...\n' % alignments_path); sys.stderr.write('Reference file "%s"...\n' % reference_path); sys.stderr.write('Coverage threshold: %d\n' % coverage_threshold); summary_file = process_mpileup(alignments_path, reference_path, ('%s.mpileup' % alignments_path_bam), coverage_threshold, output_prefix, thread_id, bed_position); def CollectSummaries(sam_files, prefix_for_intermediate_results, collective_output_file): fp_collect = None; try: fp_collect = open(collective_output_file, 'w'); except IOError: sys.stderr.write('ERROR: Could not open file "%s" for writing!\n' % collective_output_file); return; for sam_file in sam_files: summary_file = prefix_for_intermediate_results + '.sum'; try: fp_sum = open(summary_file, 'r'); lines = fp_sum.readlines(); fp_sum.close(); except IOError: sys.stderr.write('ERROR: Could not open file "%s" for reading!\n' % summary_file); continue; fp_collect.write(''.join(lines) + '\n'); fp_collect.close(); if __name__ == "__main__": # if (len(sys.argv) < 5): # sys.stderr.write('Usage:\n'); # sys.stderr.write('\t%s <reference_file_path> coverage_threshold <collective_output_file> <{sb}am_file_1> [<{sb}am_file_2> <{sb}am_file_3> ...]\n' % sys.argv[0]); # sys.stderr.write('\t(If <collective_output_file> is equal to "-", no files will be written to disk.)\n'); # exit(1); if (len(sys.argv) < 5): sys.stderr.write('Usage:\n'); sys.stderr.write('\t%s <reference_file_path> coverage_threshold <output_prefix> <{sb}am_file_> [position]\n' % sys.argv[0]); sys.stderr.write('\t(If <collective_output_file> is equal to "-", no files will be written to disk.)\n'); sys.stderr.write('\tPosition parameter is a string specifying "chromosome:start-end"\n\n'); exit(1); reference_file = sys.argv[1]; coverage_threshold = int(sys.argv[2]); output_prefix = sys.argv[3]; sam_file = sys.argv[4]; bed_position = ''; if (len(sys.argv) > 5): bed_position = sys.argv[5]; # sys.stderr.write('bed_position: "%s"\n\n' % bed_position); processes = []; if (output_prefix == '-'): output_prefix = os.path.splitext(sam_file)[0]; main(sam_file, reference_file, coverage_threshold, output_prefix, 0, bed_position); # if (output_prefix != '-'): # CollectSummaries([sam_file], output_prefix, output_prefix + '.variant.sum');
false
true
f7fe83ebf8fc4ea77d58cdf5ea08a00b8eb21944
39
py
Python
sentiment_analysis/data_provider.py
mengfanShi/SpiderMan
679b3b5b64e8e6883eca0a22ddeec23a7a9d61bb
[ "MIT" ]
1
2018-01-02T17:07:28.000Z
2018-01-02T17:07:28.000Z
sentiment_analysis/data_provider.py
mengfanShi/SpiderMan
679b3b5b64e8e6883eca0a22ddeec23a7a9d61bb
[ "MIT" ]
null
null
null
sentiment_analysis/data_provider.py
mengfanShi/SpiderMan
679b3b5b64e8e6883eca0a22ddeec23a7a9d61bb
[ "MIT" ]
2
2018-01-02T15:38:36.000Z
2021-04-06T05:50:41.000Z
# -*- coding: utf-8 -*- import jieba
7.8
23
0.538462
import jieba
true
true
f7fe84288dcebceea381116a51baee3b3a17183d
2,127
py
Python
src_multilevel/utils/data_processor.py
vineetjohn/ecom-sigir-task-2018
1be3d5670912e43cf21090faf3b4f51ac3bbba9f
[ "MIT" ]
1
2018-08-07T12:38:47.000Z
2018-08-07T12:38:47.000Z
src_multilevel/utils/data_processor.py
vineetjohn/ecom-sigir-task-2018
1be3d5670912e43cf21090faf3b4f51ac3bbba9f
[ "MIT" ]
null
null
null
src_multilevel/utils/data_processor.py
vineetjohn/ecom-sigir-task-2018
1be3d5670912e43cf21090faf3b4f51ac3bbba9f
[ "MIT" ]
null
null
null
import logging import re import spacy from spacy.lang.en import English from src.config import global_config from src.utils import stopword_aggregator logger = logging.getLogger(global_config.logger_name) def is_valid_token(token): return len(token) >= 3 and token not in stopword_aggregator.custom_stopwords def clean_product(string, tokenizer): string = re.sub(r"[^A-Za-z]", " ", string) string = re.sub(r"\s{2,}", " ", string) string = string.strip().lower() tokens = tokenizer(string) tokens = [str(x) for x in tokens if is_valid_token(str(x))] return " ".join(tokens) def get_training_data(input_file_path): products, labels = list(), list() spacy_nlp = spacy.load("en") tokenizer = English().Defaults.create_tokenizer(spacy_nlp) max_category_depth = 1 with open(input_file_path) as input_file: i = 0 for line in input_file: if not ((i + 1) % 10000): logger.info("{} lines processed".format(i + 1)) i += 1 [product, category_string] = line.strip().split('\t') categories = category_string.strip().split('>') max_category_depth = len(categories) if len(categories) > max_category_depth else max_category_depth cleaned_product = clean_product(product, tokenizer) if cleaned_product: logger.debug("original: {}, cleaned: {}".format(product, cleaned_product)) products.append(cleaned_product) labels.append(categories) else: logger.error("skipped product {}".format(product)) logger.info("max_category_depth: {}".format(max_category_depth)) return products, labels def get_test_data(input_file_path): products = list() spacy_nlp = spacy.load("en") tokenizer = English().Defaults.create_tokenizer(spacy_nlp) with open(input_file_path) as input_file: for line in input_file: product = line.strip() cleaned_product = clean_product(product, tokenizer) products.append(cleaned_product) return products
31.746269
112
0.652562
import logging import re import spacy from spacy.lang.en import English from src.config import global_config from src.utils import stopword_aggregator logger = logging.getLogger(global_config.logger_name) def is_valid_token(token): return len(token) >= 3 and token not in stopword_aggregator.custom_stopwords def clean_product(string, tokenizer): string = re.sub(r"[^A-Za-z]", " ", string) string = re.sub(r"\s{2,}", " ", string) string = string.strip().lower() tokens = tokenizer(string) tokens = [str(x) for x in tokens if is_valid_token(str(x))] return " ".join(tokens) def get_training_data(input_file_path): products, labels = list(), list() spacy_nlp = spacy.load("en") tokenizer = English().Defaults.create_tokenizer(spacy_nlp) max_category_depth = 1 with open(input_file_path) as input_file: i = 0 for line in input_file: if not ((i + 1) % 10000): logger.info("{} lines processed".format(i + 1)) i += 1 [product, category_string] = line.strip().split('\t') categories = category_string.strip().split('>') max_category_depth = len(categories) if len(categories) > max_category_depth else max_category_depth cleaned_product = clean_product(product, tokenizer) if cleaned_product: logger.debug("original: {}, cleaned: {}".format(product, cleaned_product)) products.append(cleaned_product) labels.append(categories) else: logger.error("skipped product {}".format(product)) logger.info("max_category_depth: {}".format(max_category_depth)) return products, labels def get_test_data(input_file_path): products = list() spacy_nlp = spacy.load("en") tokenizer = English().Defaults.create_tokenizer(spacy_nlp) with open(input_file_path) as input_file: for line in input_file: product = line.strip() cleaned_product = clean_product(product, tokenizer) products.append(cleaned_product) return products
true
true
f7fe8436091bd5d409cc6f6db5d50d49536600c2
17,601
py
Python
python_modules/dagster/dagster/core/definitions/resource_definition.py
rpatil524/dagster
6f918d94cbd543ab752ab484a65e3a40fd441716
[ "Apache-2.0" ]
4,606
2018-06-21T17:45:20.000Z
2022-03-31T23:39:42.000Z
python_modules/dagster/dagster/core/definitions/resource_definition.py
rpatil524/dagster
6f918d94cbd543ab752ab484a65e3a40fd441716
[ "Apache-2.0" ]
6,221
2018-06-12T04:36:01.000Z
2022-03-31T21:43:05.000Z
python_modules/dagster/dagster/core/definitions/resource_definition.py
rpatil524/dagster
6f918d94cbd543ab752ab484a65e3a40fd441716
[ "Apache-2.0" ]
619
2018-08-22T22:43:09.000Z
2022-03-31T22:48:06.000Z
from collections import namedtuple from functools import update_wrapper from typing import ( TYPE_CHECKING, AbstractSet, Any, Callable, Dict, List, Optional, Union, cast, overload, ) from dagster import check from dagster.core.definitions.config import is_callable_valid_config_arg from dagster.core.definitions.configurable import AnonymousConfigurableDefinition from dagster.core.errors import ( DagsterInvalidDefinitionError, DagsterInvalidInvocationError, DagsterUnknownResourceError, ) from dagster.seven import funcsigs from dagster.utils.backcompat import experimental_arg_warning from ..decorator_utils import ( get_function_params, is_required_param, positional_arg_name_list, validate_expected_params, ) from .definition_config_schema import ( IDefinitionConfigSchema, convert_user_facing_definition_config_schema, ) from .resource_invocation import resource_invocation_result if TYPE_CHECKING: from dagster.core.execution.resources_init import InitResourceContext def is_context_provided(params: List[funcsigs.Parameter]) -> bool: return len(params) >= 1 class ResourceDefinition(AnonymousConfigurableDefinition): """Core class for defining resources. Resources are scoped ways to make external resources (like database connections) available to during job execution and to clean up after execution resolves. If resource_fn yields once rather than returning (in the manner of functions decorable with :py:func:`@contextlib.contextmanager <python:contextlib.contextmanager>`) then the body of the function after the yield will be run after execution resolves, allowing users to write their own teardown/cleanup logic. Depending on your executor, resources may be instantiated and cleaned up more than once in a job execution. Args: resource_fn (Callable[[InitResourceContext], Any]): User-provided function to instantiate the resource, which will be made available to executions keyed on the ``context.resources`` object. config_schema (Optional[ConfigSchema): The schema for the config. If set, Dagster will check that config provided for the resource matches this schema and fail if it does not. If not set, Dagster will accept any config provided for the resource. description (Optional[str]): A human-readable description of the resource. required_resource_keys: (Optional[Set[str]]) Keys for the resources required by this resource. A DagsterInvariantViolationError will be raised during initialization if dependencies are cyclic. version (Optional[str]): (Experimental) The version of the resource's definition fn. Two wrapped resource functions should only have the same version if they produce the same resource definition when provided with the same inputs. """ def __init__( self, resource_fn: Callable[["InitResourceContext"], Any], config_schema: Optional[Union[Any, IDefinitionConfigSchema]] = None, description: Optional[str] = None, required_resource_keys: Optional[AbstractSet[str]] = None, version: Optional[str] = None, ): self._resource_fn = check.callable_param(resource_fn, "resource_fn") self._config_schema = convert_user_facing_definition_config_schema(config_schema) self._description = check.opt_str_param(description, "description") self._required_resource_keys = check.opt_set_param( required_resource_keys, "required_resource_keys" ) self._version = check.opt_str_param(version, "version") if version: experimental_arg_warning("version", "ResourceDefinition.__init__") @property def resource_fn(self) -> Callable[..., Any]: return self._resource_fn @property def config_schema(self) -> IDefinitionConfigSchema: return self._config_schema @property def description(self) -> Optional[str]: return self._description @property def version(self) -> Optional[str]: return self._version @property def required_resource_keys(self) -> AbstractSet[str]: return self._required_resource_keys @staticmethod def none_resource(description: Optional[str] = None) -> "ResourceDefinition": """A helper function that returns a none resource. Args: description ([Optional[str]]): The description of the resource. Defaults to None. Returns: [ResourceDefinition]: A resource that does nothing. """ return ResourceDefinition.hardcoded_resource(value=None, description=description) @staticmethod def hardcoded_resource(value: Any, description: Optional[str] = None) -> "ResourceDefinition": """A helper function that creates a ``ResourceDefinition`` with a hardcoded object. Args: value (Any): The value that will be accessible via context.resources.resource_name. description ([Optional[str]]): The description of the resource. Defaults to None. Returns: [ResourceDefinition]: A hardcoded resource. """ return ResourceDefinition(resource_fn=lambda _init_context: value, description=description) @staticmethod def mock_resource(description: Optional[str] = None) -> "ResourceDefinition": """A helper function that creates a ``ResourceDefinition`` which wraps a ``mock.MagicMock``. Args: description ([Optional[str]]): The description of the resource. Defaults to None. Returns: [ResourceDefinition]: A resource that creates the magic methods automatically and helps you mock existing resources. """ from unittest import mock return ResourceDefinition( resource_fn=lambda _init_context: mock.MagicMock(), description=description ) @staticmethod def string_resource(description: Optional[str] = None) -> "ResourceDefinition": return ResourceDefinition( resource_fn=lambda init_context: init_context.resource_config, config_schema=str, description=description, ) def copy_for_configured( self, description: Optional[str], config_schema: IDefinitionConfigSchema, _ ) -> "ResourceDefinition": return ResourceDefinition( config_schema=config_schema, description=description or self.description, resource_fn=self.resource_fn, required_resource_keys=self.required_resource_keys, version=self.version, ) def __call__(self, *args, **kwargs): from dagster.core.execution.resources_init import InitResourceContext context_provided = is_context_provided(get_function_params(self.resource_fn)) if context_provided: if len(args) + len(kwargs) == 0: raise DagsterInvalidInvocationError( "Resource initialization function has context argument, but no context was provided " "when invoking." ) if len(args) + len(kwargs) > 1: raise DagsterInvalidInvocationError( "Initialization of resource received multiple arguments. Only a first " "positional context parameter should be provided when invoking." ) context_param_name = get_function_params(self.resource_fn)[0].name if args: check.opt_inst_param(args[0], context_param_name, InitResourceContext) return resource_invocation_result(self, args[0]) else: if context_param_name not in kwargs: raise DagsterInvalidInvocationError( f"Resource initialization expected argument '{context_param_name}'." ) check.opt_inst_param( kwargs[context_param_name], context_param_name, InitResourceContext ) return resource_invocation_result(self, kwargs[context_param_name]) else: return resource_invocation_result(self, None) class _ResourceDecoratorCallable: def __init__( self, config_schema: Optional[Dict[str, Any]] = None, description: Optional[str] = None, required_resource_keys: Optional[AbstractSet[str]] = None, version: Optional[str] = None, ): self.config_schema = config_schema # checked by underlying definition self.description = check.opt_str_param(description, "description") self.version = check.opt_str_param(version, "version") self.required_resource_keys = check.opt_set_param( required_resource_keys, "required_resource_keys" ) def __call__(self, resource_fn: Callable[["InitResourceContext"], Any]): check.callable_param(resource_fn, "resource_fn") any_name = ["*"] if is_context_provided(get_function_params(resource_fn)) else [] params = get_function_params(resource_fn) missing_positional = validate_expected_params(params, any_name) if missing_positional: raise DagsterInvalidDefinitionError( f"@resource decorated function '{resource_fn.__name__}' expects a single " "positional argument." ) extras = params[len(any_name) :] required_extras = list(filter(is_required_param, extras)) if required_extras: raise DagsterInvalidDefinitionError( f"@resource decorated function '{resource_fn.__name__}' expects only a single positional required argument. " f"Got required extra params {', '.join(positional_arg_name_list(required_extras))}" ) resource_def = ResourceDefinition( resource_fn=resource_fn, config_schema=self.config_schema, description=self.description, version=self.version, required_resource_keys=self.required_resource_keys, ) update_wrapper(resource_def, wrapped=resource_fn) return resource_def @overload def resource(config_schema=Callable[["InitResourceContext"], Any]) -> ResourceDefinition: ... @overload def resource( config_schema: Optional[Dict[str, Any]] = None, description: Optional[str] = None, required_resource_keys: Optional[AbstractSet[str]] = None, version=None, ) -> Callable[[Callable[["InitResourceContext"], Any]], "ResourceDefinition"]: ... def resource( config_schema: Optional[ Union[Callable[["InitResourceContext"], Any], IDefinitionConfigSchema, Dict[str, Any]] ] = None, description: Optional[str] = None, required_resource_keys: Optional[AbstractSet[str]] = None, version=None, ) -> Union[ Callable[[Callable[["InitResourceContext"], Any]], "ResourceDefinition"], "ResourceDefinition" ]: """Define a resource. The decorated function should accept an :py:class:`InitResourceContext` and return an instance of the resource. This function will become the ``resource_fn`` of an underlying :py:class:`ResourceDefinition`. If the decorated function yields once rather than returning (in the manner of functions decorable with :py:func:`@contextlib.contextmanager <python:contextlib.contextmanager>`) then the body of the function after the yield will be run after execution resolves, allowing users to write their own teardown/cleanup logic. Args: config_schema (Optional[ConfigSchema]): The schema for the config. Configuration data available in `init_context.resource_config`. If not set, Dagster will accept any config provided. description(Optional[str]): A human-readable description of the resource. version (Optional[str]): (Experimental) The version of a resource function. Two wrapped resource functions should only have the same version if they produce the same resource definition when provided with the same inputs. required_resource_keys (Optional[Set[str]]): Keys for the resources required by this resource. """ # This case is for when decorator is used bare, without arguments. # E.g. @resource versus @resource() if callable(config_schema) and not is_callable_valid_config_arg(config_schema): return _ResourceDecoratorCallable()(config_schema) def _wrap(resource_fn: Callable[["InitResourceContext"], Any]) -> "ResourceDefinition": return _ResourceDecoratorCallable( config_schema=cast(Optional[Dict[str, Any]], config_schema), description=description, required_resource_keys=required_resource_keys, version=version, )(resource_fn) return _wrap class Resources: """This class functions as a "tag" that we can use to type the namedtuple returned by ScopedResourcesBuilder.build(). The way that we create the namedtuple returned by build() is incompatible with type annotations on its own due to its dynamic attributes, so this tag class provides a workaround.""" class IContainsGenerator: """This class adds an additional tag to indicate that the resources object has at least one resource that has been yielded from a generator, and thus may require teardown.""" class ScopedResourcesBuilder( namedtuple("ScopedResourcesBuilder", "resource_instance_dict contains_generator") ): """There are concepts in the codebase (e.g. ops, system storage) that receive only the resources that they have specified in required_resource_keys. ScopedResourcesBuilder is responsible for dynamically building a class with only those required resources and returning an instance of that class.""" def __new__( cls, resource_instance_dict: Optional[Dict[str, Any]] = None, contains_generator: Optional[bool] = False, ): return super(ScopedResourcesBuilder, cls).__new__( cls, resource_instance_dict=check.opt_dict_param( resource_instance_dict, "resource_instance_dict", key_type=str ), contains_generator=contains_generator, ) def build(self, required_resource_keys: Optional[AbstractSet[str]]) -> Resources: """We dynamically create a type that has the resource keys as properties, to enable dotting into the resources from a context. For example, given: resources = {'foo': <some resource>, 'bar': <some other resource>} then this will create the type Resource(namedtuple('foo bar')) and then binds the specified resources into an instance of this object, which can be consumed as, e.g., context.resources.foo. """ required_resource_keys = check.opt_set_param( required_resource_keys, "required_resource_keys", of_type=str ) # it is possible that the surrounding context does NOT have the required resource keys # because we are building a context for steps that we are not going to execute (e.g. in the # resume/retry case, in order to generate copy intermediates events) resource_instance_dict = { key: self.resource_instance_dict[key] for key in required_resource_keys if key in self.resource_instance_dict } # If any of the resources are generators, add the IContainsGenerator subclass to flag that # this is the case. if self.contains_generator: class _ScopedResourcesContainsGenerator( namedtuple("_ScopedResourcesContainsGenerator", list(resource_instance_dict.keys())), # type: ignore[misc] Resources, IContainsGenerator, ): def __getattr__(self, attr): raise DagsterUnknownResourceError(attr) return _ScopedResourcesContainsGenerator(**resource_instance_dict) # type: ignore[call-arg] else: class _ScopedResources( namedtuple("_ScopedResources", list(resource_instance_dict.keys())), # type: ignore[misc] Resources, ): def __getattr__(self, attr): raise DagsterUnknownResourceError(attr) return _ScopedResources(**resource_instance_dict) # type: ignore[call-arg] def make_values_resource(**kwargs: Any) -> ResourceDefinition: """A helper function that creates a ``ResourceDefinition`` to take in user-defined values. This is useful for sharing values between ops. Args: **kwargs: Arbitrary keyword arguments that will be passed to the config schema of the returned resource definition. If not set, Dagster will accept any config provided for the resource. For example: .. code-block:: python @op(required_resource_keys={"globals"}) def my_op(context): print(context.resources.globals["my_str_var"]) @job(resource_defs={"globals": make_values_resource(my_str_var=str, my_int_var=int)}) def my_job(): my_op() Returns: ResourceDefinition: A resource that passes in user-defined values. """ return ResourceDefinition( resource_fn=lambda init_context: init_context.resource_config, config_schema=kwargs or Any, )
40.002273
125
0.684279
from collections import namedtuple from functools import update_wrapper from typing import ( TYPE_CHECKING, AbstractSet, Any, Callable, Dict, List, Optional, Union, cast, overload, ) from dagster import check from dagster.core.definitions.config import is_callable_valid_config_arg from dagster.core.definitions.configurable import AnonymousConfigurableDefinition from dagster.core.errors import ( DagsterInvalidDefinitionError, DagsterInvalidInvocationError, DagsterUnknownResourceError, ) from dagster.seven import funcsigs from dagster.utils.backcompat import experimental_arg_warning from ..decorator_utils import ( get_function_params, is_required_param, positional_arg_name_list, validate_expected_params, ) from .definition_config_schema import ( IDefinitionConfigSchema, convert_user_facing_definition_config_schema, ) from .resource_invocation import resource_invocation_result if TYPE_CHECKING: from dagster.core.execution.resources_init import InitResourceContext def is_context_provided(params: List[funcsigs.Parameter]) -> bool: return len(params) >= 1 class ResourceDefinition(AnonymousConfigurableDefinition): def __init__( self, resource_fn: Callable[["InitResourceContext"], Any], config_schema: Optional[Union[Any, IDefinitionConfigSchema]] = None, description: Optional[str] = None, required_resource_keys: Optional[AbstractSet[str]] = None, version: Optional[str] = None, ): self._resource_fn = check.callable_param(resource_fn, "resource_fn") self._config_schema = convert_user_facing_definition_config_schema(config_schema) self._description = check.opt_str_param(description, "description") self._required_resource_keys = check.opt_set_param( required_resource_keys, "required_resource_keys" ) self._version = check.opt_str_param(version, "version") if version: experimental_arg_warning("version", "ResourceDefinition.__init__") @property def resource_fn(self) -> Callable[..., Any]: return self._resource_fn @property def config_schema(self) -> IDefinitionConfigSchema: return self._config_schema @property def description(self) -> Optional[str]: return self._description @property def version(self) -> Optional[str]: return self._version @property def required_resource_keys(self) -> AbstractSet[str]: return self._required_resource_keys @staticmethod def none_resource(description: Optional[str] = None) -> "ResourceDefinition": return ResourceDefinition.hardcoded_resource(value=None, description=description) @staticmethod def hardcoded_resource(value: Any, description: Optional[str] = None) -> "ResourceDefinition": return ResourceDefinition(resource_fn=lambda _init_context: value, description=description) @staticmethod def mock_resource(description: Optional[str] = None) -> "ResourceDefinition": from unittest import mock return ResourceDefinition( resource_fn=lambda _init_context: mock.MagicMock(), description=description ) @staticmethod def string_resource(description: Optional[str] = None) -> "ResourceDefinition": return ResourceDefinition( resource_fn=lambda init_context: init_context.resource_config, config_schema=str, description=description, ) def copy_for_configured( self, description: Optional[str], config_schema: IDefinitionConfigSchema, _ ) -> "ResourceDefinition": return ResourceDefinition( config_schema=config_schema, description=description or self.description, resource_fn=self.resource_fn, required_resource_keys=self.required_resource_keys, version=self.version, ) def __call__(self, *args, **kwargs): from dagster.core.execution.resources_init import InitResourceContext context_provided = is_context_provided(get_function_params(self.resource_fn)) if context_provided: if len(args) + len(kwargs) == 0: raise DagsterInvalidInvocationError( "Resource initialization function has context argument, but no context was provided " "when invoking." ) if len(args) + len(kwargs) > 1: raise DagsterInvalidInvocationError( "Initialization of resource received multiple arguments. Only a first " "positional context parameter should be provided when invoking." ) context_param_name = get_function_params(self.resource_fn)[0].name if args: check.opt_inst_param(args[0], context_param_name, InitResourceContext) return resource_invocation_result(self, args[0]) else: if context_param_name not in kwargs: raise DagsterInvalidInvocationError( f"Resource initialization expected argument '{context_param_name}'." ) check.opt_inst_param( kwargs[context_param_name], context_param_name, InitResourceContext ) return resource_invocation_result(self, kwargs[context_param_name]) else: return resource_invocation_result(self, None) class _ResourceDecoratorCallable: def __init__( self, config_schema: Optional[Dict[str, Any]] = None, description: Optional[str] = None, required_resource_keys: Optional[AbstractSet[str]] = None, version: Optional[str] = None, ): self.config_schema = config_schema self.description = check.opt_str_param(description, "description") self.version = check.opt_str_param(version, "version") self.required_resource_keys = check.opt_set_param( required_resource_keys, "required_resource_keys" ) def __call__(self, resource_fn: Callable[["InitResourceContext"], Any]): check.callable_param(resource_fn, "resource_fn") any_name = ["*"] if is_context_provided(get_function_params(resource_fn)) else [] params = get_function_params(resource_fn) missing_positional = validate_expected_params(params, any_name) if missing_positional: raise DagsterInvalidDefinitionError( f"@resource decorated function '{resource_fn.__name__}' expects a single " "positional argument." ) extras = params[len(any_name) :] required_extras = list(filter(is_required_param, extras)) if required_extras: raise DagsterInvalidDefinitionError( f"@resource decorated function '{resource_fn.__name__}' expects only a single positional required argument. " f"Got required extra params {', '.join(positional_arg_name_list(required_extras))}" ) resource_def = ResourceDefinition( resource_fn=resource_fn, config_schema=self.config_schema, description=self.description, version=self.version, required_resource_keys=self.required_resource_keys, ) update_wrapper(resource_def, wrapped=resource_fn) return resource_def @overload def resource(config_schema=Callable[["InitResourceContext"], Any]) -> ResourceDefinition: ... @overload def resource( config_schema: Optional[Dict[str, Any]] = None, description: Optional[str] = None, required_resource_keys: Optional[AbstractSet[str]] = None, version=None, ) -> Callable[[Callable[["InitResourceContext"], Any]], "ResourceDefinition"]: ... def resource( config_schema: Optional[ Union[Callable[["InitResourceContext"], Any], IDefinitionConfigSchema, Dict[str, Any]] ] = None, description: Optional[str] = None, required_resource_keys: Optional[AbstractSet[str]] = None, version=None, ) -> Union[ Callable[[Callable[["InitResourceContext"], Any]], "ResourceDefinition"], "ResourceDefinition" ]: if callable(config_schema) and not is_callable_valid_config_arg(config_schema): return _ResourceDecoratorCallable()(config_schema) def _wrap(resource_fn: Callable[["InitResourceContext"], Any]) -> "ResourceDefinition": return _ResourceDecoratorCallable( config_schema=cast(Optional[Dict[str, Any]], config_schema), description=description, required_resource_keys=required_resource_keys, version=version, )(resource_fn) return _wrap class Resources: class IContainsGenerator: class ScopedResourcesBuilder( namedtuple("ScopedResourcesBuilder", "resource_instance_dict contains_generator") ): def __new__( cls, resource_instance_dict: Optional[Dict[str, Any]] = None, contains_generator: Optional[bool] = False, ): return super(ScopedResourcesBuilder, cls).__new__( cls, resource_instance_dict=check.opt_dict_param( resource_instance_dict, "resource_instance_dict", key_type=str ), contains_generator=contains_generator, ) def build(self, required_resource_keys: Optional[AbstractSet[str]]) -> Resources: required_resource_keys = check.opt_set_param( required_resource_keys, "required_resource_keys", of_type=str ) resource_instance_dict = { key: self.resource_instance_dict[key] for key in required_resource_keys if key in self.resource_instance_dict } if self.contains_generator: class _ScopedResourcesContainsGenerator( namedtuple("_ScopedResourcesContainsGenerator", list(resource_instance_dict.keys())), Resources, IContainsGenerator, ): def __getattr__(self, attr): raise DagsterUnknownResourceError(attr) return _ScopedResourcesContainsGenerator(**resource_instance_dict) else: class _ScopedResources( namedtuple("_ScopedResources", list(resource_instance_dict.keys())), Resources, ): def __getattr__(self, attr): raise DagsterUnknownResourceError(attr) return _ScopedResources(**resource_instance_dict) def make_values_resource(**kwargs: Any) -> ResourceDefinition: return ResourceDefinition( resource_fn=lambda init_context: init_context.resource_config, config_schema=kwargs or Any, )
true
true
f7fe84ce03cdd504b8f1583950e160169cbd9d90
3,878
py
Python
python/bot.py
dev-null-undefined/felix
addad2375bc46683c75674ba83acc04495526830
[ "MIT" ]
135
2018-09-08T18:56:27.000Z
2022-03-24T10:27:34.000Z
python/bot.py
dev-null-undefined/felix
addad2375bc46683c75674ba83acc04495526830
[ "MIT" ]
73
2018-09-29T07:40:10.000Z
2022-03-06T11:57:19.000Z
python/bot.py
dev-null-undefined/felix
addad2375bc46683c75674ba83acc04495526830
[ "MIT" ]
105
2018-09-08T20:52:32.000Z
2022-03-03T16:16:23.000Z
"""Felix Discord Bot This file starts the bot and loads all extensions/cogs and configs/permissions The Bot automatically tries to load all extensions found in the "cogs/" folder plus the hangman.hangman extension. An extension can be reloaded without restarting the bot. The extension "management" provides the commands to load/unload other extensions This bot requires discord.py pip install -U discord.py """ import json import traceback import sys from datetime import datetime from os import path, listdir from discord.ext.commands import Bot, when_mentioned_or from discord import DMChannel, Message, Activity, Intents, AllowedMentions from aiohttp import ClientSession, ClientTimeout class Felix(Bot): def __init__(self, *args, **options): super().__init__(*args, **options) self.session = None self.flood_mode = False with open('../config.json') as conffile: self.config = json.load(conffile) self.last_errors = [] async def start(self, *args, **kwargs): self.session = ClientSession(timeout=ClientTimeout(total=30)) await super().start(self.config["bot_key"], *args, **kwargs) async def close(self): await self.session.close() await super().close() def user_is_admin(self, user): try: user_roles = [role.id for role in user.roles] except AttributeError: return False permitted_roles = self.config['admin_roles'] return any(role in permitted_roles for role in user_roles) def user_is_superuser(self, user): superusers = self.config['superusers'] return user.id in superusers client = Felix( command_prefix=when_mentioned_or('felix ', 'Felix '), description='Hi I am Felix!', max_messages=15000, intents=Intents.all(), allowed_mentions=AllowedMentions(everyone=False, users=True, roles=True) ) STARTUP_EXTENSIONS = [] for file in listdir(path.join(path.dirname(__file__), 'cogs/')): filename, ext = path.splitext(file) if '.py' in ext: STARTUP_EXTENSIONS.append(f'cogs.{filename}') for extension in reversed(STARTUP_EXTENSIONS): try: client.load_extension(f'{extension}') except Exception as e: client.last_errors.append((e, datetime.utcnow(), None, None)) exc = f'{type(e).__name__}: {e}' print(f'Failed to load extension {extension}\n{exc}') @client.event async def on_ready(): main_id = client.config['main_guild'] client.main_guild = client.get_guild(main_id) or client.guilds[0] print('\nActive in these guilds/servers:') [print(g.name) for g in client.guilds] print('\nMain guild:', client.main_guild.name) print('\nFelix-Python started successfully') return True @client.event async def on_error(event_method, *args, **kwargs): """|coro| The default error handler provided by the client. By default this prints to :data:`sys.stderr` however it could be overridden to have a different implementation. Check :func:`~discord.on_error` for more details. """ print('Default Handler: Ignoring exception in {}'.format(event_method), file=sys.stderr) traceback.print_exc() # --------------- custom code below ------------------------------- # Saving the error if it resulted from a message edit if len(args) > 1: a1, a2, *_ = args if isinstance(a1, Message) and isinstance(a2, Message): client.last_errors.append((sys.exc_info()[1], datetime.utcnow(), a2, a2.content)) await client.change_presence( activity=Activity(name='ERROR encountered', url=None, type=3) ) @client.event async def on_message(msg): # Ignore DMs if isinstance(msg.channel, DMChannel): return await client.process_commands(msg) client.run() print('Felix-Python has exited')
32.049587
93
0.676637
import json import traceback import sys from datetime import datetime from os import path, listdir from discord.ext.commands import Bot, when_mentioned_or from discord import DMChannel, Message, Activity, Intents, AllowedMentions from aiohttp import ClientSession, ClientTimeout class Felix(Bot): def __init__(self, *args, **options): super().__init__(*args, **options) self.session = None self.flood_mode = False with open('../config.json') as conffile: self.config = json.load(conffile) self.last_errors = [] async def start(self, *args, **kwargs): self.session = ClientSession(timeout=ClientTimeout(total=30)) await super().start(self.config["bot_key"], *args, **kwargs) async def close(self): await self.session.close() await super().close() def user_is_admin(self, user): try: user_roles = [role.id for role in user.roles] except AttributeError: return False permitted_roles = self.config['admin_roles'] return any(role in permitted_roles for role in user_roles) def user_is_superuser(self, user): superusers = self.config['superusers'] return user.id in superusers client = Felix( command_prefix=when_mentioned_or('felix ', 'Felix '), description='Hi I am Felix!', max_messages=15000, intents=Intents.all(), allowed_mentions=AllowedMentions(everyone=False, users=True, roles=True) ) STARTUP_EXTENSIONS = [] for file in listdir(path.join(path.dirname(__file__), 'cogs/')): filename, ext = path.splitext(file) if '.py' in ext: STARTUP_EXTENSIONS.append(f'cogs.{filename}') for extension in reversed(STARTUP_EXTENSIONS): try: client.load_extension(f'{extension}') except Exception as e: client.last_errors.append((e, datetime.utcnow(), None, None)) exc = f'{type(e).__name__}: {e}' print(f'Failed to load extension {extension}\n{exc}') @client.event async def on_ready(): main_id = client.config['main_guild'] client.main_guild = client.get_guild(main_id) or client.guilds[0] print('\nActive in these guilds/servers:') [print(g.name) for g in client.guilds] print('\nMain guild:', client.main_guild.name) print('\nFelix-Python started successfully') return True @client.event async def on_error(event_method, *args, **kwargs): print('Default Handler: Ignoring exception in {}'.format(event_method), file=sys.stderr) traceback.print_exc() if len(args) > 1: a1, a2, *_ = args if isinstance(a1, Message) and isinstance(a2, Message): client.last_errors.append((sys.exc_info()[1], datetime.utcnow(), a2, a2.content)) await client.change_presence( activity=Activity(name='ERROR encountered', url=None, type=3) ) @client.event async def on_message(msg): if isinstance(msg.channel, DMChannel): return await client.process_commands(msg) client.run() print('Felix-Python has exited')
true
true
f7fe84f5af308e1f6c379272bf01425d466b1ac6
518
py
Python
myBinaries/src/kvs/workloadGen.py
alex1230608/gem5
d5225681568102a6441ce2c32d82f5b1b45ea4e2
[ "BSD-3-Clause" ]
null
null
null
myBinaries/src/kvs/workloadGen.py
alex1230608/gem5
d5225681568102a6441ce2c32d82f5b1b45ea4e2
[ "BSD-3-Clause" ]
null
null
null
myBinaries/src/kvs/workloadGen.py
alex1230608/gem5
d5225681568102a6441ce2c32d82f5b1b45ea4e2
[ "BSD-3-Clause" ]
null
null
null
num_nic = 2 time_period = 100 separate = 10000 test_range = 2 test_repeat = 300 interval = 1 sharded = 1 readWrite = 1 print("%d"%num_nic) for nic in range(0, num_nic): print "%d"%(test_repeat*(test_range/interval)), print "" for nic in range(0, num_nic): if sharded == 1: start = nic*separate else: start = 0 end = start + test_range print "" time = 0 for i in range(0, test_repeat): for key in range(start, end, interval): time = time + time_period print("%d\t%d\t%d"%(time, key, readWrite))
17.266667
48
0.662162
num_nic = 2 time_period = 100 separate = 10000 test_range = 2 test_repeat = 300 interval = 1 sharded = 1 readWrite = 1 print("%d"%num_nic) for nic in range(0, num_nic): print "%d"%(test_repeat*(test_range/interval)), print "" for nic in range(0, num_nic): if sharded == 1: start = nic*separate else: start = 0 end = start + test_range print "" time = 0 for i in range(0, test_repeat): for key in range(start, end, interval): time = time + time_period print("%d\t%d\t%d"%(time, key, readWrite))
false
true
f7fe8605c92c4ee75d7e0097fdb100a8c6fd6e57
6,501
py
Python
bocce/utils.py
brianjpetersen/bocce
20a4845400e8759173c5391ce52f18dafbf4c678
[ "MIT" ]
null
null
null
bocce/utils.py
brianjpetersen/bocce
20a4845400e8759173c5391ce52f18dafbf4c678
[ "MIT" ]
null
null
null
bocce/utils.py
brianjpetersen/bocce
20a4845400e8759173c5391ce52f18dafbf4c678
[ "MIT" ]
null
null
null
# standard libraries import os import functools import collections import collections.abc import datetime import json import multiprocessing import threading import traceback import time # third party libraries pass # first party libraries pass __where__ = os.path.dirname(os.path.abspath(__file__)) class repeat(threading.Thread): def __init__(self, function, period, how='thread', on_error=None, args=None, kwargs=None): super(repeat, self).__init__(daemon=True) if args is None: args = () if kwargs is None: kwargs = {} if on_error is None: def on_error(exception): traceback.print_exc() print() def wrapped(): try: function(*args, **kwargs) except Exception as exception: on_error(exception) self.function = wrapped self.period = period if how == 'thread': self.How = threading.Thread elif how == 'process': self.How = multiprocessing.Process self.terminated = False self.start() def run(self): while self.terminated == False: try: start = time.time() runner = self.How(target=self.function) runner.start() runner.join() duration = time.time() - start if duration < self.period: time.sleep(self.period - duration) except: continue def terminate(self): self.terminated = True def cached_getter(allow_get=True, allow_set=True, allow_delete=True): class Wrapper: __slots__ = ('getter', 'name', 'cached_name', ) def __init__(self, getter): self.getter = getter self.name = getter.__name__ self.cached_name = '_cached_{}'.format(self.name) def __get__(self, instance, owner=None): if self.allow_get == False: raise AttributeError try: return getattr(instance, self.cached_name) except: value = self.getter(instance) setattr(instance, self.cached_name, value) return value def __set__(self, instance, value): if self.allow_set == False: raise AttributeError setattr(instance, self.cached_name, value) def __delete__(self, instance): if self.allow_delete == False: raise AttributeError delattr(instance, self.cached_name) Wrapper.allow_get = allow_get Wrapper.allow_set = allow_set Wrapper.allow_delete = allow_delete return Wrapper """ def cached_setter(allow_get=True, set_once=False, allow_delete=True): class Wrapper: __slots__ = ('name', 'setter', 'was_set', 'value', ) def __init__(self, setter): self.setter = setter self.name = setter.__name__ self.was_set = False def __get__(self, obj, type=None): if self.allow_get == False: raise AttributeError return self.value def __set__(self, obj, value): if self.was_set and self.set_once: raise AttributeError self.value = self.setter(obj, value) def __delete__(self, obj): if self.allow_delete == False: raise AttributeError delattr(obj, self.name) Wrapper.allow_get = allow_get Wrapper.allow_delete = allow_delete Wrapper.set_once = set_once return Wrapper """ def once(f): @functools.wraps(f) def decorator(*args, **kwargs): try: return f._result except AttributeError: result = f._result = f(*args, **kwargs) return result return decorator class LRUCache(collections.abc.MutableMapping): def __init__(self, size=None): if not isinstance(size, (int, float)): raise TypeError() else: if size < 0: raise ValueError() self._size = size self._cache = collections.OrderedDict() def __getitem__(self, key): return self.touch(key) def flush(self): self._cache = collections.OrderedDict() @property def overflowing(self): return len(self) > self.size def touch(self, key): value = self._cache.pop(key) self._cache[key] = value return value def __setitem__(self, key, value): self._cache[key] = value if self.size is not None: self.squeeze() @property def size(self): return self._size @size.setter def size(self, size): self._size = size self.squeeze() def squeeze(self): while self.overflowing: self._cache.popitem(last=False) def __delitem__(self, key): del self._cache[key] def __iter__(self): return iter(self._cache) def __len__(self): return len(self._cache) class When: @staticmethod def timestamp(when=None, format='%Y-%m-%dT%H:%M:%SZ'): if when is None: when = datetime.datetime.utcnow() return when.strftime(format) @staticmethod def iso_timestamp(when=None): return When.timestamp(when, format='%Y-%m-%dT%H:%M:%SZ') @staticmethod def unix_timestamp(when=None): if when is None: when = datetime.datetime.utcnow() return when.timestamp() @staticmethod def http_timestamp(when=None): return When.timestamp(when, format='%a, %d-%b-%Y %T GMT') """ @staticmethod def from_timestamp(timestamp, format='YYYY-MM-DD'): pass """ class JsonEncoder(json.JSONEncoder): def __init__(self, indent=None, serializers=None): super(JsonEncoder, self).__init__(indent=indent) if serializers is None: serializers = {} self.serializers = serializers def default(self, obj): try: serializer = self.serializers[obj.__class__] return serializer(obj) except: return super(JsonEncoder, self).default(obj)
26.21371
69
0.557607
import os import functools import collections import collections.abc import datetime import json import multiprocessing import threading import traceback import time pass pass __where__ = os.path.dirname(os.path.abspath(__file__)) class repeat(threading.Thread): def __init__(self, function, period, how='thread', on_error=None, args=None, kwargs=None): super(repeat, self).__init__(daemon=True) if args is None: args = () if kwargs is None: kwargs = {} if on_error is None: def on_error(exception): traceback.print_exc() print() def wrapped(): try: function(*args, **kwargs) except Exception as exception: on_error(exception) self.function = wrapped self.period = period if how == 'thread': self.How = threading.Thread elif how == 'process': self.How = multiprocessing.Process self.terminated = False self.start() def run(self): while self.terminated == False: try: start = time.time() runner = self.How(target=self.function) runner.start() runner.join() duration = time.time() - start if duration < self.period: time.sleep(self.period - duration) except: continue def terminate(self): self.terminated = True def cached_getter(allow_get=True, allow_set=True, allow_delete=True): class Wrapper: __slots__ = ('getter', 'name', 'cached_name', ) def __init__(self, getter): self.getter = getter self.name = getter.__name__ self.cached_name = '_cached_{}'.format(self.name) def __get__(self, instance, owner=None): if self.allow_get == False: raise AttributeError try: return getattr(instance, self.cached_name) except: value = self.getter(instance) setattr(instance, self.cached_name, value) return value def __set__(self, instance, value): if self.allow_set == False: raise AttributeError setattr(instance, self.cached_name, value) def __delete__(self, instance): if self.allow_delete == False: raise AttributeError delattr(instance, self.cached_name) Wrapper.allow_get = allow_get Wrapper.allow_set = allow_set Wrapper.allow_delete = allow_delete return Wrapper def once(f): @functools.wraps(f) def decorator(*args, **kwargs): try: return f._result except AttributeError: result = f._result = f(*args, **kwargs) return result return decorator class LRUCache(collections.abc.MutableMapping): def __init__(self, size=None): if not isinstance(size, (int, float)): raise TypeError() else: if size < 0: raise ValueError() self._size = size self._cache = collections.OrderedDict() def __getitem__(self, key): return self.touch(key) def flush(self): self._cache = collections.OrderedDict() @property def overflowing(self): return len(self) > self.size def touch(self, key): value = self._cache.pop(key) self._cache[key] = value return value def __setitem__(self, key, value): self._cache[key] = value if self.size is not None: self.squeeze() @property def size(self): return self._size @size.setter def size(self, size): self._size = size self.squeeze() def squeeze(self): while self.overflowing: self._cache.popitem(last=False) def __delitem__(self, key): del self._cache[key] def __iter__(self): return iter(self._cache) def __len__(self): return len(self._cache) class When: @staticmethod def timestamp(when=None, format='%Y-%m-%dT%H:%M:%SZ'): if when is None: when = datetime.datetime.utcnow() return when.strftime(format) @staticmethod def iso_timestamp(when=None): return When.timestamp(when, format='%Y-%m-%dT%H:%M:%SZ') @staticmethod def unix_timestamp(when=None): if when is None: when = datetime.datetime.utcnow() return when.timestamp() @staticmethod def http_timestamp(when=None): return When.timestamp(when, format='%a, %d-%b-%Y %T GMT') class JsonEncoder(json.JSONEncoder): def __init__(self, indent=None, serializers=None): super(JsonEncoder, self).__init__(indent=indent) if serializers is None: serializers = {} self.serializers = serializers def default(self, obj): try: serializer = self.serializers[obj.__class__] return serializer(obj) except: return super(JsonEncoder, self).default(obj)
true
true
f7fe88093ad7d02c94f780d3849b03a3795789a9
14,209
py
Python
JFit/physics/nu_oscillation/Prob_e2e.py
J-Fit/JFit
85c67aaca0295a75714db2011e35222dabf50c38
[ "MIT" ]
1
2021-03-02T12:51:42.000Z
2021-03-02T12:51:42.000Z
JFit/physics/nu_oscillation/Prob_e2e.py
J-Fit/JFit
85c67aaca0295a75714db2011e35222dabf50c38
[ "MIT" ]
null
null
null
JFit/physics/nu_oscillation/Prob_e2e.py
J-Fit/JFit
85c67aaca0295a75714db2011e35222dabf50c38
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- ''' pure nue -> nue author: Jinnan Zhang zhangjinnan@ihep.ac.cn date: 2021.03.08 ''' import numpy as np def get_parser(): import argparse parser = argparse.ArgumentParser(description="Check or show the oscillation pattern.") parser.add_argument( "--cME", action="store_true", help="Check the matter effect model, the JUNO Yellow book model, the Yufeng model, and the Hiroshi model." ) parser.set_defaults(cME=False) parser.add_argument("--pNMO", action="store_true", help="Show pattern of neutrino mass ordering.") parser.set_defaults(pNMO=False) parser.add_argument( "--NMO-op", type=str, help="The NMO show option.") return parser class Prob_e2e: def __init__(self, NMO=1, ME=True, NameSpace='PDG2020'): self.NameSpace = NameSpace if NMO == 1: self.NMO = 'normal' # mass ordering, 1 for normal, others for invert else: self.NMO = 'invert' self.ME = ME # in Matter or not import os import yaml curPath = os.path.dirname(os.path.realpath(__file__)) OsciPar_yamlPath = curPath + "/data/OscillationParameters.yaml" f_osci_par = open(OsciPar_yamlPath) self.OsciPar = yaml.load(f_osci_par.read(), Loader=yaml.Loader) self.Sin_sqTheta12 = self.OsciPar[self.NameSpace][self.NMO]['sinsq12'] self.DeltaM21_sq = self.OsciPar[self.NameSpace][self.NMO]['dmsq21'] self.DeltaM31_sq = self.OsciPar[self.NameSpace][self.NMO]['dmsq31'] self.DeltaM32_sq = self.OsciPar[self.NameSpace][self.NMO]['dmsq32'] self.Sin_sqTheta13 = self.OsciPar[self.NameSpace][self.NMO]['sinsq13'] self.matter_density = self.OsciPar['MatterDensity'] self.cal_matter_potential() def out(self): print(self.A_MatPoten_0) def cal_matter_potential(self): M_unified_atomic_kg = 1.6605390666e-27 N_e = self.matter_density / M_unified_atomic_kg / 2.0 hbar_C = 197.3269804 # MeV.fm G_F = 1.1663787e-5 #- sign for antineutrinos self.A_MatPoten_0 = -2 * np.sqrt( 2) * G_F * N_e * hbar_C * hbar_C * hbar_C * 1e-39 def get_prob_e2e_Amir(self, Enu, baseline, ME=True): ''' Enu: MeV, baseline: cm Based on: arXiv:1910.12900, from Amir N. Khan, Hiroshi Nunokawa,... ''' Sin_sqTheta12 = self.Sin_sqTheta12 DeltaM21_sq = self.DeltaM21_sq DeltaM31_sq = self.DeltaM31_sq DeltaM32_sq = self.DeltaM32_sq Sin_sqTheta13 = self.Sin_sqTheta13 E = Enu BaseLine = baseline * 1e-2 # cm to m prob = 0 Sinsq2Theta12 = (4 * self.Sin_sqTheta12 * (1 - self.Sin_sqTheta12)) Sinsq2Theta13 = (4 * self.Sin_sqTheta13 * (1 - self.Sin_sqTheta13)) if ME: # reverse the relation A_MatPoten = E * self.A_MatPoten_0 # eq. 6 DeltaMsq_ee = DeltaM31_sq * (1 - Sin_sqTheta12) + DeltaM32_sq * Sin_sqTheta12 Cos_2Theta_12 = 1 - 2 * Sin_sqTheta12 Cos_2Theta_13 = 1 - 2 * Sin_sqTheta13 # eq. 8 DeltaMsq_ee_M = DeltaMsq_ee*np.sqrt((Cos_2Theta_13-A_MatPoten/DeltaMsq_ee)**2+Sinsq2Theta13) # eq. 7 Cos_2Theta_13_M=(DeltaMsq_ee*Cos_2Theta_13-A_MatPoten)/DeltaMsq_ee_M # eq. 11 A_MatPoten_prime=0.5*(A_MatPoten+DeltaMsq_ee-DeltaMsq_ee_M) # eq.12 Cos_sq_theta13M_minus_theta13=(DeltaMsq_ee_M+DeltaMsq_ee-A_MatPoten*Cos_2Theta_13)*0.5/DeltaMsq_ee_M # eq. 10 DeltaM21_sq_M= DeltaM21_sq*np.sqrt((Cos_2Theta_12-A_MatPoten_prime/DeltaM21_sq)**2+Cos_sq_theta13M_minus_theta13*Sinsq2Theta12) # eq. 9 Cos_2Theta_12_M=(DeltaM21_sq*Cos_2Theta_12-A_MatPoten_prime)/DeltaM21_sq_M Sin_sqTheta13_M=(1-Cos_2Theta_13_M)/2 Sinsq2Theta13_M = 1-Cos_2Theta_13_M*Cos_2Theta_13_M Sin_sqTheta12_M = (1-Cos_2Theta_12_M)/2 Sinsq2Theta12_M=1-Cos_2Theta_12_M*Cos_2Theta_12_M DeltaM31_sq_M = DeltaMsq_ee_M+Sin_sqTheta12_M*DeltaM21_sq_M DeltaM32_sq_M = DeltaM31_sq_M - DeltaM21_sq_M Delta21 = 1.266932679815373 * DeltaM21_sq_M * BaseLine / E Delta31 = 1.266932679815373 * DeltaM31_sq_M * BaseLine / E Delta32 = 1.266932679815373 * DeltaM32_sq_M * BaseLine / E prob = 1. - Sinsq2Theta13_M * ( (1 - Sin_sqTheta12_M) * np.sin(Delta31)**2. + Sin_sqTheta12_M * np.sin(Delta32)**2.) - ( (1 - Sin_sqTheta13_M)** 2.) * Sinsq2Theta12_M * np.sin(Delta21)**2. else: Delta21 = 1.266932679815373 * self.DeltaM21_sq * BaseLine / E Delta31 = 1.266932679815373 * self.DeltaM31_sq * BaseLine / E Delta32 = 1.266932679815373 * self.DeltaM32_sq * BaseLine / E prob = 1. - Sinsq2Theta13 * ( (1 - self.Sin_sqTheta12) * np.sin(Delta31)**2. + self.Sin_sqTheta12 * np.sin(Delta32)**2.) - ( (1 - self.Sin_sqTheta13)** 2.) * Sinsq2Theta12 * np.sin(Delta21)**2. return prob def get_prob_e2e_Yufeng(self, Enu, baseline, ME=True): ''' Enu: MeV, baseline: cm Based on: https://juno.ihep.ac.cn/cgi-bin/Dev_DocDB/ShowDocument?docid=6859 ''' Sin_sqTheta12 = self.Sin_sqTheta12 DeltaM21_sq = self.DeltaM21_sq DeltaM31_sq = self.DeltaM31_sq DeltaM32_sq = self.DeltaM32_sq Sin_sqTheta13 = self.Sin_sqTheta13 E = Enu BaseLine = baseline * 1e-2 # cm to m prob = 0 Sinsq2Theta12 = (4 * self.Sin_sqTheta12 * (1 - self.Sin_sqTheta12)) Sinsq2Theta13 = (4 * self.Sin_sqTheta13 * (1 - self.Sin_sqTheta13)) if ME: # reverse the relation, for neutrino A_MatPoten = E * self.A_MatPoten_0 Delta_c = DeltaM31_sq * (1 - Sin_sqTheta12) + DeltaM32_sq * Sin_sqTheta12 # eq. 8 alpha_c = DeltaM21_sq / Delta_c # eq .8 A_star = A_MatPoten * (1 - Sin_sqTheta13) / DeltaM21_sq # eq .9 A_c = A_MatPoten / Delta_c # eq. 9 Cos_2Theta_12 = 1 - 2 * Sin_sqTheta12 Cos_2Theta_13 = 1 - 2 * Sin_sqTheta13 # C_hat_12 = np.sqrt(1 - 2.0 * A_star * Cos_2Theta_12 +A_star * A_star) # C_hat_13 = np.sqrt(1 - 2.0 * A_c * Cos_2Theta_13 +A_c * A_c) C_hat_12_prime = np.sqrt(1 - 2.0 * A_star * Cos_2Theta_12 +A_star * A_star) C_hat_13_prime = np.sqrt(1 - 2.0 * A_c * Cos_2Theta_13 + A_c * A_c) Cos_sq_Theta12_tilde = 0.5*(1-(A_star-Cos_2Theta_12)/C_hat_12_prime) Cos_sq_Theta13_tilde = 0.5*(1-(A_c-Cos_2Theta_13)/C_hat_13_prime) Sin_sqTheta13_M=1-Cos_sq_Theta13_tilde Sinsq2Theta13_M = 4*Sin_sqTheta13_M*Cos_sq_Theta13_tilde Sin_sqTheta12_M = 1-Cos_sq_Theta12_tilde Sinsq2Theta12_M=4*Sin_sqTheta12_M*Cos_sq_Theta12_tilde DeltaM21_sq_M = Delta_c*(0.5*(1+A_c-C_hat_13_prime)+alpha_c*(C_hat_12_prime-A_star)) DeltaM31_sq_M = Delta_c*(0.5*(1+A_c+C_hat_13_prime)+alpha_c*0.5*(C_hat_12_prime-A_star-Cos_2Theta_12)) DeltaM32_sq_M = DeltaM31_sq_M - DeltaM21_sq_M Delta21 = 1.266932679815373 * DeltaM21_sq_M * BaseLine / E Delta31 = 1.266932679815373 * DeltaM31_sq_M * BaseLine / E Delta32 = 1.266932679815373 * DeltaM32_sq_M * BaseLine / E prob = 1. - Sinsq2Theta13_M * ( (1 - Sin_sqTheta12_M) * np.sin(Delta31)**2. + Sin_sqTheta12_M * np.sin(Delta32)**2.) - ( (1 - Sin_sqTheta13_M)** 2.) * Sinsq2Theta12_M * np.sin(Delta21)**2. # print() else: Delta21 = 1.266932679815373 * self.DeltaM21_sq * BaseLine / E Delta31 = 1.266932679815373 * self.DeltaM31_sq * BaseLine / E Delta32 = 1.266932679815373 * self.DeltaM32_sq * BaseLine / E prob = 1. - Sinsq2Theta13 * ( (1 - self.Sin_sqTheta12) * np.sin(Delta31)**2. + self.Sin_sqTheta12 * np.sin(Delta32)**2.) - ( (1 - self.Sin_sqTheta13)** 2.) * Sinsq2Theta12 * np.sin(Delta21)**2. # print("Yufeng: ",self.DeltaM31_sq) return prob def get_prob_e2e_YB(self, Enu, baseline, ME=True): ''' Enu: MeV, baseline: cm ''' E = Enu BaseLine = baseline * 1e-2 # cm to m prob = 0 Sinsq2Theta12 = (4 * self.Sin_sqTheta12 * (1 - self.Sin_sqTheta12)) Sinsq2Theta13 = (4 * self.Sin_sqTheta13 * (1 - self.Sin_sqTheta13)) if ME: A_MatPoten = E * self.A_MatPoten_0 eta_12 = (1 - 2 * self.Sin_sqTheta12 - A_MatPoten / self.DeltaM21_sq) * ( 1 - 2 * self.Sin_sqTheta12 - A_MatPoten / self.DeltaM21_sq) + Sinsq2Theta12 eta_13 = (1 - 2 * self.Sin_sqTheta13 - A_MatPoten / self.DeltaM31_sq) * ( 1 - 2 * self.Sin_sqTheta13 - A_MatPoten / self.DeltaM31_sq) + Sinsq2Theta13 Sinsq2Theta12_M = Sinsq2Theta12 / eta_12 Sinsq2Theta13_M = Sinsq2Theta13 / eta_13 Sin_sqTheta12_M = (1 - np.sqrt(1 - Sinsq2Theta12_M)) / 2. Sin_sqTheta13_M = (1 - np.sqrt(1 - Sinsq2Theta13_M)) / 2. DeltaM21_sq_M = self.DeltaM21_sq * np.sqrt(eta_12) DeltaM31_sq_M = self.DeltaM31_sq * np.sqrt(eta_13) DeltaM32_sq_M = DeltaM31_sq_M - DeltaM21_sq_M Delta21 = 1.266932679815373 * DeltaM21_sq_M * BaseLine / E Delta31 = 1.266932679815373 * DeltaM31_sq_M * BaseLine / E Delta32 = 1.266932679815373 * DeltaM32_sq_M * BaseLine / E prob = 1. - Sinsq2Theta13_M * ( (1 - Sin_sqTheta12_M) * np.sin(Delta31)**2. + Sin_sqTheta12_M * np.sin(Delta32)**2.) - ( (1 - Sin_sqTheta13_M)** 2.) * Sinsq2Theta12_M * np.sin(Delta21)**2. else: Delta21 = 1.266932679815373 * self.DeltaM21_sq * BaseLine / E Delta31 = 1.266932679815373 * self.DeltaM31_sq * BaseLine / E Delta32 = 1.266932679815373 * self.DeltaM32_sq * BaseLine / E prob = 1. - Sinsq2Theta13 * ( (1 - self.Sin_sqTheta12) * np.sin(Delta31)**2. + self.Sin_sqTheta12 * np.sin(Delta32)**2.) - ( (1 - self.Sin_sqTheta13)** 2.) * Sinsq2Theta12 * np.sin(Delta21)**2. # print("YB: ",self.DeltaM31_sq) return prob def Check_YB_Hermitian(E_low=0.8, E_up=15., N=1000, BaseLine=52.5e5,ME=1): def GetAsy(a, b): # return 2 * (a - b) / (a + b) return (a - b) / ( b) Es = np.linspace(E_low, E_up, N) # JUNO Yellow formula P_e2e_YB = Prob_e2e(NMO=1) y_YB = P_e2e_YB.get_prob_e2e_YB(Es, baseline=BaseLine,ME=ME) y_Yufeng=P_e2e_YB.get_prob_e2e_Yufeng(Es, baseline=BaseLine,ME=ME) y_Amir=P_e2e_YB.get_prob_e2e_Amir(Es, baseline=BaseLine,ME=ME) # Hermitian approach import sys sys.path.append('../..') from physics.nu_oscillation import oscprob3nu, hamiltonians3nu from physics.nu_oscillation.globaldefs import CONV_CM_TO_INV_EV, VCC_EARTH_CRUST, S23_NO_BF, DCP_NO_BF S12_NO_BF = np.sqrt(P_e2e_YB.Sin_sqTheta12) S13_NO_BF = np.sqrt(P_e2e_YB.Sin_sqTheta13) D21_NO_BF = P_e2e_YB.DeltaM21_sq D31_NO_BF = P_e2e_YB.DeltaM31_sq h_vacuum_energy_indep = hamiltonians3nu.hamiltonian_3nu_vacuum_energy_independent( S12_NO_BF, S23_NO_BF, S13_NO_BF, -DCP_NO_BF, D21_NO_BF, D31_NO_BF) # sign - DCP_NO_BF for antineutrinos y_Het = np.zeros(N) for i, energy in enumerate(Es): # sign - for antineutrinos if ME: h_matter = hamiltonians3nu.hamiltonian_3nu_matter(h_vacuum_energy_indep, energy * 1e6,-VCC_EARTH_CRUST) else: h_matter = np.multiply(1/(energy*1e6),h_vacuum_energy_indep) Pee, Pem, Pet, Pme, Pmm, Pmt, Pte, Ptm, Ptt = oscprob3nu.probabilities_3nu( h_matter, BaseLine * CONV_CM_TO_INV_EV) y_Het[i] = Pee import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages plt.style.use('../../detector/DYB_like/lib/Paper.mplstyle') with PdfPages('results/ME_models.pdf') as pdf: fig, ax = plt.subplots() ax.set_ylabel(r'$\frac{2\cdot(A-B)}{(A+B)}$') ax.set_xlabel('Neutrino Energy [MeV]') # ax.plot(Es, y_Het, label='Hamiltonian approach') # ax.plot(Es, y_YB, label='Yellow Book Approach') # ax.plot(Es, y_Yufeng, label='Yufeng Approach') # ax.plot(Es, y_Amir, label='Amir Approach') # ax.plot(Es, GetAsy(y_YB, y_Het), label='YB/Hamiltonian') # ax.plot(Es, GetAsy(y_Amir,y_Yufeng), label='Amir/Yufeng') ax.plot(Es, GetAsy(y_Amir,y_Yufeng), label='Amir/Yufeng') ax.text(y=0.,x=6,s="Amir: arXiv:1910.12900\n Yufeng: JUNO-doc-6859") ax.legend() pdf.savefig() # ax.cla() # fig.savefig('./results/Yufeng_Amir.png') ax.plot(Es, GetAsy(y_YB, y_Het), label='YB/Hamiltonian') ax.plot(Es, GetAsy(y_YB, y_Yufeng), label='YB/Yufeng') ax.plot(Es, GetAsy(y_Yufeng,y_Het), label='Yufeng/Hamiltonian') # ax.plot(Es, GetAsy(y_Amir,y_Het), label='Amir/Hamiltonian') ax.set_ylabel(r'$\frac{2\cdot(A-B)}{(A+B)}$') ax.set_xlabel('Neutrino Energy [MeV]') ax.legend() pdf.savefig() # fig.savefig('./results/four_model.png') # plt.show() def show_NMO_pattern(pattern='nue2nue'): print(pattern) if __name__ == "__main__": parser = get_parser() args = parser.parse_args() if args.cME: Check_YB_Hermitian() if args.pNMO: show_NMO_pattern(args.NMO_op)
44.823344
139
0.597157
import numpy as np def get_parser(): import argparse parser = argparse.ArgumentParser(description="Check or show the oscillation pattern.") parser.add_argument( "--cME", action="store_true", help="Check the matter effect model, the JUNO Yellow book model, the Yufeng model, and the Hiroshi model." ) parser.set_defaults(cME=False) parser.add_argument("--pNMO", action="store_true", help="Show pattern of neutrino mass ordering.") parser.set_defaults(pNMO=False) parser.add_argument( "--NMO-op", type=str, help="The NMO show option.") return parser class Prob_e2e: def __init__(self, NMO=1, ME=True, NameSpace='PDG2020'): self.NameSpace = NameSpace if NMO == 1: self.NMO = 'normal' else: self.NMO = 'invert' self.ME = ME import os import yaml curPath = os.path.dirname(os.path.realpath(__file__)) OsciPar_yamlPath = curPath + "/data/OscillationParameters.yaml" f_osci_par = open(OsciPar_yamlPath) self.OsciPar = yaml.load(f_osci_par.read(), Loader=yaml.Loader) self.Sin_sqTheta12 = self.OsciPar[self.NameSpace][self.NMO]['sinsq12'] self.DeltaM21_sq = self.OsciPar[self.NameSpace][self.NMO]['dmsq21'] self.DeltaM31_sq = self.OsciPar[self.NameSpace][self.NMO]['dmsq31'] self.DeltaM32_sq = self.OsciPar[self.NameSpace][self.NMO]['dmsq32'] self.Sin_sqTheta13 = self.OsciPar[self.NameSpace][self.NMO]['sinsq13'] self.matter_density = self.OsciPar['MatterDensity'] self.cal_matter_potential() def out(self): print(self.A_MatPoten_0) def cal_matter_potential(self): M_unified_atomic_kg = 1.6605390666e-27 N_e = self.matter_density / M_unified_atomic_kg / 2.0 hbar_C = 197.3269804 G_F = 1.1663787e-5 self.A_MatPoten_0 = -2 * np.sqrt( 2) * G_F * N_e * hbar_C * hbar_C * hbar_C * 1e-39 def get_prob_e2e_Amir(self, Enu, baseline, ME=True): Sin_sqTheta12 = self.Sin_sqTheta12 DeltaM21_sq = self.DeltaM21_sq DeltaM31_sq = self.DeltaM31_sq DeltaM32_sq = self.DeltaM32_sq Sin_sqTheta13 = self.Sin_sqTheta13 E = Enu BaseLine = baseline * 1e-2 prob = 0 Sinsq2Theta12 = (4 * self.Sin_sqTheta12 * (1 - self.Sin_sqTheta12)) Sinsq2Theta13 = (4 * self.Sin_sqTheta13 * (1 - self.Sin_sqTheta13)) if ME: A_MatPoten = E * self.A_MatPoten_0 DeltaMsq_ee = DeltaM31_sq * (1 - Sin_sqTheta12) + DeltaM32_sq * Sin_sqTheta12 Cos_2Theta_12 = 1 - 2 * Sin_sqTheta12 Cos_2Theta_13 = 1 - 2 * Sin_sqTheta13 DeltaMsq_ee_M = DeltaMsq_ee*np.sqrt((Cos_2Theta_13-A_MatPoten/DeltaMsq_ee)**2+Sinsq2Theta13) Cos_2Theta_13_M=(DeltaMsq_ee*Cos_2Theta_13-A_MatPoten)/DeltaMsq_ee_M A_MatPoten_prime=0.5*(A_MatPoten+DeltaMsq_ee-DeltaMsq_ee_M) Cos_sq_theta13M_minus_theta13=(DeltaMsq_ee_M+DeltaMsq_ee-A_MatPoten*Cos_2Theta_13)*0.5/DeltaMsq_ee_M DeltaM21_sq_M= DeltaM21_sq*np.sqrt((Cos_2Theta_12-A_MatPoten_prime/DeltaM21_sq)**2+Cos_sq_theta13M_minus_theta13*Sinsq2Theta12) Cos_2Theta_12_M=(DeltaM21_sq*Cos_2Theta_12-A_MatPoten_prime)/DeltaM21_sq_M Sin_sqTheta13_M=(1-Cos_2Theta_13_M)/2 Sinsq2Theta13_M = 1-Cos_2Theta_13_M*Cos_2Theta_13_M Sin_sqTheta12_M = (1-Cos_2Theta_12_M)/2 Sinsq2Theta12_M=1-Cos_2Theta_12_M*Cos_2Theta_12_M DeltaM31_sq_M = DeltaMsq_ee_M+Sin_sqTheta12_M*DeltaM21_sq_M DeltaM32_sq_M = DeltaM31_sq_M - DeltaM21_sq_M Delta21 = 1.266932679815373 * DeltaM21_sq_M * BaseLine / E Delta31 = 1.266932679815373 * DeltaM31_sq_M * BaseLine / E Delta32 = 1.266932679815373 * DeltaM32_sq_M * BaseLine / E prob = 1. - Sinsq2Theta13_M * ( (1 - Sin_sqTheta12_M) * np.sin(Delta31)**2. + Sin_sqTheta12_M * np.sin(Delta32)**2.) - ( (1 - Sin_sqTheta13_M)** 2.) * Sinsq2Theta12_M * np.sin(Delta21)**2. else: Delta21 = 1.266932679815373 * self.DeltaM21_sq * BaseLine / E Delta31 = 1.266932679815373 * self.DeltaM31_sq * BaseLine / E Delta32 = 1.266932679815373 * self.DeltaM32_sq * BaseLine / E prob = 1. - Sinsq2Theta13 * ( (1 - self.Sin_sqTheta12) * np.sin(Delta31)**2. + self.Sin_sqTheta12 * np.sin(Delta32)**2.) - ( (1 - self.Sin_sqTheta13)** 2.) * Sinsq2Theta12 * np.sin(Delta21)**2. return prob def get_prob_e2e_Yufeng(self, Enu, baseline, ME=True): Sin_sqTheta12 = self.Sin_sqTheta12 DeltaM21_sq = self.DeltaM21_sq DeltaM31_sq = self.DeltaM31_sq DeltaM32_sq = self.DeltaM32_sq Sin_sqTheta13 = self.Sin_sqTheta13 E = Enu BaseLine = baseline * 1e-2 prob = 0 Sinsq2Theta12 = (4 * self.Sin_sqTheta12 * (1 - self.Sin_sqTheta12)) Sinsq2Theta13 = (4 * self.Sin_sqTheta13 * (1 - self.Sin_sqTheta13)) if ME: A_MatPoten = E * self.A_MatPoten_0 Delta_c = DeltaM31_sq * (1 - Sin_sqTheta12) + DeltaM32_sq * Sin_sqTheta12 alpha_c = DeltaM21_sq / Delta_c A_star = A_MatPoten * (1 - Sin_sqTheta13) / DeltaM21_sq A_c = A_MatPoten / Delta_c Cos_2Theta_12 = 1 - 2 * Sin_sqTheta12 Cos_2Theta_13 = 1 - 2 * Sin_sqTheta13 C_hat_12_prime = np.sqrt(1 - 2.0 * A_star * Cos_2Theta_12 +A_star * A_star) C_hat_13_prime = np.sqrt(1 - 2.0 * A_c * Cos_2Theta_13 + A_c * A_c) Cos_sq_Theta12_tilde = 0.5*(1-(A_star-Cos_2Theta_12)/C_hat_12_prime) Cos_sq_Theta13_tilde = 0.5*(1-(A_c-Cos_2Theta_13)/C_hat_13_prime) Sin_sqTheta13_M=1-Cos_sq_Theta13_tilde Sinsq2Theta13_M = 4*Sin_sqTheta13_M*Cos_sq_Theta13_tilde Sin_sqTheta12_M = 1-Cos_sq_Theta12_tilde Sinsq2Theta12_M=4*Sin_sqTheta12_M*Cos_sq_Theta12_tilde DeltaM21_sq_M = Delta_c*(0.5*(1+A_c-C_hat_13_prime)+alpha_c*(C_hat_12_prime-A_star)) DeltaM31_sq_M = Delta_c*(0.5*(1+A_c+C_hat_13_prime)+alpha_c*0.5*(C_hat_12_prime-A_star-Cos_2Theta_12)) DeltaM32_sq_M = DeltaM31_sq_M - DeltaM21_sq_M Delta21 = 1.266932679815373 * DeltaM21_sq_M * BaseLine / E Delta31 = 1.266932679815373 * DeltaM31_sq_M * BaseLine / E Delta32 = 1.266932679815373 * DeltaM32_sq_M * BaseLine / E prob = 1. - Sinsq2Theta13_M * ( (1 - Sin_sqTheta12_M) * np.sin(Delta31)**2. + Sin_sqTheta12_M * np.sin(Delta32)**2.) - ( (1 - Sin_sqTheta13_M)** 2.) * Sinsq2Theta12_M * np.sin(Delta21)**2. else: Delta21 = 1.266932679815373 * self.DeltaM21_sq * BaseLine / E Delta31 = 1.266932679815373 * self.DeltaM31_sq * BaseLine / E Delta32 = 1.266932679815373 * self.DeltaM32_sq * BaseLine / E prob = 1. - Sinsq2Theta13 * ( (1 - self.Sin_sqTheta12) * np.sin(Delta31)**2. + self.Sin_sqTheta12 * np.sin(Delta32)**2.) - ( (1 - self.Sin_sqTheta13)** 2.) * Sinsq2Theta12 * np.sin(Delta21)**2. return prob def get_prob_e2e_YB(self, Enu, baseline, ME=True): E = Enu BaseLine = baseline * 1e-2 prob = 0 Sinsq2Theta12 = (4 * self.Sin_sqTheta12 * (1 - self.Sin_sqTheta12)) Sinsq2Theta13 = (4 * self.Sin_sqTheta13 * (1 - self.Sin_sqTheta13)) if ME: A_MatPoten = E * self.A_MatPoten_0 eta_12 = (1 - 2 * self.Sin_sqTheta12 - A_MatPoten / self.DeltaM21_sq) * ( 1 - 2 * self.Sin_sqTheta12 - A_MatPoten / self.DeltaM21_sq) + Sinsq2Theta12 eta_13 = (1 - 2 * self.Sin_sqTheta13 - A_MatPoten / self.DeltaM31_sq) * ( 1 - 2 * self.Sin_sqTheta13 - A_MatPoten / self.DeltaM31_sq) + Sinsq2Theta13 Sinsq2Theta12_M = Sinsq2Theta12 / eta_12 Sinsq2Theta13_M = Sinsq2Theta13 / eta_13 Sin_sqTheta12_M = (1 - np.sqrt(1 - Sinsq2Theta12_M)) / 2. Sin_sqTheta13_M = (1 - np.sqrt(1 - Sinsq2Theta13_M)) / 2. DeltaM21_sq_M = self.DeltaM21_sq * np.sqrt(eta_12) DeltaM31_sq_M = self.DeltaM31_sq * np.sqrt(eta_13) DeltaM32_sq_M = DeltaM31_sq_M - DeltaM21_sq_M Delta21 = 1.266932679815373 * DeltaM21_sq_M * BaseLine / E Delta31 = 1.266932679815373 * DeltaM31_sq_M * BaseLine / E Delta32 = 1.266932679815373 * DeltaM32_sq_M * BaseLine / E prob = 1. - Sinsq2Theta13_M * ( (1 - Sin_sqTheta12_M) * np.sin(Delta31)**2. + Sin_sqTheta12_M * np.sin(Delta32)**2.) - ( (1 - Sin_sqTheta13_M)** 2.) * Sinsq2Theta12_M * np.sin(Delta21)**2. else: Delta21 = 1.266932679815373 * self.DeltaM21_sq * BaseLine / E Delta31 = 1.266932679815373 * self.DeltaM31_sq * BaseLine / E Delta32 = 1.266932679815373 * self.DeltaM32_sq * BaseLine / E prob = 1. - Sinsq2Theta13 * ( (1 - self.Sin_sqTheta12) * np.sin(Delta31)**2. + self.Sin_sqTheta12 * np.sin(Delta32)**2.) - ( (1 - self.Sin_sqTheta13)** 2.) * Sinsq2Theta12 * np.sin(Delta21)**2. return prob def Check_YB_Hermitian(E_low=0.8, E_up=15., N=1000, BaseLine=52.5e5,ME=1): def GetAsy(a, b): return (a - b) / ( b) Es = np.linspace(E_low, E_up, N) P_e2e_YB = Prob_e2e(NMO=1) y_YB = P_e2e_YB.get_prob_e2e_YB(Es, baseline=BaseLine,ME=ME) y_Yufeng=P_e2e_YB.get_prob_e2e_Yufeng(Es, baseline=BaseLine,ME=ME) y_Amir=P_e2e_YB.get_prob_e2e_Amir(Es, baseline=BaseLine,ME=ME) import sys sys.path.append('../..') from physics.nu_oscillation import oscprob3nu, hamiltonians3nu from physics.nu_oscillation.globaldefs import CONV_CM_TO_INV_EV, VCC_EARTH_CRUST, S23_NO_BF, DCP_NO_BF S12_NO_BF = np.sqrt(P_e2e_YB.Sin_sqTheta12) S13_NO_BF = np.sqrt(P_e2e_YB.Sin_sqTheta13) D21_NO_BF = P_e2e_YB.DeltaM21_sq D31_NO_BF = P_e2e_YB.DeltaM31_sq h_vacuum_energy_indep = hamiltonians3nu.hamiltonian_3nu_vacuum_energy_independent( S12_NO_BF, S23_NO_BF, S13_NO_BF, -DCP_NO_BF, D21_NO_BF, D31_NO_BF) y_Het = np.zeros(N) for i, energy in enumerate(Es): if ME: h_matter = hamiltonians3nu.hamiltonian_3nu_matter(h_vacuum_energy_indep, energy * 1e6,-VCC_EARTH_CRUST) else: h_matter = np.multiply(1/(energy*1e6),h_vacuum_energy_indep) Pee, Pem, Pet, Pme, Pmm, Pmt, Pte, Ptm, Ptt = oscprob3nu.probabilities_3nu( h_matter, BaseLine * CONV_CM_TO_INV_EV) y_Het[i] = Pee import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages plt.style.use('../../detector/DYB_like/lib/Paper.mplstyle') with PdfPages('results/ME_models.pdf') as pdf: fig, ax = plt.subplots() ax.set_ylabel(r'$\frac{2\cdot(A-B)}{(A+B)}$') ax.set_xlabel('Neutrino Energy [MeV]') ax.plot(Es, GetAsy(y_Amir,y_Yufeng), label='Amir/Yufeng') ax.text(y=0.,x=6,s="Amir: arXiv:1910.12900\n Yufeng: JUNO-doc-6859") ax.legend() pdf.savefig() ax.plot(Es, GetAsy(y_YB, y_Het), label='YB/Hamiltonian') ax.plot(Es, GetAsy(y_YB, y_Yufeng), label='YB/Yufeng') ax.plot(Es, GetAsy(y_Yufeng,y_Het), label='Yufeng/Hamiltonian') ax.set_ylabel(r'$\frac{2\cdot(A-B)}{(A+B)}$') ax.set_xlabel('Neutrino Energy [MeV]') ax.legend() pdf.savefig() def show_NMO_pattern(pattern='nue2nue'): print(pattern) if __name__ == "__main__": parser = get_parser() args = parser.parse_args() if args.cME: Check_YB_Hermitian() if args.pNMO: show_NMO_pattern(args.NMO_op)
true
true
f7fe881573c50b01cca6dca48fde1cc4ad374b83
2,316
py
Python
examples/ami/sd0/local/dataio.py
phecda-xu/PaddleSpeech
6bf0d3bf57229091a74912633e837dabc6215c86
[ "Apache-2.0" ]
1
2022-02-26T01:48:00.000Z
2022-02-26T01:48:00.000Z
examples/ami/sd0/local/dataio.py
ziwenag/PaddleSpeech
89e69ee10ee02b875af663146bc46fcf095e812a
[ "Apache-2.0" ]
null
null
null
examples/ami/sd0/local/dataio.py
ziwenag/PaddleSpeech
89e69ee10ee02b875af663146bc46fcf095e812a
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Data reading and writing. Authors * qingenz123@126.com (Qingen ZHAO) 2022 """ import os import pickle def save_pkl(obj, file): """Save an object in pkl format. Arguments --------- obj : object Object to save in pkl format file : str Path to the output file sampling_rate : int Sampling rate of the audio file, TODO: this is not used? Example ------- >>> tmpfile = os.path.join(getfixture('tmpdir'), "example.pkl") >>> save_pkl([1, 2, 3, 4, 5], tmpfile) >>> load_pkl(tmpfile) [1, 2, 3, 4, 5] """ with open(file, "wb") as f: pickle.dump(obj, f) def load_pickle(pickle_path): """Utility function for loading .pkl pickle files. Arguments --------- pickle_path : str Path to pickle file. Returns ------- out : object Python object loaded from pickle. """ with open(pickle_path, "rb") as f: out = pickle.load(f) return out def load_pkl(file): """Loads a pkl file. For an example, see `save_pkl`. Arguments --------- file : str Path to the input pkl file. Returns ------- The loaded object. """ # Deals with the situation where two processes are trying # to access the same label dictionary by creating a lock count = 100 while count > 0: if os.path.isfile(file + ".lock"): time.sleep(1) count -= 1 else: break try: open(file + ".lock", "w").close() with open(file, "rb") as f: return pickle.load(f) finally: if os.path.isfile(file + ".lock"): os.remove(file + ".lock")
23.632653
74
0.6019
import os import pickle def save_pkl(obj, file): with open(file, "wb") as f: pickle.dump(obj, f) def load_pickle(pickle_path): with open(pickle_path, "rb") as f: out = pickle.load(f) return out def load_pkl(file): count = 100 while count > 0: if os.path.isfile(file + ".lock"): time.sleep(1) count -= 1 else: break try: open(file + ".lock", "w").close() with open(file, "rb") as f: return pickle.load(f) finally: if os.path.isfile(file + ".lock"): os.remove(file + ".lock")
true
true
f7fe89ff2c106eb98d907bf2dbfdab13c48c8747
2,223
py
Python
squeezer/onnx/export.py
esceptico/squeezer
98bc4c7923c6aa3b12ac81444d79392826fc34c6
[ "MIT" ]
29
2021-11-16T18:50:54.000Z
2022-03-13T08:18:29.000Z
squeezer/onnx/export.py
esceptico/squeezer
98bc4c7923c6aa3b12ac81444d79392826fc34c6
[ "MIT" ]
null
null
null
squeezer/onnx/export.py
esceptico/squeezer
98bc4c7923c6aa3b12ac81444d79392826fc34c6
[ "MIT" ]
null
null
null
from logging import getLogger from typing import Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.onnx import export logger = getLogger(__name__) def export_to_onnx( model: nn.Module, dummy_input: [Union[Tuple], torch.Tensor], file, opset_version: int = 12, input_names: Optional[List[str]] = None, output_names: Optional[List[str]] = None, dynamic_axes: Dict[str, Dict[int, str]] = None ) -> None: """Exports PyTorch model to ONNX format. Args: model: PyTorch module. dummy_input: Dummy input. file: Path to save converted model or file-like object. opset_version: Version of ONNX operator set. Defaults to 12. input_names: Names of model inputs. Defaults to None. output_names: Names of model outputs. Defaults to None. dynamic_axes: Axes (input or/and outputs) with dynamic shapes. Defaults to None. Examples: >>> from transformers import AutoModel, AutoTokenizer >>> tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased') >>> model = AutoModel.from_pretrained('bert-base-uncased') >>> encoded = tokenizer('aboba', return_tensors='np') >>> >>> export_to_onnx( >>> model, >>> dummy_input=tuple(encoded.values()), >>> path_to_save='model.onnx', >>> input_names=list(encoded.keys()), >>> output_names=['last_hidden_state', 'pooler_output'], >>> dynamic_axes={ >>> 'input_ids' : {0 : 'batch_size', 1: 'seq'}, >>> 'token_type_ids' : {0 : 'batch_size', 1: 'seq'}, >>> 'attention_mask' : {0 : 'batch_size', 1: 'seq'}, >>> 'last_hidden_state' : {0 : 'batch_size', 1: 'seq'}, >>> 'pooler_output' : {0 : 'batch_size', 1: 'seq'} >>> } >>> ) """ model.eval() export( model, dummy_input, file, opset_version=opset_version, do_constant_folding=True, input_names=input_names, output_names=output_names, dynamic_axes=dynamic_axes ) logger.warning(f'Model was exported to ONNX.')
34.2
74
0.589744
from logging import getLogger from typing import Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.onnx import export logger = getLogger(__name__) def export_to_onnx( model: nn.Module, dummy_input: [Union[Tuple], torch.Tensor], file, opset_version: int = 12, input_names: Optional[List[str]] = None, output_names: Optional[List[str]] = None, dynamic_axes: Dict[str, Dict[int, str]] = None ) -> None: model.eval() export( model, dummy_input, file, opset_version=opset_version, do_constant_folding=True, input_names=input_names, output_names=output_names, dynamic_axes=dynamic_axes ) logger.warning(f'Model was exported to ONNX.')
true
true
f7fe8aea28a782debcb6c52ead11ec2710fb20c0
23,189
py
Python
nuitka/tools/specialize/__main__.py
lurid-bogey/Nuitka
7eca8d66874e08f6d8472ad4e63255a08ad0c3c5
[ "Apache-2.0" ]
null
null
null
nuitka/tools/specialize/__main__.py
lurid-bogey/Nuitka
7eca8d66874e08f6d8472ad4e63255a08ad0c3c5
[ "Apache-2.0" ]
null
null
null
nuitka/tools/specialize/__main__.py
lurid-bogey/Nuitka
7eca8d66874e08f6d8472ad4e63255a08ad0c3c5
[ "Apache-2.0" ]
null
null
null
# Copyright 2019, Kay Hayen, mailto:kay.hayen@gmail.com # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ This tool is generating code variants for helper codes from Jinja templates. """ from __future__ import print_function import os from abc import abstractmethod import jinja2 import nuitka.codegen.OperationCodes from nuitka.__past__ import getMetaClassBase from nuitka.tools.quality.autoformat.Autoformat import autoformat class TypeDescBase(getMetaClassBase("Type")): # To be overloaded type_name = None type_desc = None type_decl = None python_requirement = None def __init__(self): assert self.type_name assert self.type_desc assert self.type_decl def __repr__(self): return "<%s %s %s>" % (self.__class__.__name__, self.type_name, self.type_desc) @classmethod def getHelperCodeName(cls): return cls.type_name.upper() @classmethod def getTypeName2(cls): return cls.type_name @classmethod def getTypeName3(cls): return cls.type_name @classmethod def getVariableDecl(cls, variable_name): if cls.type_decl.endswith("*"): return cls.type_decl + variable_name else: return cls.type_decl + " " + variable_name @classmethod def getCheckValueCode(cls, operand): return "CHECK_OBJECT(%s);" % operand @classmethod def getTypeValueExpression(cls, operand): return "Py_TYPE(%s)" % operand @abstractmethod def getNewStyleNumberTypeCheckExpression(self, operand): pass @staticmethod def needsIndexConversion(): return True def canTypeCoerceObjects(self, left): if left is self and left is not object_desc: return "0" # TODO: Provide hook for float to say it can do int. return ( "1" if self.getSlotValueCheckExpression("type2", "nb_coerce") != "false" else "0" ) @classmethod def getIntCheckExpression(cls, operand): if cls.type_name == "int": return "1" elif cls.type_name == "object": return "PyInt_CheckExact(%s)" % operand else: return "0" def getIndexCheckExpression(self, operand): if self.hasSlot("nb_index"): return "1" elif self.type_name == "object": return "PyIndex_Check(%s)" % operand else: return "0" def getTypeIdenticalCheckExpression(self, other, operand1, operand2): if self is object_desc or other is object_desc: return "%s == %s" % (operand1, operand2) elif self is other: return "1" else: return "0" @staticmethod def getRealSubTypeCheckCode(right, operand2, operand1): if right is object_desc: return "PyType_IsSubtype(%s, %s)" % (operand2, operand1) else: return 0 def getSlotComparisonEqualExpression(self, right, operand1, operand2): if right is object_desc or self is object_desc: return "%s == %s" % (operand1, operand2) else: return "0" @abstractmethod def hasSlot(self, slot): pass def _getSlotValueExpression(self, operand, slot): if slot.startswith("nb_"): return "(%s) ? %s : NULL" % ( operand + "->tp_as_number != NULL && " + self.getNewStyleNumberTypeCheckExpression(operand), operand + "->tp_as_number->" + slot, ) elif slot.startswith("sq_"): return "%s ? %s : NULL" % ( operand + "->tp_as_sequence" + " != NULL", operand + "->tp_as_sequence->" + slot, ) else: assert False, slot def getSlotValueExpression(self, operand, slot): if not self.hasSlot(slot): return "NULL" return self._getSlotValueExpression(operand, slot) def getSlotValueCheckExpression(self, operand, slot): # Virtual method, pylint: disable=unused-argument return "true" if self.hasSlot(slot) else "false" def getRaiseUnsupportedTypeError(self, operation, other, operand1, operand2): args = [] if self is object_desc: args.append("%s->tp_name" % operand1) if other is object_desc: args.append("%s->tp_name" % operand2) if args: args = ", " + ", ".join(args) else: args = "" if ( self.getTypeName2() != self.getTypeName3() or other.getTypeName2() != other.getTypeName3() ): return """\ #if PYTHON_VERSION < 300 PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for %s: '%s' and '%s'"%s); #else PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for %s: '%s' and '%s'"%s); #endif return NULL;""" % ( operation, "%s" if self is object_desc else self.getTypeName2(), "%s" if other is object_desc else other.getTypeName2(), args, operation, "%s" if self is object_desc else self.getTypeName3(), "%s" if other is object_desc else other.getTypeName3(), args, ) else: return """\ PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for %s: '%s' and '%s'"%s); return NULL;""" % ( operation, "%s" if self is object_desc else self.getTypeName2(), "%s" if other is object_desc else other.getTypeName2(), args, ) def getSameTypeSpecializationCode( self, other, nb_slot, sq_slot, operand1, operand2 ): cand = self if self is not object_desc else other if cand is object_desc: return "" # Special case for sequence concats/repeats. if sq_slot is not None and not cand.hasSlot(nb_slot) and cand.hasSlot(sq_slot): slot = sq_slot else: slot = nb_slot if slot == "sq_repeat": if cand in (list_desc, tuple_desc, unicode_desc, str_desc, bytes_desc): return "" return "return SLOT_%s_%s_%s(%s, %s);" % ( slot, cand.getHelperCodeName(), cand.getHelperCodeName(), operand1, operand2, ) def getSimilarTypeSpecializationCode(self, other, nb_slot, operand1, operand2): return "return SLOT_%s_%s_%s(%s, %s);" % ( nb_slot, self.getHelperCodeName(), other.getHelperCodeName(), operand1, operand2, ) def getTypeSpecializationCode(self, other, nb_slot, sq_slot, operand1, operand2): if self is object_desc or other is object_desc: return "" if self is other: return self.getSameTypeSpecializationCode( other, nb_slot, sq_slot, operand1, operand2 ) if other in related_types.get(self, ()): return self.getSimilarTypeSpecializationCode( other, nb_slot, operand1, operand2 ) return "" @abstractmethod def getSqConcatSlotSpecializationCode(self, other, slot, operand1, operand2): pass class ConcreteTypeBase(TypeDescBase): type_decl = "PyObject *" def _getSlotValueExpression(self, operand, slot): if slot.startswith("nb_"): return self.getTypeValueExpression(operand)[1:] + ".tp_as_number->" + slot elif slot.startswith("sq_"): return self.getTypeValueExpression(operand)[1:] + ".tp_as_sequence->" + slot else: assert False, slot def getCheckValueCode(self, operand): return """\ CHECK_OBJECT(%(operand)s); assert(%(type_name)s_CheckExact(%(operand)s)); #if PYTHON_VERSION < 300 assert(%(is_newstyle)sNEW_STYLE_NUMBER(%(operand)s)); #endif""" % { "operand": operand, "type_name": self.getTypeValueExpression(operand)[1:].split("_")[0], "is_newstyle": "" if self.getNewStyleNumberTypeCheckExpression(operand) == "1" else "!", } @abstractmethod def getTypeValueExpression(self, operand): pass def getSqConcatSlotSpecializationCode(self, other, slot, operand1, operand2): if not self.hasSlot(slot): return "" # TODO: Use second type eventually when we specialize those too. return "return SLOT_%s_%s_%s(%s, %s);" % ( slot, self.getHelperCodeName(), other.getHelperCodeName(), operand1, operand2, ) class IntDesc(ConcreteTypeBase): type_name = "int" type_desc = "Python2 'int'" python_requirement = "PYTHON_VERSION < 300" @classmethod def getTypeValueExpression(cls, operand): return "&PyInt_Type" @classmethod def getNewStyleNumberTypeCheckExpression(cls, operand): return "1" def hasSlot(self, slot): if slot.startswith("nb_"): return True elif slot.startswith("sq_"): return False else: assert False @staticmethod def needsIndexConversion(): return False @staticmethod def getAsLongValueExpression(operand): return "PyInt_AS_LONG(%s)" % operand @staticmethod def getAsObjectValueExpression(operand): return operand @staticmethod def releaseAsObjectValueStatement(operand): # Virtual method, pylint: disable=unused-argument return "" int_desc = IntDesc() class StrDesc(ConcreteTypeBase): type_name = "str" type_desc = "Python2 'str'" python_requirement = "PYTHON_VERSION < 300" @classmethod def getTypeValueExpression(cls, operand): return "&PyString_Type" @classmethod def getNewStyleNumberTypeCheckExpression(cls, operand): return "1" def hasSlot(self, slot): if slot.startswith("nb_"): return "slot" == "nb_remainder" elif slot.startswith("sq_"): return "ass" not in slot else: assert False, slot str_desc = StrDesc() class UnicodeDesc(ConcreteTypeBase): type_name = "UNICODE" type_desc = "Python2 'unicode', Python3 'str'" @classmethod def getTypeValueExpression(cls, operand): return "&PyUnicode_Type" @classmethod def getCheckValueCode(cls, operand): return """\ CHECK_OBJECT(%(operand)s); assert(PyUnicode_CheckExact(%(operand)s)); assert(NEW_STYLE_NUMBER(%(operand)s));""" % { "operand": operand } @classmethod def getNewStyleNumberTypeCheckExpression(cls, operand): return "1" def hasSlot(self, slot): if slot.startswith("nb_"): return "slot" == "nb_remainder" elif slot.startswith("sq_"): return "ass" not in slot else: assert False, slot unicode_desc = UnicodeDesc() class FloatDesc(ConcreteTypeBase): type_name = "float" type_desc = "Python 'float'" @classmethod def getTypeValueExpression(cls, operand): return "&PyFloat_Type" def hasSlot(self, slot): if slot.startswith("nb_"): return True elif slot.startswith("sq_"): return False else: assert False, slot @classmethod def getNewStyleNumberTypeCheckExpression(cls, operand): return "1" float_desc = FloatDesc() class TupleDesc(ConcreteTypeBase): type_name = "tuple" type_desc = "Python 'tuple'" @classmethod def getTypeValueExpression(cls, operand): return "&PyTuple_Type" def hasSlot(self, slot): if slot.startswith("nb_"): return False elif slot.startswith("sq_"): return "ass" not in slot else: assert False, slot @classmethod def getNewStyleNumberTypeCheckExpression(cls, operand): return "0" tuple_desc = TupleDesc() class ListDesc(ConcreteTypeBase): type_name = "list" type_desc = "Python 'list'" @classmethod def getTypeValueExpression(cls, operand): return "&PyList_Type" def hasSlot(self, slot): if slot.startswith("nb_"): return False elif slot.startswith("sq_"): return True else: assert False, slot @classmethod def getNewStyleNumberTypeCheckExpression(cls, operand): return "0" list_desc = ListDesc() class BytesDesc(ConcreteTypeBase): type_name = "bytes" type_desc = "Python3 'bytes'" python_requirement = "PYTHON_VERSION >= 300" @classmethod def getTypeValueExpression(cls, operand): return "&PyBytes_Type" def hasSlot(self, slot): if slot.startswith("nb_"): return "slot" == "nb_remainder" elif slot.startswith("sq_"): return "ass" not in slot and slot != "sq_slice" else: assert False, slot @classmethod def getNewStyleNumberTypeCheckExpression(cls, operand): return "0" bytes_desc = BytesDesc() class LongDesc(ConcreteTypeBase): type_name = "long" type_desc = "Python2 'long', Python3 'int'" @classmethod def getTypeName3(cls): return "int" @classmethod def getTypeValueExpression(cls, operand): return "&PyLong_Type" def hasSlot(self, slot): if slot.startswith("nb_"): return True elif slot.startswith("sq_"): return False else: assert False @classmethod def getNewStyleNumberTypeCheckExpression(cls, operand): return "1" @staticmethod def needsIndexConversion(): return False long_desc = LongDesc() class ObjectDesc(TypeDescBase): type_name = "object" type_desc = "any Python object" type_decl = "PyObject *" def hasSlot(self, slot): # Don't want to get asked, we cannot know. assert False def getIndexCheckExpression(self, operand): return "PyIndex_Check(%s)" % operand def getNewStyleNumberTypeCheckExpression(self, operand): return "NEW_STYLE_NUMBER_TYPE(%s)" % operand def getSlotValueExpression(self, operand, slot): # Always check. return self._getSlotValueExpression(operand, slot) def getSlotValueCheckExpression(self, operand, slot): return "(%s) != NULL" % self._getSlotValueExpression(operand, slot) def getSqConcatSlotSpecializationCode(self, other, slot, operand1, operand2): return "" object_desc = ObjectDesc() class CLongDesc(TypeDescBase): type_name = "clong" type_desc = "C platform long value" type_decl = "long" @classmethod def getCheckValueCode(cls, operand): return "" @classmethod def getTypeValueExpression(cls, operand): return "NULL" @classmethod def getNewStyleNumberTypeCheckExpression(cls, operand): return "0" def hasSlot(self, slot): return False def getSqConcatSlotSpecializationCode(self, other, slot, operand1, operand2): return "" @staticmethod def getAsLongValueExpression(operand): return operand @staticmethod def getAsObjectValueExpression(operand): return "PyLong_FromLong(%s)" % operand @staticmethod def releaseAsObjectValueStatement(operand): return "Py_DECREF(%s);" % operand clong_desc = CLongDesc() related_types = {clong_desc: (int_desc,), int_desc: (clong_desc,)} class AlternativeTypeBase(object): # TODO: Base class for alternative types pass class AlternativeIntOrClong(AlternativeTypeBase): # TODO: Base class for alternative type int or clong. pass env = jinja2.Environment( loader=jinja2.PackageLoader("nuitka.tools.specialize", "templates"), trim_blocks=True, lstrip_blocks=True, ) env.undefined = jinja2.StrictUndefined types = ( int_desc, str_desc, unicode_desc, float_desc, tuple_desc, list_desc, bytes_desc, long_desc, clong_desc, object_desc, ) def findTypeFromCodeName(code_name): for candidate in types: if candidate.getHelperCodeName() == code_name: return candidate assert False, code_name add_codes = set() def makeNbSlotCode(operand, op_code, left, right, emit): key = operand, op_code, left, right if key in add_codes: return if left in (int_desc, clong_desc): template = env.get_template("HelperOperationBinaryInt.c.j2") elif left == long_desc: template = env.get_template("HelperOperationBinaryLong.c.j2") elif left == float_desc: template = env.get_template("HelperOperationBinaryFloat.c.j2") else: return code = template.render( operand=operand, left=left, right=right, nb_slot=_getNbSlotFromOperand(operand, op_code), ) emit(code) add_codes.add(key) mul_repeats = set() def makeMulRepeatCode(left, right, emit): key = right, left if key in mul_repeats: return template = env.get_template("HelperOperationMulRepeatSlot.c.j2") code = template.render(left=left, right=right) emit(code) mul_repeats.add(key) def _getNbSlotFromOperand(operand, op_code): if operand == "+": return "nb_add" elif operand == "*": return "nb_multiply" elif operand == "-": return "nb_subtract" elif operand == "//": return "nb_floor_divide" elif operand == "/": if op_code == "TRUEDIV": return "nb_true_divide" else: return "nb_divide" else: assert False, operand def makeHelperOperations(template, helpers_set, operand, op_code, emit_h, emit_c, emit): # Complexity comes natural, pylint: disable=too-many-branches emit( '/* C helpers for type specialized "%s" (%s) operations */' % (operand, op_code) ) emit() for helper_name in helpers_set: left = findTypeFromCodeName(helper_name.split("_")[3]) right = findTypeFromCodeName(helper_name.split("_")[4]) if left.python_requirement: emit("#if %s" % left.python_requirement) elif right.python_requirement: emit("#if %s" % right.python_requirement) nb_slot = _getNbSlotFromOperand(operand, op_code) code = left.getSameTypeSpecializationCode( right, nb_slot, None, "operand1", "operand2" ) if code: cand = left if left is not object_desc else right makeNbSlotCode(operand, op_code, cand, cand, emit_c) if left is not right and right in related_types.get(left, ()): code = left.getSimilarTypeSpecializationCode( right, nb_slot, "operand1", "operand2" ) if code: makeNbSlotCode(operand, op_code, left, right, emit_c) if operand == "*": repeat = left.getSqConcatSlotSpecializationCode( right, "sq_repeat", "operand2", "operand1" ) if repeat: makeMulRepeatCode(left, right, emit_c) repeat = right.getSqConcatSlotSpecializationCode( left, "sq_repeat", "operand2", "operand1" ) if repeat: makeMulRepeatCode(right, left, emit_c) emit( '/* Code referring to "%s" corresponds to %s and "%s" to %s. */' % ( left.getHelperCodeName(), left.type_desc, right.getHelperCodeName(), right.type_desc, ) ) if operand == "+": sq_slot = "sq_concat" elif operand == "*": sq_slot = "sq_repeat" else: sq_slot = None code = template.render( left=left, right=right, op_code=op_code, operand=operand, nb_slot=_getNbSlotFromOperand(operand, op_code), sq_slot1=sq_slot, ) emit_c(code) emit_h("extern " + code.splitlines()[0].replace(" {", ";")) if left.python_requirement or right.python_requirement: emit("#endif") emit() def makeHelpersBinaryOperation(operand, op_code): specialized_op_helpers_set = getattr( nuitka.codegen.OperationCodes, "specialized_%s_helpers_set" % op_code.lower() ) template = env.get_template("HelperOperationBinary.c.j2") filename_c = "nuitka/build/static_src/HelpersOperationBinary%s.c" % op_code.title() filename_h = ( "nuitka/build/include/nuitka/helper/operations_binary_%s.h" % op_code.lower() ) with open(filename_c, "w") as output_c: with open(filename_h, "w") as output_h: def emit_h(*args): writeline(output_h, *args) def emit_c(*args): writeline(output_c, *args) def emit(*args): emit_h(*args) emit_c(*args) def emitGenerationWarning(emit): emit( "/* WARNING, this code is GENERATED. Modify the template %s instead! */" % template.name ) emitGenerationWarning(emit_h) emitGenerationWarning(emit_c) filename_utils = filename_c[:-2] + "Utils.c" if os.path.exists(filename_utils): emit_c('#include "%s"' % os.path.basename(filename_utils)) makeHelperOperations( template, specialized_op_helpers_set, operand, op_code, emit_h, emit_c, emit, ) autoformat(filename_c, None, True) autoformat(filename_h, None, True) def writeline(output, *args): if not args: output.write("\n") elif len(args) == 1: output.write(args[0] + "\n") else: assert False, args def main(): makeHelpersBinaryOperation("+", "ADD") makeHelpersBinaryOperation("-", "SUB") makeHelpersBinaryOperation("*", "MUL") makeHelpersBinaryOperation("//", "FLOORDIV") makeHelpersBinaryOperation("/", "TRUEDIV") makeHelpersBinaryOperation("/", "OLDDIV") if __name__ == "__main__": main()
26.59289
92
0.60201
from __future__ import print_function import os from abc import abstractmethod import jinja2 import nuitka.codegen.OperationCodes from nuitka.__past__ import getMetaClassBase from nuitka.tools.quality.autoformat.Autoformat import autoformat class TypeDescBase(getMetaClassBase("Type")): type_name = None type_desc = None type_decl = None python_requirement = None def __init__(self): assert self.type_name assert self.type_desc assert self.type_decl def __repr__(self): return "<%s %s %s>" % (self.__class__.__name__, self.type_name, self.type_desc) @classmethod def getHelperCodeName(cls): return cls.type_name.upper() @classmethod def getTypeName2(cls): return cls.type_name @classmethod def getTypeName3(cls): return cls.type_name @classmethod def getVariableDecl(cls, variable_name): if cls.type_decl.endswith("*"): return cls.type_decl + variable_name else: return cls.type_decl + " " + variable_name @classmethod def getCheckValueCode(cls, operand): return "CHECK_OBJECT(%s);" % operand @classmethod def getTypeValueExpression(cls, operand): return "Py_TYPE(%s)" % operand @abstractmethod def getNewStyleNumberTypeCheckExpression(self, operand): pass @staticmethod def needsIndexConversion(): return True def canTypeCoerceObjects(self, left): if left is self and left is not object_desc: return "0" return ( "1" if self.getSlotValueCheckExpression("type2", "nb_coerce") != "false" else "0" ) @classmethod def getIntCheckExpression(cls, operand): if cls.type_name == "int": return "1" elif cls.type_name == "object": return "PyInt_CheckExact(%s)" % operand else: return "0" def getIndexCheckExpression(self, operand): if self.hasSlot("nb_index"): return "1" elif self.type_name == "object": return "PyIndex_Check(%s)" % operand else: return "0" def getTypeIdenticalCheckExpression(self, other, operand1, operand2): if self is object_desc or other is object_desc: return "%s == %s" % (operand1, operand2) elif self is other: return "1" else: return "0" @staticmethod def getRealSubTypeCheckCode(right, operand2, operand1): if right is object_desc: return "PyType_IsSubtype(%s, %s)" % (operand2, operand1) else: return 0 def getSlotComparisonEqualExpression(self, right, operand1, operand2): if right is object_desc or self is object_desc: return "%s == %s" % (operand1, operand2) else: return "0" @abstractmethod def hasSlot(self, slot): pass def _getSlotValueExpression(self, operand, slot): if slot.startswith("nb_"): return "(%s) ? %s : NULL" % ( operand + "->tp_as_number != NULL && " + self.getNewStyleNumberTypeCheckExpression(operand), operand + "->tp_as_number->" + slot, ) elif slot.startswith("sq_"): return "%s ? %s : NULL" % ( operand + "->tp_as_sequence" + " != NULL", operand + "->tp_as_sequence->" + slot, ) else: assert False, slot def getSlotValueExpression(self, operand, slot): if not self.hasSlot(slot): return "NULL" return self._getSlotValueExpression(operand, slot) def getSlotValueCheckExpression(self, operand, slot): return "true" if self.hasSlot(slot) else "false" def getRaiseUnsupportedTypeError(self, operation, other, operand1, operand2): args = [] if self is object_desc: args.append("%s->tp_name" % operand1) if other is object_desc: args.append("%s->tp_name" % operand2) if args: args = ", " + ", ".join(args) else: args = "" if ( self.getTypeName2() != self.getTypeName3() or other.getTypeName2() != other.getTypeName3() ): return """\ #if PYTHON_VERSION < 300 PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for %s: '%s' and '%s'"%s); #else PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for %s: '%s' and '%s'"%s); #endif return NULL;""" % ( operation, "%s" if self is object_desc else self.getTypeName2(), "%s" if other is object_desc else other.getTypeName2(), args, operation, "%s" if self is object_desc else self.getTypeName3(), "%s" if other is object_desc else other.getTypeName3(), args, ) else: return """\ PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for %s: '%s' and '%s'"%s); return NULL;""" % ( operation, "%s" if self is object_desc else self.getTypeName2(), "%s" if other is object_desc else other.getTypeName2(), args, ) def getSameTypeSpecializationCode( self, other, nb_slot, sq_slot, operand1, operand2 ): cand = self if self is not object_desc else other if cand is object_desc: return "" if sq_slot is not None and not cand.hasSlot(nb_slot) and cand.hasSlot(sq_slot): slot = sq_slot else: slot = nb_slot if slot == "sq_repeat": if cand in (list_desc, tuple_desc, unicode_desc, str_desc, bytes_desc): return "" return "return SLOT_%s_%s_%s(%s, %s);" % ( slot, cand.getHelperCodeName(), cand.getHelperCodeName(), operand1, operand2, ) def getSimilarTypeSpecializationCode(self, other, nb_slot, operand1, operand2): return "return SLOT_%s_%s_%s(%s, %s);" % ( nb_slot, self.getHelperCodeName(), other.getHelperCodeName(), operand1, operand2, ) def getTypeSpecializationCode(self, other, nb_slot, sq_slot, operand1, operand2): if self is object_desc or other is object_desc: return "" if self is other: return self.getSameTypeSpecializationCode( other, nb_slot, sq_slot, operand1, operand2 ) if other in related_types.get(self, ()): return self.getSimilarTypeSpecializationCode( other, nb_slot, operand1, operand2 ) return "" @abstractmethod def getSqConcatSlotSpecializationCode(self, other, slot, operand1, operand2): pass class ConcreteTypeBase(TypeDescBase): type_decl = "PyObject *" def _getSlotValueExpression(self, operand, slot): if slot.startswith("nb_"): return self.getTypeValueExpression(operand)[1:] + ".tp_as_number->" + slot elif slot.startswith("sq_"): return self.getTypeValueExpression(operand)[1:] + ".tp_as_sequence->" + slot else: assert False, slot def getCheckValueCode(self, operand): return """\ CHECK_OBJECT(%(operand)s); assert(%(type_name)s_CheckExact(%(operand)s)); #if PYTHON_VERSION < 300 assert(%(is_newstyle)sNEW_STYLE_NUMBER(%(operand)s)); #endif""" % { "operand": operand, "type_name": self.getTypeValueExpression(operand)[1:].split("_")[0], "is_newstyle": "" if self.getNewStyleNumberTypeCheckExpression(operand) == "1" else "!", } @abstractmethod def getTypeValueExpression(self, operand): pass def getSqConcatSlotSpecializationCode(self, other, slot, operand1, operand2): if not self.hasSlot(slot): return "" return "return SLOT_%s_%s_%s(%s, %s);" % ( slot, self.getHelperCodeName(), other.getHelperCodeName(), operand1, operand2, ) class IntDesc(ConcreteTypeBase): type_name = "int" type_desc = "Python2 'int'" python_requirement = "PYTHON_VERSION < 300" @classmethod def getTypeValueExpression(cls, operand): return "&PyInt_Type" @classmethod def getNewStyleNumberTypeCheckExpression(cls, operand): return "1" def hasSlot(self, slot): if slot.startswith("nb_"): return True elif slot.startswith("sq_"): return False else: assert False @staticmethod def needsIndexConversion(): return False @staticmethod def getAsLongValueExpression(operand): return "PyInt_AS_LONG(%s)" % operand @staticmethod def getAsObjectValueExpression(operand): return operand @staticmethod def releaseAsObjectValueStatement(operand): return "" int_desc = IntDesc() class StrDesc(ConcreteTypeBase): type_name = "str" type_desc = "Python2 'str'" python_requirement = "PYTHON_VERSION < 300" @classmethod def getTypeValueExpression(cls, operand): return "&PyString_Type" @classmethod def getNewStyleNumberTypeCheckExpression(cls, operand): return "1" def hasSlot(self, slot): if slot.startswith("nb_"): return "slot" == "nb_remainder" elif slot.startswith("sq_"): return "ass" not in slot else: assert False, slot str_desc = StrDesc() class UnicodeDesc(ConcreteTypeBase): type_name = "UNICODE" type_desc = "Python2 'unicode', Python3 'str'" @classmethod def getTypeValueExpression(cls, operand): return "&PyUnicode_Type" @classmethod def getCheckValueCode(cls, operand): return """\ CHECK_OBJECT(%(operand)s); assert(PyUnicode_CheckExact(%(operand)s)); assert(NEW_STYLE_NUMBER(%(operand)s));""" % { "operand": operand } @classmethod def getNewStyleNumberTypeCheckExpression(cls, operand): return "1" def hasSlot(self, slot): if slot.startswith("nb_"): return "slot" == "nb_remainder" elif slot.startswith("sq_"): return "ass" not in slot else: assert False, slot unicode_desc = UnicodeDesc() class FloatDesc(ConcreteTypeBase): type_name = "float" type_desc = "Python 'float'" @classmethod def getTypeValueExpression(cls, operand): return "&PyFloat_Type" def hasSlot(self, slot): if slot.startswith("nb_"): return True elif slot.startswith("sq_"): return False else: assert False, slot @classmethod def getNewStyleNumberTypeCheckExpression(cls, operand): return "1" float_desc = FloatDesc() class TupleDesc(ConcreteTypeBase): type_name = "tuple" type_desc = "Python 'tuple'" @classmethod def getTypeValueExpression(cls, operand): return "&PyTuple_Type" def hasSlot(self, slot): if slot.startswith("nb_"): return False elif slot.startswith("sq_"): return "ass" not in slot else: assert False, slot @classmethod def getNewStyleNumberTypeCheckExpression(cls, operand): return "0" tuple_desc = TupleDesc() class ListDesc(ConcreteTypeBase): type_name = "list" type_desc = "Python 'list'" @classmethod def getTypeValueExpression(cls, operand): return "&PyList_Type" def hasSlot(self, slot): if slot.startswith("nb_"): return False elif slot.startswith("sq_"): return True else: assert False, slot @classmethod def getNewStyleNumberTypeCheckExpression(cls, operand): return "0" list_desc = ListDesc() class BytesDesc(ConcreteTypeBase): type_name = "bytes" type_desc = "Python3 'bytes'" python_requirement = "PYTHON_VERSION >= 300" @classmethod def getTypeValueExpression(cls, operand): return "&PyBytes_Type" def hasSlot(self, slot): if slot.startswith("nb_"): return "slot" == "nb_remainder" elif slot.startswith("sq_"): return "ass" not in slot and slot != "sq_slice" else: assert False, slot @classmethod def getNewStyleNumberTypeCheckExpression(cls, operand): return "0" bytes_desc = BytesDesc() class LongDesc(ConcreteTypeBase): type_name = "long" type_desc = "Python2 'long', Python3 'int'" @classmethod def getTypeName3(cls): return "int" @classmethod def getTypeValueExpression(cls, operand): return "&PyLong_Type" def hasSlot(self, slot): if slot.startswith("nb_"): return True elif slot.startswith("sq_"): return False else: assert False @classmethod def getNewStyleNumberTypeCheckExpression(cls, operand): return "1" @staticmethod def needsIndexConversion(): return False long_desc = LongDesc() class ObjectDesc(TypeDescBase): type_name = "object" type_desc = "any Python object" type_decl = "PyObject *" def hasSlot(self, slot): assert False def getIndexCheckExpression(self, operand): return "PyIndex_Check(%s)" % operand def getNewStyleNumberTypeCheckExpression(self, operand): return "NEW_STYLE_NUMBER_TYPE(%s)" % operand def getSlotValueExpression(self, operand, slot): # Always check. return self._getSlotValueExpression(operand, slot) def getSlotValueCheckExpression(self, operand, slot): return "(%s) != NULL" % self._getSlotValueExpression(operand, slot) def getSqConcatSlotSpecializationCode(self, other, slot, operand1, operand2): return "" object_desc = ObjectDesc() class CLongDesc(TypeDescBase): type_name = "clong" type_desc = "C platform long value" type_decl = "long" @classmethod def getCheckValueCode(cls, operand): return "" @classmethod def getTypeValueExpression(cls, operand): return "NULL" @classmethod def getNewStyleNumberTypeCheckExpression(cls, operand): return "0" def hasSlot(self, slot): return False def getSqConcatSlotSpecializationCode(self, other, slot, operand1, operand2): return "" @staticmethod def getAsLongValueExpression(operand): return operand @staticmethod def getAsObjectValueExpression(operand): return "PyLong_FromLong(%s)" % operand @staticmethod def releaseAsObjectValueStatement(operand): return "Py_DECREF(%s);" % operand clong_desc = CLongDesc() related_types = {clong_desc: (int_desc,), int_desc: (clong_desc,)} class AlternativeTypeBase(object): # TODO: Base class for alternative types pass class AlternativeIntOrClong(AlternativeTypeBase): # TODO: Base class for alternative type int or clong. pass env = jinja2.Environment( loader=jinja2.PackageLoader("nuitka.tools.specialize", "templates"), trim_blocks=True, lstrip_blocks=True, ) env.undefined = jinja2.StrictUndefined types = ( int_desc, str_desc, unicode_desc, float_desc, tuple_desc, list_desc, bytes_desc, long_desc, clong_desc, object_desc, ) def findTypeFromCodeName(code_name): for candidate in types: if candidate.getHelperCodeName() == code_name: return candidate assert False, code_name add_codes = set() def makeNbSlotCode(operand, op_code, left, right, emit): key = operand, op_code, left, right if key in add_codes: return if left in (int_desc, clong_desc): template = env.get_template("HelperOperationBinaryInt.c.j2") elif left == long_desc: template = env.get_template("HelperOperationBinaryLong.c.j2") elif left == float_desc: template = env.get_template("HelperOperationBinaryFloat.c.j2") else: return code = template.render( operand=operand, left=left, right=right, nb_slot=_getNbSlotFromOperand(operand, op_code), ) emit(code) add_codes.add(key) mul_repeats = set() def makeMulRepeatCode(left, right, emit): key = right, left if key in mul_repeats: return template = env.get_template("HelperOperationMulRepeatSlot.c.j2") code = template.render(left=left, right=right) emit(code) mul_repeats.add(key) def _getNbSlotFromOperand(operand, op_code): if operand == "+": return "nb_add" elif operand == "*": return "nb_multiply" elif operand == "-": return "nb_subtract" elif operand == "//": return "nb_floor_divide" elif operand == "/": if op_code == "TRUEDIV": return "nb_true_divide" else: return "nb_divide" else: assert False, operand def makeHelperOperations(template, helpers_set, operand, op_code, emit_h, emit_c, emit): # Complexity comes natural, pylint: disable=too-many-branches emit( '/* C helpers for type specialized "%s" (%s) operations */' % (operand, op_code) ) emit() for helper_name in helpers_set: left = findTypeFromCodeName(helper_name.split("_")[3]) right = findTypeFromCodeName(helper_name.split("_")[4]) if left.python_requirement: emit("#if %s" % left.python_requirement) elif right.python_requirement: emit("#if %s" % right.python_requirement) nb_slot = _getNbSlotFromOperand(operand, op_code) code = left.getSameTypeSpecializationCode( right, nb_slot, None, "operand1", "operand2" ) if code: cand = left if left is not object_desc else right makeNbSlotCode(operand, op_code, cand, cand, emit_c) if left is not right and right in related_types.get(left, ()): code = left.getSimilarTypeSpecializationCode( right, nb_slot, "operand1", "operand2" ) if code: makeNbSlotCode(operand, op_code, left, right, emit_c) if operand == "*": repeat = left.getSqConcatSlotSpecializationCode( right, "sq_repeat", "operand2", "operand1" ) if repeat: makeMulRepeatCode(left, right, emit_c) repeat = right.getSqConcatSlotSpecializationCode( left, "sq_repeat", "operand2", "operand1" ) if repeat: makeMulRepeatCode(right, left, emit_c) emit( '/* Code referring to "%s" corresponds to %s and "%s" to %s. */' % ( left.getHelperCodeName(), left.type_desc, right.getHelperCodeName(), right.type_desc, ) ) if operand == "+": sq_slot = "sq_concat" elif operand == "*": sq_slot = "sq_repeat" else: sq_slot = None code = template.render( left=left, right=right, op_code=op_code, operand=operand, nb_slot=_getNbSlotFromOperand(operand, op_code), sq_slot1=sq_slot, ) emit_c(code) emit_h("extern " + code.splitlines()[0].replace(" {", ";")) if left.python_requirement or right.python_requirement: emit("#endif") emit() def makeHelpersBinaryOperation(operand, op_code): specialized_op_helpers_set = getattr( nuitka.codegen.OperationCodes, "specialized_%s_helpers_set" % op_code.lower() ) template = env.get_template("HelperOperationBinary.c.j2") filename_c = "nuitka/build/static_src/HelpersOperationBinary%s.c" % op_code.title() filename_h = ( "nuitka/build/include/nuitka/helper/operations_binary_%s.h" % op_code.lower() ) with open(filename_c, "w") as output_c: with open(filename_h, "w") as output_h: def emit_h(*args): writeline(output_h, *args) def emit_c(*args): writeline(output_c, *args) def emit(*args): emit_h(*args) emit_c(*args) def emitGenerationWarning(emit): emit( "/* WARNING, this code is GENERATED. Modify the template %s instead! */" % template.name ) emitGenerationWarning(emit_h) emitGenerationWarning(emit_c) filename_utils = filename_c[:-2] + "Utils.c" if os.path.exists(filename_utils): emit_c(' makeHelperOperations( template, specialized_op_helpers_set, operand, op_code, emit_h, emit_c, emit, ) autoformat(filename_c, None, True) autoformat(filename_h, None, True) def writeline(output, *args): if not args: output.write("\n") elif len(args) == 1: output.write(args[0] + "\n") else: assert False, args def main(): makeHelpersBinaryOperation("+", "ADD") makeHelpersBinaryOperation("-", "SUB") makeHelpersBinaryOperation("*", "MUL") makeHelpersBinaryOperation("//", "FLOORDIV") makeHelpersBinaryOperation("/", "TRUEDIV") makeHelpersBinaryOperation("/", "OLDDIV") if __name__ == "__main__": main()
true
true
f7fe8b1e75fed505e11af640bc149b84a1c652b2
47,069
py
Python
mytardis_ngs_ingestor/illumina/models.py
mytardis/mytardis_ngs_ingestor
5232c688574c8e6cd9a50951c37cd878a09feba3
[ "BSD-3-Clause" ]
1
2020-11-19T19:10:20.000Z
2020-11-19T19:10:20.000Z
mytardis_ngs_ingestor/illumina/models.py
mytardis/mytardis_ngs_ingestor
5232c688574c8e6cd9a50951c37cd878a09feba3
[ "BSD-3-Clause" ]
3
2017-10-02T03:48:03.000Z
2020-03-12T23:52:47.000Z
mytardis_ngs_ingestor/illumina/models.py
mytardis/mytardis_ngs_ingestor
5232c688574c8e6cd9a50951c37cd878a09feba3
[ "BSD-3-Clause" ]
null
null
null
# Data model generated from ../fixtures/sequencing_facility_schema.json from mytardis_ngs_ingestor.mytardis_models import MyTardisParameterSet class IlluminaSequencingRunBase(MyTardisParameterSet): """ :type run_id: unicode :type run_number: float :type flowcell_id: unicode :type instrument_id: unicode :type instrument_model: unicode :type read_cycles: unicode :type chemistry: unicode :type operator_name: unicode :type rta_version: unicode :type ingestor_useragent: unicode :type demultiplexing_program: unicode :type demultiplexing_commandline_options: unicode """ def __init__(self): super(IlluminaSequencingRunBase, self).__init__() # Run Unique ID self.run_id = None # type: unicode # Run number self.run_number = None # type: float # Flowcell ID self.flowcell_id = None # type: unicode # Instrument ID self.instrument_id = None # type: unicode # Instrument model self.instrument_model = None # type: unicode # Number of cycles in each read [index reads in (brackets)] self.read_cycles = None # type: unicode # Terminator chemistry self.chemistry = None # type: unicode # Instrument operator self.operator_name = None # type: unicode # Illumina RTA version self.rta_version = None # type: unicode # Ingestor User Agent self.ingestor_useragent = None # type: unicode # Demultiplexing program version self.demultiplexing_program = None # type: unicode # Demultiplexing program commandline options self.demultiplexing_commandline_options = None # type: unicode # Dictionaries to allow reconstitution of the schema for each parameter # run_id fixture self._run_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run Unique ' u'ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']}} # type: dict # run_number fixture self._run_number__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_number', u'data_type': 1, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run number', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']}} # type: dict # flowcell_id fixture self._flowcell_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'flowcell_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Flowcell ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']}} # type: dict # instrument_id fixture self._instrument_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'instrument_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Instrument ' u'ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']}} # type: dict # instrument_model fixture self._instrument_model__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'instrument_model', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Instrument model', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']}} # type: dict # read_cycles fixture self._read_cycles__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'read_cycles', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Number of' u'cycles in each read [index reads in (brackets)]', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']}} # type: dict # chemistry fixture self._chemistry__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'chemistry', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Terminator ' u'chemistry', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']}} # type: dict # operator_name fixture self._operator_name__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'operator_name', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Instrument ' u'operator', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']}} # type: dict # rta_version fixture self._rta_version__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'rta_version', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Illumina RTA ' u'version', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']}} # type: dict # ingestor_useragent fixture self._ingestor_useragent__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'ingestor_useragent', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Ingestor User Agent', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']}} # type: dict self._demultiplexing_program__attr_schema = { u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'demultiplexing_program', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Demultiplexing program version', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']} } # type: dict self._demultiplexing_commandline_options__attr_schema = { u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'demultiplexing_commandline_options', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Demultiplexing commandline options', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']} } # type: dict self._subtype__schema = "illumina-sequencing-run" # type: unicode self._model__schema = "tardis_portal.schema" # type: unicode self._name__schema = "Illumina Sequencing Run" # type: unicode self._pk__schema = None # type: NoneType self._type__schema = 1 # type: int self._hidden__schema = False # type: bool self._namespace__schema = "http://www.tardis.edu.au/schemas/ngs/run/illumina" # type: unicode self._immutable__schema = True # type: bool class DemultiplexedSamplesBase(MyTardisParameterSet): """ :type run_id: unicode :type project_id: unicode :type run_experiment: unicode :type run_number: float :type flowcell_id: unicode :type instrument_id: unicode :type instrument_model: unicode :type read_cycles: unicode :type chemistry: unicode :type operator_name: unicode :type rta_version: unicode :type ingestor_useragent: unicode :type demultiplexing_program: unicode :type demultiplexing_commandline_options: unicode """ def __init__(self): super(DemultiplexedSamplesBase, self).__init__() # Run Unique ID self.run_id = None # type: unicode # Project ID self.project_id = None # type: unicode # Run Experiment link self.run_experiment = None # type: unicode # Run number self.run_number = None # type: float # Flowcell ID self.flowcell_id = None # type: unicode # Instrument ID self.instrument_id = None # type: unicode # Instrument model self.instrument_model = None # type: unicode # Number of cycles in each read [index reads in (brackets)] self.read_cycles = None # type: unicode # Terminator chemistry self.chemistry = None # type: unicode # Instrument operator self.operator_name = None # type: unicode # Illumina RTA version self.rta_version = None # type: unicode # Ingestor User Agent self.ingestor_useragent = None # type: unicode # Demultiplexing program version self.demultiplexing_program = None # type: unicode # Demultiplexing program commandline options self.demultiplexing_commandline_options = None # type: unicode # Dictionaries to allow reconstitution of the schema for each parameter # run_id fixture self._run_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run Unique ' u'ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} # type: dict # project_id fixture self._project_id__attr_schema = { u'pk': None, u'model': u'tardis_portal.parametername', u'fields': { u'name': u'project_id', u'data_type': 2, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Project ID', u'units': u'', u'order': 9999, u'immutable': True, u'schema': [ u'http://www.tardis.edu.au/schemas/ngs/project' ] } } # type: dict # run_experiment fixture self._run_experiment__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_experiment', u'data_type': 4, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run Experiment link', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} # type: dict # run_number fixture self._run_number__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_number', u'data_type': 1, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run number', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} # type: dict # flowcell_id fixture self._flowcell_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'flowcell_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Flowcell ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} # type: dict # instrument_id fixture self._instrument_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'instrument_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Instrument ' u'ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} # type: dict # instrument_model fixture self._instrument_model__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'instrument_model', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Instrument model', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} # type: dict # read_cycles fixture self._read_cycles__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'read_cycles', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Number of ' u'cycles in each read [index reads in (brackets)]', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} # type: dict # chemistry fixture self._chemistry__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'chemistry', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Terminator' u'chemistry', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} # type: dict # operator_name fixture self._operator_name__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'operator_name', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Instrument ' u'operator', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} # type: dict # rta_version fixture self._rta_version__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'rta_version', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Illumina RTA ' u'version', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} # type: dict # ingestor_useragent fixture self._ingestor_useragent__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'ingestor_useragent', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Ingestor User Agent', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} # type: dict self._demultiplexing_program__attr_schema = { u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'demultiplexing_program', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Demultiplexing program version', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']} } # type: dict self._demultiplexing_commandline_options__attr_schema = { u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'demultiplexing_commandline_options', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Demultiplexing commandline options', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']} } # type: dict self._subtype__schema = "demultiplexed-samples" # type: unicode self._model__schema = "tardis_portal.schema" # type: unicode self._name__schema = "Sequencing Project (Demultiplexed Sample Set)" # type: unicode self._pk__schema = None # type: NoneType self._type__schema = 1 # type: int self._hidden__schema = False # type: bool self._namespace__schema = "http://www.tardis.edu.au/schemas/ngs/project" # type: unicode self._immutable__schema = True # type: bool class NucleotideRawReadsDatasetBase(MyTardisParameterSet): """ :type run_id: unicode :type project_experiment: unicode :type run_experiment: unicode :type fastqc_dataset: unicode :type run_number: float :type flowcell_id: unicode :type instrument_id: unicode :type instrument_model: unicode :type read_cycles: unicode :type chemistry: unicode :type operator_name: unicode :type rta_version: unicode """ def __init__(self): super(NucleotideRawReadsDatasetBase, self).__init__() # Run Unique ID self.run_id = None # type: unicode # Project Experiment link self.project_experiment = None # type: unicode # Run Experiment link self.run_experiment = None # type: unicode # Associated FastQC reports self.fastqc_dataset = None # type: unicode # Run number self.run_number = None # type: float # Flowcell ID self.flowcell_id = None # type: unicode # Instrument ID self.instrument_id = None # type: unicode # Instrument model self.instrument_model = None # type: unicode # Number of cycles in each read [index reads in (brackets)] self.read_cycles = None # type: unicode # Terminator chemistry self.chemistry = None # type: unicode # Instrument operator self.operator_name = None # type: unicode # Illumina RTA version self.rta_version = None # type: unicode # Dictionaries to allow reconstitution of the schema for each parameter # run_id fixture self._run_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run Unique ' u'ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} # type: dict # project_experiment fixture self._project_experiment__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'project_experiment', u'data_type': 4, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Project Experiment link', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} # type: dict # run_experiment fixture self._run_experiment__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_experiment', u'data_type': 4, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run Experiment link', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} # type: dict # fastqc_dataset fixture self._fastqc_dataset__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'fastqc_dataset', u'data_type': 4, u'immutable': False, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Associated FastQC reports', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} # type: dict # run_number fixture self._run_number__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_number', u'data_type': 1, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run number', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} # type: dict # flowcell_id fixture self._flowcell_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'flowcell_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Flowcell ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} # type: dict # instrument_id fixture self._instrument_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'instrument_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Instrument ' u'ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} # type: dict # instrument_model fixture self._instrument_model__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'instrument_model', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Instrument model', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} # type: dict # read_cycles fixture self._read_cycles__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'read_cycles', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Number of' u'cycles in each read [index reads in (brackets)]', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} # type: dict # chemistry fixture self._chemistry__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'chemistry', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Terminator' u'chemistry', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} # type: dict # operator_name fixture self._operator_name__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'operator_name', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Instrument ' u'operator', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} # type: dict # rta_version fixture self._rta_version__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'rta_version', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Illumina RTA ' u'version', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} # type: dict self._subtype__schema = "nucleotide-raw-reads-dataset" # type: unicode self._model__schema = "tardis_portal.schema" # type: unicode self._name__schema = "Nucleotide Sequencing Project Raw Reads" # type: unicode self._pk__schema = None # type: NoneType self._type__schema = 2 # type: int self._hidden__schema = False # type: bool self._namespace__schema = "http://www.tardis.edu.au/schemas/ngs/project/raw_reads" # type: unicode self._immutable__schema = True # type: bool class FastqcReportsBase(MyTardisParameterSet): """ :type run_id: unicode :type project: unicode :type raw_reads_dataset: unicode :type fastqc_version: unicode """ def __init__(self): super(FastqcReportsBase, self).__init__() # Run Unique ID self.run_id = None # type: unicode # Project name self.project = None # type: unicode # Raw reads project link self.raw_reads_dataset = None # type: unicode # FastQC software version self.fastqc_version = None # type: unicode # Dictionaries to allow reconstitution of the schema for each parameter # run_id fixture self._run_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run Unique ' u'ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/fastqc']}} # type: dict # project fixture self._project__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'project', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Project name', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/fastqc']}} # type: dict # raw_reads_dataset fixture self._raw_reads_dataset__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'raw_reads_dataset', u'data_type': 4, u'immutable': False, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Raw reads project link', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/fastqc']}} # type: dict # fastqc_version fixture self._fastqc_version__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'fastqc_version', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'FastQC software version', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/fastqc']}} # type: dict self._subtype__schema = "fastqc-reports" # type: unicode self._model__schema = "tardis_portal.schema" # type: unicode self._name__schema = "FastQC Reports" # type: unicode self._pk__schema = None # type: NoneType self._type__schema = 2 # type: int self._hidden__schema = False # type: bool self._namespace__schema = "http://www.tardis.edu.au/schemas/ngs/project/fastqc" # type: unicode self._immutable__schema = True # type: bool class HiddenFastqcProjectSummaryBase(MyTardisParameterSet): """ :type hidden_fastqc_summary_json: dict :type fastqc_version: unicode """ def __init__(self): super(HiddenFastqcProjectSummaryBase, self).__init__() # (Hidden) FastQC summary for all samples (JSON) self.hidden_fastqc_summary_json = None # type: dict # FastQC software version self.fastqc_version = None # type: unicode # Dictionaries to allow reconstitution of the schema for each parameter # hidden_fastqc_summary_json fixture self._hidden_fastqc_summary_json__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'hidden_fastqc_summary_json', u'data_type': 8, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'(Hidden) FastQC summary for all samples (JSON)', u'units': u'fastqc-summary-table', u'order': 9999, u'schema': [u'http:' u'//www.tardis.edu.au/schemas/ngs/project/hidden_fastqc_summary']}} # type: dict # fastqc_version fixture self._fastqc_version__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'fastqc_version', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'FastQC software version', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/__hid' u'den__fastqc_summary']}} # type: dict self._subtype__schema = "hidden-fastqc-project-summary" # type: unicode self._model__schema = "tardis_portal.schema" # type: unicode self._name__schema = "FastQC Project Summary" # type: unicode self._pk__schema = None # type: NoneType self._type__schema = 2 # type: int self._hidden__schema = True # type: bool self._namespace__schema = "http://www.tardis.edu.au/schemas/ngs/project/hidden_fastqc_summary" # type: unicode self._immutable__schema = True # type: bool class FastqRawReadsBase(MyTardisParameterSet): """ :type run_id: unicode :type sample_id: unicode :type reference_genome: unicode :type index_sequence: unicode :type is_control: unicode :type recipe: unicode :type operator_name: unicode :type description: unicode :type project: unicode :type number_of_reads: float :type number_of_poor_quality_reads: float :type read_length: float """ def __init__(self): super(FastqRawReadsBase, self).__init__() # Run Unique ID self.run_id = None # type: unicode # Sample ID self.sample_id = None # type: unicode # Sample name self.sample_name = None # type: unicode # Lane self.lane = None # type: int # Read number self.read = None # type: int # Reference genome self.reference_genome = None # type: unicode # Index sequence (barcode) for this sample self.index_sequence = None # type: unicode # Is control ? self.is_control = None # type: unicode # Recipe self.recipe = None # type: unicode # Instrument Operator self.operator_name = None # type: unicode # Description self.description = None # type: unicode # Project name self.project = None # type: unicode # Number of reads self.number_of_reads = None # type: float # Number of reads flagged as poor quality (FastQC) self.number_of_poor_quality_reads = None # type: float # Read length self.read_length = None # type: float # Dictionaries to allow reconstitution of the schema for each parameter # run_id fixture self._run_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run Unique ' u'ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} # type: dict # sample_id fixture self._sample_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'sample_id', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Sample ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} # type: dict # sample_name fixture self._sample_name__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'sample_name', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Sample name', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} # type: dict # lane fixture self._lane__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'lane', u'data_type': 1, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Lane', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} # read fixture self._read__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'read', u'data_type': 1, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Read number', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} # reference_genome fixture self._reference_genome__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'reference_genome', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Reference genome', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} # type: dict # index_sequence fixture self._index_sequence__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'index_sequence', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Index sequence (barcode) for this sample', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} # type: dict # is_control fixture self._is_control__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'is_control', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Is control ?', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} # type: dict # recipe fixture self._recipe__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'recipe', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Recipe', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} # type: dict # operator_name fixture self._operator_name__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'operator_name', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Instrument ' u'Operator', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} # type: dict # description fixture self._description__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'description', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Description', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} # type: dict # project fixture self._project__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'project', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Project name', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} # type: dict # number_of_reads fixture self._number_of_reads__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'number_of_reads', u'data_type': 1, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Number of reads', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} # type: dict # number_of_poor_quality_reads fixture self._number_of_poor_quality_reads__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'number_of_poor_quality_reads', u'data_type': 1, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Number of reads flagged as poor quality (FastQC)', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} # type: dict # read_length fixture self._read_length__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'read_length', u'data_type': 1, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Read length', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} # type: dict self._subtype__schema = "fastq-raw-reads" # type: unicode self._model__schema = "tardis_portal.schema" # type: unicode self._name__schema = "Nucleotide Sequence Raw Reads (FASTQ)" # type: unicode self._pk__schema = None # type: NoneType self._type__schema = 3 # type: int self._hidden__schema = False # type: bool self._namespace__schema = "http://www.tardis.edu.au/schemas/ngs/file/fastq" # type: unicode self._immutable__schema = True # type: bool class FastqcOutputBase(MyTardisParameterSet): """ :type run_id: unicode :type sample_id: unicode :type project: unicode :type fastqc_version: unicode """ def __init__(self): super(FastqcOutputBase, self).__init__() # Run Unique ID self.run_id = None # type: unicode # Sample ID self.sample_id = None # type: unicode # Project name self.project = None # type: unicode # FastQC software version self.fastqc_version = None # type: unicode # Dictionaries to allow reconstitution of the schema for each parameter # run_id fixture self._run_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run Unique ' u'ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastqc']}} # type: dict # sample_id fixture self._sample_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'sample_id', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Sample ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastqc']}} # type: dict # project fixture self._project__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'project', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Project name', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastqc']}} # type: dict # fastqc_version fixture self._fastqc_version__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'fastqc_version', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'FastQC software version', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastqc']}} # type: dict self._subtype__schema = "fastqc-output" # type: unicode self._model__schema = "tardis_portal.schema" # type: unicode self._name__schema = "FastQC report" # type: unicode self._pk__schema = None # type: NoneType self._type__schema = 3 # type: int self._hidden__schema = False # type: bool self._namespace__schema = "http://www.tardis.edu.au/schemas/ngs/file/fastqc" # type: unicode self._immutable__schema = True # type: bool class IlluminaRunConfigBase(MyTardisParameterSet): """ :type run_id: unicode """ def __init__(self): super(IlluminaRunConfigBase, self).__init__() # the run ID self.run_id = None # type: unicode # Dictionaries to allow reconstitution of the schema for each parameter # fastqc_version fixture self._run_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina/config']}} # type: dict self._subtype__schema = "illumina-run-config" # type: unicode self._model__schema = "tardis_portal.schema" # type: unicode self._name__schema = "Illumia run config and log files" # type: unicode self._pk__schema = None # type: NoneType self._type__schema = 2 # type: int self._hidden__schema = False # type: bool self._namespace__schema = "http://www.tardis.edu.au/schemas/ngs/run/illumina/config" # type: unicode self._immutable__schema = True # type: bool class IlluminaRunInstrumentFilesBase(MyTardisParameterSet): """ :type run_id: unicode """ def __init__(self): super(IlluminaRunInstrumentFilesBase, self).__init__() # the run ID self.run_id = None # type: unicode # Dictionaries to allow reconstitution of the schema for each parameter # fastqc_version fixture self._run_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina/files']}} # type: dict self._subtype__schema = "illumina-run-instrument-files" # type: unicode self._model__schema = "tardis_portal.schema" # type: unicode self._name__schema = "Illumia run instrument files" # type: unicode self._pk__schema = None # type: NoneType self._type__schema = 2 # type: int self._hidden__schema = False # type: bool self._namespace__schema = "http://www.tardis.edu.au/schemas/ngs/run/illumina/files" # type: unicode self._immutable__schema = True # type: bool class IlluminaRunInstrumentFileBase(MyTardisParameterSet): """ :type run_id: unicode """ def __init__(self): super(IlluminaRunInstrumentFileBase, self).__init__() # the run ID self.run_id = None # type: unicode # Dictionaries to allow reconstitution of the schema for each parameter # fastqc_version fixture self._run_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina/files']}} # type: dict self._subtype__schema = "illumina-run-instrument-file" # type: unicode self._model__schema = "tardis_portal.schema" # type: unicode self._name__schema = "Illumina instrument run file" # type: unicode self._pk__schema = None # type: NoneType self._type__schema = 3 # type: int self._hidden__schema = False # type: bool self._namespace__schema = "http://www.tardis.edu.au/schemas/ngs/run/file" # type: unicode self._immutable__schema = True # type: bool
44.615166
119
0.608362
from mytardis_ngs_ingestor.mytardis_models import MyTardisParameterSet class IlluminaSequencingRunBase(MyTardisParameterSet): def __init__(self): super(IlluminaSequencingRunBase, self).__init__() self.run_id = None self.run_number = None self.flowcell_id = None self.instrument_id = None self.instrument_model = None self.read_cycles = None self.chemistry = None self.operator_name = None self.rta_version = None self.ingestor_useragent = None self.demultiplexing_program = None self.demultiplexing_commandline_options = None self._run_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run Unique ' u'ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']}} self._run_number__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_number', u'data_type': 1, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run number', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']}} self._flowcell_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'flowcell_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Flowcell ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']}} self._instrument_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'instrument_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Instrument ' u'ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']}} self._instrument_model__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'instrument_model', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Instrument model', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']}} self._read_cycles__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'read_cycles', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Number of' u'cycles in each read [index reads in (brackets)]', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']}} self._chemistry__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'chemistry', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Terminator ' u'chemistry', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']}} self._operator_name__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'operator_name', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Instrument ' u'operator', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']}} self._rta_version__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'rta_version', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Illumina RTA ' u'version', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']}} self._ingestor_useragent__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'ingestor_useragent', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Ingestor User Agent', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']}} self._demultiplexing_program__attr_schema = { u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'demultiplexing_program', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Demultiplexing program version', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']} } self._demultiplexing_commandline_options__attr_schema = { u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'demultiplexing_commandline_options', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Demultiplexing commandline options', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina']} } self._subtype__schema = "illumina-sequencing-run" self._model__schema = "tardis_portal.schema" self._name__schema = "Illumina Sequencing Run" self._pk__schema = None self._type__schema = 1 self._hidden__schema = False self._namespace__schema = "http://www.tardis.edu.au/schemas/ngs/run/illumina" self._immutable__schema = True class DemultiplexedSamplesBase(MyTardisParameterSet): def __init__(self): super(DemultiplexedSamplesBase, self).__init__() self.run_id = None self.project_id = None self.run_experiment = None self.run_number = None self.flowcell_id = None self.instrument_id = None self.instrument_model = None self.read_cycles = None self.chemistry = None self.operator_name = None self.rta_version = None self.ingestor_useragent = None self.demultiplexing_program = None self.demultiplexing_commandline_options = None self._run_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run Unique ' u'ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} self._project_id__attr_schema = { u'pk': None, u'model': u'tardis_portal.parametername', u'fields': { u'name': u'project_id', u'data_type': 2, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Project ID', u'units': u'', u'order': 9999, u'immutable': True, u'schema': [ u'http://www.tardis.edu.au/schemas/ngs/project' ] } } self._run_experiment__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_experiment', u'data_type': 4, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run Experiment link', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} self._run_number__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_number', u'data_type': 1, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run number', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} self._flowcell_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'flowcell_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Flowcell ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} self._instrument_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'instrument_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Instrument ' u'ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} self._instrument_model__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'instrument_model', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Instrument model', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} self._read_cycles__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'read_cycles', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Number of ' u'cycles in each read [index reads in (brackets)]', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} self._chemistry__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'chemistry', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Terminator' u'chemistry', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} self._operator_name__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'operator_name', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Instrument ' u'operator', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} self._rta_version__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'rta_version', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Illumina RTA ' u'version', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} self._ingestor_useragent__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'ingestor_useragent', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Ingestor User Agent', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']}} self._demultiplexing_program__attr_schema = { u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'demultiplexing_program', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Demultiplexing program version', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']} } self._demultiplexing_commandline_options__attr_schema = { u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'demultiplexing_commandline_options', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Demultiplexing commandline options', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project']} } self._subtype__schema = "demultiplexed-samples" self._model__schema = "tardis_portal.schema" self._name__schema = "Sequencing Project (Demultiplexed Sample Set)" self._pk__schema = None self._type__schema = 1 self._hidden__schema = False self._namespace__schema = "http://www.tardis.edu.au/schemas/ngs/project" self._immutable__schema = True class NucleotideRawReadsDatasetBase(MyTardisParameterSet): def __init__(self): super(NucleotideRawReadsDatasetBase, self).__init__() self.run_id = None self.project_experiment = None self.run_experiment = None self.fastqc_dataset = None self.run_number = None self.flowcell_id = None self.instrument_id = None self.instrument_model = None self.read_cycles = None self.chemistry = None self.operator_name = None self.rta_version = None self._run_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run Unique ' u'ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} self._project_experiment__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'project_experiment', u'data_type': 4, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Project Experiment link', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} self._run_experiment__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_experiment', u'data_type': 4, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run Experiment link', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} self._fastqc_dataset__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'fastqc_dataset', u'data_type': 4, u'immutable': False, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Associated FastQC reports', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} self._run_number__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_number', u'data_type': 1, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run number', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} self._flowcell_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'flowcell_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Flowcell ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} self._instrument_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'instrument_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Instrument ' u'ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} self._instrument_model__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'instrument_model', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Instrument model', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} self._read_cycles__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'read_cycles', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Number of' u'cycles in each read [index reads in (brackets)]', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} self._chemistry__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'chemistry', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Terminator' u'chemistry', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} self._operator_name__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'operator_name', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Instrument ' u'operator', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} self._rta_version__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'rta_version', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Illumina RTA ' u'version', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/raw_reads']}} self._subtype__schema = "nucleotide-raw-reads-dataset" self._model__schema = "tardis_portal.schema" self._name__schema = "Nucleotide Sequencing Project Raw Reads" self._pk__schema = None self._type__schema = 2 self._hidden__schema = False self._namespace__schema = "http://www.tardis.edu.au/schemas/ngs/project/raw_reads" self._immutable__schema = True class FastqcReportsBase(MyTardisParameterSet): def __init__(self): super(FastqcReportsBase, self).__init__() self.run_id = None self.project = None self.raw_reads_dataset = None self.fastqc_version = None self._run_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run Unique ' u'ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/fastqc']}} self._project__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'project', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Project name', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/fastqc']}} self._raw_reads_dataset__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'raw_reads_dataset', u'data_type': 4, u'immutable': False, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Raw reads project link', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/fastqc']}} self._fastqc_version__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'fastqc_version', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'FastQC software version', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/fastqc']}} self._subtype__schema = "fastqc-reports" self._model__schema = "tardis_portal.schema" self._name__schema = "FastQC Reports" self._pk__schema = None self._type__schema = 2 self._hidden__schema = False self._namespace__schema = "http://www.tardis.edu.au/schemas/ngs/project/fastqc" self._immutable__schema = True class HiddenFastqcProjectSummaryBase(MyTardisParameterSet): def __init__(self): super(HiddenFastqcProjectSummaryBase, self).__init__() self.hidden_fastqc_summary_json = None self.fastqc_version = None self._hidden_fastqc_summary_json__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'hidden_fastqc_summary_json', u'data_type': 8, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'(Hidden) FastQC summary for all samples (JSON)', u'units': u'fastqc-summary-table', u'order': 9999, u'schema': [u'http:' u'//www.tardis.edu.au/schemas/ngs/project/hidden_fastqc_summary']}} self._fastqc_version__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'fastqc_version', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'FastQC software version', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/project/__hid' u'den__fastqc_summary']}} self._subtype__schema = "hidden-fastqc-project-summary" self._model__schema = "tardis_portal.schema" self._name__schema = "FastQC Project Summary" self._pk__schema = None self._type__schema = 2 self._hidden__schema = True self._namespace__schema = "http://www.tardis.edu.au/schemas/ngs/project/hidden_fastqc_summary" self._immutable__schema = True class FastqRawReadsBase(MyTardisParameterSet): def __init__(self): super(FastqRawReadsBase, self).__init__() self.run_id = None self.sample_id = None self.sample_name = None self.lane = None self.read = None self.reference_genome = None self.index_sequence = None self.is_control = None self.recipe = None self.operator_name = None self.description = None self.project = None self.number_of_reads = None self.number_of_poor_quality_reads = None self.read_length = None self._run_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run Unique ' u'ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} self._sample_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'sample_id', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Sample ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} self._sample_name__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'sample_name', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Sample name', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} self._lane__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'lane', u'data_type': 1, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Lane', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} self._read__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'read', u'data_type': 1, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Read number', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} self._reference_genome__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'reference_genome', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Reference genome', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} self._index_sequence__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'index_sequence', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Index sequence (barcode) for this sample', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} self._is_control__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'is_control', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Is control ?', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} self._recipe__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'recipe', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Recipe', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} self._operator_name__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'operator_name', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Instrument ' u'Operator', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} self._description__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'description', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Description', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} self._project__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'project', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Project name', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} self._number_of_reads__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'number_of_reads', u'data_type': 1, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Number of reads', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} self._number_of_poor_quality_reads__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'number_of_poor_quality_reads', u'data_type': 1, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Number of reads flagged as poor quality (FastQC)', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} self._read_length__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'read_length', u'data_type': 1, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Read length', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastq']}} self._subtype__schema = "fastq-raw-reads" self._model__schema = "tardis_portal.schema" self._name__schema = "Nucleotide Sequence Raw Reads (FASTQ)" self._pk__schema = None self._type__schema = 3 self._hidden__schema = False self._namespace__schema = "http://www.tardis.edu.au/schemas/ngs/file/fastq" self._immutable__schema = True class FastqcOutputBase(MyTardisParameterSet): def __init__(self): super(FastqcOutputBase, self).__init__() self.run_id = None self.sample_id = None self.project = None self.fastqc_version = None self._run_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run Unique ' u'ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastqc']}} self._sample_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'sample_id', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Sample ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastqc']}} self._project__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'project', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'Project name', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastqc']}} self._fastqc_version__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'fastqc_version', u'data_type': 2, u'immutable': True, u'is_searchable': False, u'choices': u'', u'comparison_type': 1, u'full_name': u'FastQC software version', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/file/fastqc']}} self._subtype__schema = "fastqc-output" self._model__schema = "tardis_portal.schema" self._name__schema = "FastQC report" self._pk__schema = None self._type__schema = 3 self._hidden__schema = False self._namespace__schema = "http://www.tardis.edu.au/schemas/ngs/file/fastqc" self._immutable__schema = True class IlluminaRunConfigBase(MyTardisParameterSet): def __init__(self): super(IlluminaRunConfigBase, self).__init__() self.run_id = None self._run_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina/config']}} self._subtype__schema = "illumina-run-config" self._model__schema = "tardis_portal.schema" self._name__schema = "Illumia run config and log files" self._pk__schema = None self._type__schema = 2 self._hidden__schema = False self._namespace__schema = "http://www.tardis.edu.au/schemas/ngs/run/illumina/config" self._immutable__schema = True class IlluminaRunInstrumentFilesBase(MyTardisParameterSet): def __init__(self): super(IlluminaRunInstrumentFilesBase, self).__init__() self.run_id = None self._run_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina/files']}} self._subtype__schema = "illumina-run-instrument-files" self._model__schema = "tardis_portal.schema" self._name__schema = "Illumia run instrument files" self._pk__schema = None self._type__schema = 2 self._hidden__schema = False self._namespace__schema = "http://www.tardis.edu.au/schemas/ngs/run/illumina/files" self._immutable__schema = True class IlluminaRunInstrumentFileBase(MyTardisParameterSet): def __init__(self): super(IlluminaRunInstrumentFileBase, self).__init__() self.run_id = None self._run_id__attr_schema = {u'pk': None, u'model': u'tardis_portal.parametername', u'fields': {u'name': u'run_id', u'data_type': 2, u'immutable': True, u'is_searchable': True, u'choices': u'', u'comparison_type': 1, u'full_name': u'Run ID', u'units': u'', u'order': 9999, u'schema': [u'http://www.tardis.edu.au/schemas/ngs/run/illumina/files']}} self._subtype__schema = "illumina-run-instrument-file" self._model__schema = "tardis_portal.schema" self._name__schema = "Illumina instrument run file" self._pk__schema = None self._type__schema = 3 self._hidden__schema = False self._namespace__schema = "http://www.tardis.edu.au/schemas/ngs/run/file" self._immutable__schema = True
true
true
f7fe8c079b89289ce6b4343d8a4e2c41a431580a
68,217
py
Python
Python/Version 5.1 (English Real-Time search)/maze51.py
clayfish/maze
03bad22426d90225eca71d20f16e2da590a22aa2
[ "MIT" ]
null
null
null
Python/Version 5.1 (English Real-Time search)/maze51.py
clayfish/maze
03bad22426d90225eca71d20f16e2da590a22aa2
[ "MIT" ]
null
null
null
Python/Version 5.1 (English Real-Time search)/maze51.py
clayfish/maze
03bad22426d90225eca71d20f16e2da590a22aa2
[ "MIT" ]
null
null
null
from tkinter import * from tkinter import font from tkinter import messagebox from functools import partial from operator import attrgetter import webbrowser import numpy import random import math import os """ @author Nikos Kanargias E-mail: nkana@tee.gr @version 5.1 The software solves and visualizes the robot motion planning problem, by implementing variants of DFS, BFS and A* algorithms, as described by E. Keravnou in her book: "Artificial Intelligence and Expert Systems", Hellenic Open University, Patra 2000 (in Greek) as well as the Greedy search algorithm, as a special case of A*. The software also implements Dijkstra's algorithm, as just described in the relevant article in Wikipedia. http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm The superiority of A* and Dijkstra's algorithms against the other three becomes obvious. The user can change the number of the grid cells, indicating the desired number of rows and columns. The user can add as many obstacles he/she wants, as he/she would "paint" free curves with a drawing program. Individual obstacles can be removed by clicking them. The position of the robot and/or the target can be changed by dragging with the mouse. Jump from search in "Step-by-Step" way to "Animation" way and vice versa is done by pressing the corresponding button, even when the search is in progress. The speed of a search can be changed, even if the search is in progress. It is sufficient to place the slider "Speed" in the new desired position and then press the "Animation" button. The application considers that the robot itself has some volume. Therefore it can’t move diagonally to a free cell passing between two obstacles adjacent to one apex. When 'Step-by-Step' or 'Animation' search is underway it is not possible to change the position of obstacles, robot and target, as well as the search algorithm. When 'Real-Time' search is underway the position of obstacles, robot and target can be changed. Drawing of arrows to predecessors, when requested, is performed only at the end of the search. """ class Maze51: class CreateToolTip(object): """ Helper class that creates a tooltip for a given widget """ # from https://stackoverflow.com/questions/3221956/what-is-the-simplest-way-to-make-tooltips-in-tkinter def __init__(self, widget, text='widget info'): self.waittime = 500 # milliseconds self.wraplength = 180 # pixels self.widget = widget self.text = text self.widget.bind("<Enter>", self.enter) self.widget.bind("<Leave>", self.leave) self.widget.bind("<ButtonPress>", self.leave) self._id = None self.tw = None def enter(self, event=None): self.schedule() def leave(self, event=None): self.unschedule() self.hidetip() def schedule(self): self.unschedule() self._id = self.widget.after(self.waittime, self.showtip) def unschedule(self): _id = self._id self._id = None if _id: self.widget.after_cancel(_id) def showtip(self, event=None): x, y, cx, cy = self.widget.bbox("insert") x += self.widget.winfo_rootx() + 25 y += self.widget.winfo_rooty() + 20 # creates a toplevel window self.tw = Toplevel(self.widget) # Leaves only the label and removes the app window self.tw.wm_overrideredirect(True) self.tw.wm_geometry("+%d+%d" % (x, y)) label = Label(self.tw, text=self.text, justify='left', background="#ffffff", relief='solid', borderwidth=1, wraplength=self.wraplength) label.pack(ipadx=1) def hidetip(self): tw = self.tw self.tw = None if tw: tw.destroy() class MyMaze(object): """ Helper class that creates a random, perfect (without cycles) maze """ # The code of the class is an adaptation, with the original commentary, of the answer given # by user DoubleMx2 on August 25, 2013 to a question posted by user nazar_art at stackoverflow.com: # http://stackoverflow.com/questions/18396364/maze-generation-arrayindexoutofboundsexception def __init__(self, x_dimension, y_dimension): self.dimensionX = x_dimension # dimension of maze self.dimensionY = y_dimension self.gridDimensionX = x_dimension * 2 + 1 # dimension of output grid self.gridDimensionY = y_dimension * 2 + 1 # output grid self.mazeGrid = [[' ' for y in range(self.gridDimensionY)] for x in range(self.gridDimensionX)] # 2d array of Cells self.cells = [[self.Cell(x, y, False) for y in range(self.dimensionY)] for x in range(self.dimensionX)] self.generate_maze() self.update_grid() class Cell(object): """ inner class to represent a cell """ def __init__(self, x, y, is_wall=True): self.neighbors = [] # cells this cell is connected to self.open = True # if true, has yet to be used in generation self.x = x # coordinates self.y = y self.wall = is_wall # impassable cell def add_neighbor(self, other): """ add a neighbor to this cell, and this cell as a neighbor to the other """ if other not in self.neighbors: # avoid duplicates self.neighbors.append(other) if self not in other.neighbors: # avoid duplicates other.neighbors.append(self) def is_cell_below_neighbor(self): """ used in update_grid() """ return self.__class__(self.x, self.y + 1) in self.neighbors def is_cell_right_neighbor(self): """ used in update_grid() """ return self.__class__(self.x + 1, self.y) in self.neighbors def __eq__(self, other): """ useful Cell equivalence """ if isinstance(other, self.__class__): return self.x == other.x and self.y == other.y else: return False def generate_maze(self): """ generate the maze from upper left (In computing the y increases down often) """ start_at = self.get_cell(0, 0) start_at.open = False # indicate cell closed for generation cells = [start_at] while cells: # this is to reduce but not completely eliminate the number # of long twisting halls with short easy to detect branches # which results in easy mazes if random.randint(0, 9) == 0: cell = cells.pop(random.randint(0, cells.__len__()) - 1) else: cell = cells.pop(cells.__len__() - 1) # for collection neighbors = [] # cells that could potentially be neighbors potential_neighbors = [self.get_cell(cell.x + 1, cell.y), self.get_cell(cell.x, cell.y + 1), self.get_cell(cell.x - 1, cell.y), self.get_cell(cell.x, cell.y - 1)] for other in potential_neighbors: # skip if outside, is a wall or is not opened if other is None or other.wall or not other.open: continue neighbors.append(other) if not neighbors: continue # get random cell selected = neighbors[random.randint(0, neighbors.__len__()) - 1] # add as neighbor selected.open = False # indicate cell closed for generation cell.add_neighbor(selected) cells.append(cell) cells.append(selected) def get_cell(self, x, y): """ used to get a Cell at x, y; returns None out of bounds """ if x < 0 or y < 0: return None try: return self.cells[x][y] except IndexError: # catch out of bounds return None def update_grid(self): """ draw the maze """ back_char = ' ' wall_char = 'X' cell_char = ' ' # fill background for x in range(self.gridDimensionX): for y in range(self.gridDimensionY): self.mazeGrid[x][y] = back_char # build walls for x in range(self.gridDimensionX): for y in range(self.gridDimensionY): if x % 2 == 0 or y % 2 == 0: self.mazeGrid[x][y] = wall_char # make meaningful representation for x in range(self.dimensionX): for y in range(self.dimensionY): current = self.get_cell(x, y) grid_x = x * 2 + 1 grid_y = y * 2 + 1 self.mazeGrid[grid_x][grid_y] = cell_char if current.is_cell_below_neighbor(): self.mazeGrid[grid_x][grid_y + 1] = cell_char if current.is_cell_right_neighbor(): self.mazeGrid[grid_x + 1][grid_y] = cell_char class Cell(object): """ Helper class that represents the cell of the grid """ def __init__(self, row, col): self.row = row # the row number of the cell(row 0 is the top) self.col = col # the column number of the cell (column 0 is the left) self.g = 0 # the value of the function g of A* and Greedy algorithms self.h = 0 # the value of the function h of A* and Greedy algorithms self.f = 0 # the value of the function f of A* and Greedy algorithms # the distance of the cell from the initial position of the robot # Ie the label that updates the Dijkstra's algorithm self.dist = 0 # Each state corresponds to a cell # and each state has a predecessor which # stored in this variable self.prev = self.__class__ def __eq__(self, other): """ useful Cell equivalence """ if isinstance(other, self.__class__): return self.row == other.row and self.col == other.col else: return False ####################################### # # # Constants of Maze42 class # # # ####################################### INFINITY = sys.maxsize # The representation of the infinite EMPTY = 0 # empty cell OBST = 1 # cell with obstacle ROBOT = 2 # the position of the robot TARGET = 3 # the position of the target FRONTIER = 4 # cells that form the frontier (OPEN SET) CLOSED = 5 # cells that form the CLOSED SET ROUTE = 6 # cells that form the robot-to-target path MSG_DRAW_AND_SELECT = "\"Paint\" obstacles, then click 'Real-Time' or 'Step-by-Step' or 'Animation'" MSG_SELECT_STEP_BY_STEP_ETC = "Click 'Step-by-Step' or 'Animation' or 'Clear'" MSG_NO_SOLUTION = "There is no path to the target !!!" def __init__(self, maze): """ Constructor """ self.center(maze) self.rows = 41 # the number of rows of the grid self.columns = 41 # the number of columns of the grid self.square_size = int(500/self.rows) # the cell size in pixels self.arrow_size = int(self.square_size/2) # the size of the tips of the arrow pointing the predecessor cell self.openSet = [] # the OPEN SET self.closedSet = [] # the CLOSED SET self.graph = [] # the set of vertices of the graph to be explored by Dijkstra's algorithm self.robotStart = self.Cell(self.rows - 2, 1) # the initial position of the robot self.targetPos = self.Cell(1, self.columns - 2) # the position of the target self.grid = [[]] # the grid self.realTime = False # Solution is displayed instantly self.found = False # flag that the goal was found self.searching = False # flag that the search is in progress self.endOfSearch = False # flag that the search came to an end self.animation = False # flag that the animation is running self.delay = 500 # time delay of animation (in msec) self.expanded = 0 # the number of nodes that have been expanded self.selected_algo = "DFS" # DFS is initially selected self.array = numpy.array([0] * (83 * 83)) self.cur_row = self.cur_col = self.cur_val = 0 app_highlight_font = font.Font(app, family='Helvetica', size=10, weight='bold') ########################################## # # # the widgets of the user interface # # # ########################################## self.message = Label(app, text=self.MSG_DRAW_AND_SELECT, width=55, anchor='center', font=('Helvetica', 12), fg="BLUE") self.message.place(x=5, y=510) rows_lbl = Label(app, text="# of rows (5-83):", width=16, anchor='e', font=("Helvetica", 9)) rows_lbl.place(x=530, y=5) validate_rows_cmd = (app.register(self.validate_rows), '%P') invalid_rows_cmd = (app.register(self.invalid_rows)) self.rows_var = StringVar() self.rows_var.set(41) self.rowsSpinner = Spinbox(app, width=3, from_=5, to=83, textvariable=self.rows_var, validate='focus', validatecommand=validate_rows_cmd, invalidcommand=invalid_rows_cmd) self.rowsSpinner.place(x=652, y=5) cols_lbl = Label(app, text="# of columns (5-83):", width=16, anchor='e', font=("Helvetica", 9)) cols_lbl.place(x=530, y=35) validate_cols_cmd = (app.register(self.validate_cols), '%P') invalid_cols_cmd = (app.register(self.invalid_cols)) self.cols_var = StringVar() self.cols_var.set(41) self.colsSpinner = Spinbox(app, width=3, from_=5, to=83, textvariable=self.cols_var, validate='focus', validatecommand=validate_cols_cmd, invalidcommand=invalid_cols_cmd) self.colsSpinner.place(x=652, y=35) self.buttons = list() buttons_tool_tips = ("Clears and redraws the grid according to the given rows and columns", "Creates a random maze", "First click: clears search, Second click: clears obstacles", "Position of obstacles, robot and target can be changed when search is underway", "The search is performed step-by-step for every click", "The search is performed automatically") for i, action in enumerate(("New grid", "Maze", "Clear", "Real-Time", "Step-by-Step", "Animation")): btn = Button(app, text=action, width=20, font=app_highlight_font, bg="light grey", command=partial(self.select_action, action)) btn.place(x=515, y=65+30*i) self.CreateToolTip(btn, buttons_tool_tips[i]) self.buttons.append(btn) time_delay = Label(app, text="Delay (msec)", width=27, anchor='center', font=("Helvetica", 8)) time_delay.place(x=515, y=243) slider_value = IntVar() slider_value.set(500) self.slider = Scale(app, orient=HORIZONTAL, length=165, width=10, from_=0, to=1000, showvalue=1, variable=slider_value,) self.slider.place(x=515, y=260) self.CreateToolTip(self.slider, "Regulates the delay for each step (0 to 1000 msec)") self.frame = LabelFrame(app, text="Algorithms", width=170, height=100) self.frame.place(x=515, y=300) self.radio_buttons = list() radio_buttons_tool_tips = ("Depth First Search algorithm", "Breadth First Search algorithm", "A* algorithm", "Greedy search algorithm", "Dijkstra's algorithm") for i, algorithm in enumerate(("DFS", "BFS", "A*", "Greedy", "Dijkstra")): btn = Radiobutton(self.frame, text=algorithm, font=app_highlight_font, value=i + 1, command=partial(self.select_algo, algorithm)) btn.place(x=10 if i % 2 == 0 else 90, y=int(i/2)*25) self.CreateToolTip(btn, radio_buttons_tool_tips[i]) btn.deselect() self.radio_buttons.append(btn) self.radio_buttons[0].select() self.diagonal = IntVar() self.diagonalBtn = Checkbutton(app, text="Diagonal movements", font=app_highlight_font, variable=self.diagonal) self.diagonalBtn.place(x=515, y=405) self.CreateToolTip(self.diagonalBtn, "Diagonal movements are also allowed") self.drawArrows = IntVar() self.drawArrowsBtn = Checkbutton(app, text="Arrows to predecessors", font=app_highlight_font, variable=self.drawArrows) self.drawArrowsBtn.place(x=515, y=430) self.CreateToolTip(self.drawArrowsBtn, "Draw arrows to predecessors") memo_colors = ("RED", "GREEN", "BLUE", "CYAN") for i, memo in enumerate(("Robot", "Target", "Frontier", "Closed set")): label = Label(app, text=memo, width=8, anchor='center', fg=memo_colors[i], font=("Helvetica", 11)) label.place(x=515 if i % 2 == 0 else 605, y=460+int(i/2)*20) self.about_button = Button(app, text='About Maze', width=20, font=app_highlight_font, bg="light grey", command=self.about_click) self.about_button.place(x=515, y=505) self.canvas = Canvas(app, bd=0, highlightthickness=0) self.canvas.bind("<Button-1>", self.left_click) self.canvas.bind("<B1-Motion>", self.drag) self.initialize_grid(False) def validate_rows(self, entry): """ Validates entry in rowsSpinner :param entry: the value entered by the user :return: True, if entry is valid """ try: value = int(entry) valid = value in range(5, 84) except ValueError: valid = False if not valid: app.bell() # The following line is due to user PRMoureu of stackoverflow. See: # https://stackoverflow.com/questions/46861236/widget-validation-in-tkinter/46863849?noredirect=1#comment80675412_46863849 self.rowsSpinner.after_idle(lambda: self.rowsSpinner.config(validate='focusout')) return valid def invalid_rows(self): """ Sets default value to rowsSpinner in case of invalid entry """ self.rows_var.set(41) def validate_cols(self, entry): """ Validates entry in colsSpinner :param entry: the value entered by the user :return: True, if entry is valid """ try: value = int(entry) valid = value in range(5, 84) except ValueError: valid = False if not valid: app.bell() self.colsSpinner.after_idle(lambda: self.colsSpinner.config(validate='focusout')) return valid def invalid_cols(self): """ Sets default value to colsSpinner in case of invalid entry """ self.cols_var.set(41) def select_action(self, action): if action == "New grid": self.reset_click() elif action == "Maze": self.maze_click() elif action == "Clear": self.clear_click() elif action == "Real-Time": self.real_time_click() elif action == "Step-by-Step": self.step_by_step_click() elif action == "Animation": self.animation_click() def select_algo(self, algorithm): self.selected_algo = algorithm def left_click(self, event): """ Handles clicks of left mouse button as we add or remove obstacles """ row = int(event.y/self.square_size) col = int(event.x/self.square_size) if row in range(self.rows) and col in range(self.columns): if True if self.realTime else (not self.found and not self.searching): if self.realTime: self.fill_grid() self.cur_row = row self.cur_col = col self.cur_val = self.grid[row][col] if self.cur_val == self.EMPTY: self.grid[row][col] = self.OBST self.paint_cell(row, col, "BLACK") if self.cur_val == self.OBST: self.grid[row][col] = self.EMPTY self.paint_cell(row, col, "WHITE") if self.realTime and self.selected_algo == "Dijkstra": self.initialize_dijkstra() if self.realTime: self.real_Time_action() def drag(self, event): """ Handles mouse movements as we "paint" obstacles or move the robot and/or target. """ row = int(event.y/self.square_size) col = int(event.x/self.square_size) if row in range(self.rows) and col in range(self.columns): if True if self.realTime else (not self.found and not self.searching): if self.realTime: self.fill_grid() if self.Cell(row, col) != self.Cell(self.cur_row, self.cur_col) and\ self.cur_val in [self.ROBOT, self.TARGET]: new_val = self.grid[row][col] if new_val == self.EMPTY: self.grid[row][col] = self.cur_val if self.cur_val == self.ROBOT: self.grid[self.robotStart.row][self.robotStart.col] = self.EMPTY self.paint_cell(self.robotStart.row, self.robotStart.col, "WHITE") self.robotStart.row = row self.robotStart.col = col self.grid[self.robotStart.row][self.robotStart.col] = self.ROBOT self.paint_cell(self.robotStart.row, self.robotStart.col, "RED") else: self.grid[self.targetPos.row][self.targetPos.col] = self.EMPTY self.paint_cell(self.targetPos.row, self.targetPos.col, "WHITE") self.targetPos.row = row self.targetPos.col = col self.grid[self.targetPos.row][self.targetPos.col] = self.TARGET self.paint_cell(self.targetPos.row, self.targetPos.col, "GREEN") self.cur_row = row self.cur_col = col self.cur_val = self.grid[row][col] elif self.grid[row][col] != self.ROBOT and self.grid[row][col] != self.TARGET: self.grid[row][col] = self.OBST self.paint_cell(row, col, "BLACK") if self.realTime and self.selected_algo == "Dijkstra": self.initialize_dijkstra() if self.realTime: self.real_Time_action() def initialize_grid(self, make_maze): """ Creates a new clean grid or a new maze :param make_maze: flag that indicates the creation of a random maze """ self.rows = int(self.rowsSpinner.get()) self.columns = int(self.colsSpinner.get()) if make_maze and self.rows % 2 == 0: self.rows -= 1 if make_maze and self.columns % 2 == 0: self.columns -= 1 self.square_size = int(500/(self.rows if self.rows > self.columns else self.columns)) self.arrow_size = int(self.square_size/2) self.grid = self.array[:self.rows*self.columns] self.grid = self.grid.reshape(self.rows, self.columns) self.canvas.configure(width=self.columns*self.square_size+1, height=self.rows*self.square_size+1) self.canvas.place(x=10, y=10) self.canvas.create_rectangle(0, 0, self.columns*self.square_size+1, self.rows*self.square_size+1, width=0, fill="DARK GREY") for r in list(range(self.rows)): for c in list(range(self.columns)): self.grid[r][c] = self.EMPTY self.robotStart = self.Cell(self.rows-2, 1) self.targetPos = self.Cell(1, self.columns-2) self.fill_grid() if make_maze: maze = self.MyMaze(int(self.rows/2), int(self.columns/2)) for x in range(maze.gridDimensionX): for y in range(maze.gridDimensionY): if maze.mazeGrid[x][y] == 'X': # maze.wall_char: self.grid[x][y] = self.OBST self.repaint() def fill_grid(self): """ Gives initial values ​​for the cells in the grid. """ # With the first click on button 'Clear' clears the data # of any search was performed (Frontier, Closed Set, Route) # and leaves intact the obstacles and the robot and target positions # in order to be able to run another algorithm # with the same data. # With the second click removes any obstacles also. if self.searching or self.endOfSearch: for r in list(range(self.rows)): for c in list(range(self.columns)): if self.grid[r][c] in [self.FRONTIER, self.CLOSED, self.ROUTE]: self.grid[r][c] = self.EMPTY if self.grid[r][c] == self.ROBOT: self.robotStart = self.Cell(r, c) self.searching = False else: for r in list(range(self.rows)): for c in list(range(self.columns)): self.grid[r][c] = self.EMPTY self.robotStart = self.Cell(self.rows-2, 1) self.targetPos = self.Cell(1, self.columns-2) if self.selected_algo in ["A*", "Greedy"]: self.robotStart.g = 0 self.robotStart.h = 0 self.robotStart.f = 0 self.expanded = 0 self.found = False self.searching = False self.endOfSearch = False self.openSet.clear() self.closedSet.clear() self.openSet = [self.robotStart] self.closedSet = [] self.grid[self.targetPos.row][self.targetPos.col] = self.TARGET self.grid[self.robotStart.row][self.robotStart.col] = self.ROBOT self.message.configure(text=self.MSG_DRAW_AND_SELECT) self.repaint() def repaint(self): """ Repaints the grid """ color = "" for r in list(range(self.rows)): for c in list(range(self.columns)): if self.grid[r][c] == self.EMPTY: color = "WHITE" elif self.grid[r][c] == self.ROBOT: color = "RED" elif self.grid[r][c] == self.TARGET: color = "GREEN" elif self.grid[r][c] == self.OBST: color = "BLACK" elif self.grid[r][c] == self.FRONTIER: color = "BLUE" elif self.grid[r][c] == self.CLOSED: color = "CYAN" elif self.grid[r][c] == self.ROUTE: color = "YELLOW" self.paint_cell(r, c, color) def paint_cell(self, row, col, color): """ Paints a particular cell :param row: # the row of the cell :param col: # the column of the cell :param color: # the color of the cell """ self.canvas.create_rectangle(1 + col * self.square_size, 1 + row * self.square_size, 1 + (col + 1) * self.square_size - 1, 1 + (row + 1) * self.square_size - 1, width=0, fill=color) def reset_click(self): """ Action performed when user clicks "New grid" button """ self.animation = False self.realTime = False for but in self.buttons: but.configure(state="normal") self.buttons[3].configure(fg="BLACK") # Real-Time button self.slider.configure(state="normal") for but in self.radio_buttons: but.configure(state="normal") self.diagonalBtn.configure(state="normal") self.drawArrowsBtn.configure(state="normal") self.initialize_grid(False) def maze_click(self): """ Action performed when user clicks "Maze" button """ self.animation = False self.realTime = False for but in self.buttons: but.configure(state="normal") self.buttons[3].configure(fg="BLACK") # Real-Time button self.slider.configure(state="normal") for but in self.radio_buttons: but.configure(state="normal") self.diagonalBtn.configure(state="normal") self.drawArrowsBtn.configure(state="normal") self.initialize_grid(True) def clear_click(self): """ Action performed when user clicks "Clear" button """ self.animation = False self.realTime = False for but in self.buttons: but.configure(state="normal") self.buttons[3].configure(fg="BLACK") # Real-Time button self.slider.configure(state="normal") for but in self.radio_buttons: but.configure(state="normal") self.diagonalBtn.configure(state="normal") self.drawArrowsBtn.configure(state="normal") self.fill_grid() def real_time_click(self): """ Action performed when user clicks "Real-Time" button """ if self.realTime: return self.realTime = True self.searching = True # The Dijkstra's initialization should be done just before the # start of search, because obstacles must be in place. if self.selected_algo == "Dijkstra": self.initialize_dijkstra() self.buttons[3].configure(fg="RED") # Real-Time button self.slider.configure(state="disabled") for but in self.radio_buttons: but.configure(state="disabled") self.diagonalBtn.configure(state="disabled") self.drawArrowsBtn.configure(state="disabled") self.real_Time_action() def real_Time_action(self): """ Action performed during real-time search """ while not self.endOfSearch: self.check_termination() def step_by_step_click(self): """ Action performed when user clicks "Step-by-Step" button """ if self.found or self.endOfSearch: return if not self.searching and self.selected_algo == "Dijkstra": self.initialize_dijkstra() self.animation = False self.searching = True self.message.configure(text=self.MSG_SELECT_STEP_BY_STEP_ETC) self.buttons[3].configure(state="disabled") # Real-Time button for but in self.radio_buttons: but.configure(state="disabled") self.diagonalBtn.configure(state="disabled") self.drawArrowsBtn.configure(state="disabled") self.check_termination() def animation_click(self): """ Action performed when user clicks "Animation" button """ self.animation = True if not self.searching and self.selected_algo == "Dijkstra": self.initialize_dijkstra() self.searching = True self.message.configure(text=self.MSG_SELECT_STEP_BY_STEP_ETC) self.buttons[3].configure(state="disabled") # Real-Time button for but in self.radio_buttons: but.configure(state="disabled") self.diagonalBtn.configure(state="disabled") self.drawArrowsBtn.configure(state="disabled") self.delay = self.slider.get() self.animation_action() def animation_action(self): """ The action periodically performed during searching in animation mode """ if self.animation: self.check_termination() if self.endOfSearch: return self.canvas.after(self.delay, self.animation_action) def about_click(self): """ Action performed when user clicks "About Maze" button """ about_box = Toplevel(master=app) about_box.title("") about_box.geometry("340x160") about_box.resizable(False, False) self.center(about_box) about_box.transient(app) # only one window in the task bar about_box.grab_set() # modal title = Label(about_box, text="Maze", width=20, anchor='center', fg='SANDY BROWN', font=("Helvetica", 20)) title.place(x=0, y=0) version = Label(about_box, text="Version: 5.1", width=35, anchor='center', font=("Helvetica", 11, 'bold')) version.place(x=0, y=35) programmer = Label(about_box, text="Designer: Nikos Kanargias", width=35, anchor='center', font=("Helvetica", 12)) programmer.place(x=0, y=60) email = Label(about_box, text="E-mail: nkana@tee.gr", width=40, anchor='center', font=("Helvetica", 10)) email.place(x=0, y=80) source_code = Label(about_box, text="Code and documentation", fg="blue", cursor="hand2", width=35, anchor='center', font=("Helvetica", 12)) f = font.Font(source_code, source_code.cget("font")) f.configure(underline=True) source_code.configure(font=f) source_code.place(x=0, y=100) source_code.bind("<Button-1>", self.source_code_callback) self.CreateToolTip(source_code, "Click this link to retrieve code and documentation from DropBox") video = Label(about_box, text="Watch demo video on YouTube", fg="blue", cursor="hand2", width=35, anchor='center') video.configure(font=f) video.place(x=0, y=125) video.bind("<Button-1>", self.video_callback) self.CreateToolTip(video, "Click this link to watch a demo video on YouTube") def check_termination(self): """ Checks if search is completed """ # Here we decide whether we can continue the search or not. # In the case of DFS, BFS, A* and Greedy algorithms # here we have the second step: # 2. If OPEN SET = [], then terminate. There is no solution. if (self.selected_algo == "Dijkstra" and not self.graph) or\ self.selected_algo != "Dijkstra" and not self.openSet: self.endOfSearch = True self.grid[self.robotStart.row][self.robotStart.col] = self.ROBOT self.message.configure(text=self.MSG_NO_SOLUTION) self.buttons[4].configure(state="disabled") # Step-by-Step button self.buttons[5].configure(state="disabled") # Animation button self.slider.configure(state="disabled") self.repaint() if self.drawArrows.get(): self.draw_arrows() else: self.expand_node() if self.found: self.endOfSearch = True self.plot_route() self.buttons[4].configure(state="disabled") # Step-by-Step button self.buttons[5].configure(state="disabled") # Animation button self.slider.configure(state="disabled") def expand_node(self): """ Expands a node and creates his successors """ # Dijkstra's algorithm to handle separately if self.selected_algo == "Dijkstra": # 11: while Q is not empty: if not self.graph: return # 12: u := vertex in Q (graph) with smallest distance in dist[] ; # 13: remove u from Q (graph); u = self.graph.pop(0) # Add vertex u in closed set self.closedSet.append(u) # If target has been found ... if u == self.targetPos: self.found = True return # Counts nodes that have expanded. self.expanded += 1 # Update the color of the cell self.grid[u.row][u.col] = self.CLOSED # paint the cell self.paint_cell(u.row, u.col, "CYAN") # 14: if dist[u] = infinity: if u.dist == self.INFINITY: # ... then there is no solution. # 15: break; return # 16: end if # Create the neighbors of u neighbors = self.create_successors(u, False) # 18: for each neighbor v of u: for v in neighbors: # 20: alt := dist[u] + dist_between(u, v) ; alt = u.dist + self.dist_between(u, v) # 21: if alt < dist[v]: if alt < v.dist: # 22: dist[v] := alt ; v.dist = alt # 23: previous[v] := u ; v.prev = u # Update the color of the cell self.grid[v.row][v.col] = self.FRONTIER # paint the cell self.paint_cell(v.row, v.col, "BLUE") # 24: decrease-key v in Q; # (sort list of nodes with respect to dist) self.graph.sort(key=attrgetter("dist")) # The handling of the other four algorithms else: if self.selected_algo in ["DFS", "BFS"]: # Here is the 3rd step of the algorithms DFS and BFS # 3. Remove the first state, Si, from OPEN SET ... current = self.openSet.pop(0) else: # Here is the 3rd step of the algorithms A* and Greedy # 3. Remove the first state, Si, from OPEN SET, # for which f(Si) ≤ f(Sj) for all other # open states Sj ... # (sort first OPEN SET list with respect to 'f') self.openSet.sort(key=attrgetter("f")) current = self.openSet.pop(0) # ... and add it to CLOSED SET. self.closedSet.insert(0, current) # Update the color of the cell self.grid[current.row][current.col] = self.CLOSED # paint the cell self.paint_cell(current.row, current.col, "CYAN") # If the selected node is the target ... if current == self.targetPos: # ... then terminate etc last = self.targetPos last.prev = current.prev self.closedSet.append(last) self.found = True return # Count nodes that have been expanded. self.expanded += 1 # Here is the 4rd step of the algorithms # 4. Create the successors of Si, based on actions # that can be implemented on Si. # Each successor has a pointer to the Si, as its predecessor. # In the case of DFS and BFS algorithms, successors should not # belong neither to the OPEN SET nor the CLOSED SET. successors = self.create_successors(current, False) # Here is the 5th step of the algorithms # 5. For each successor of Si, ... for cell in successors: # ... if we are running DFS ... if self.selected_algo == "DFS": # ... add the successor at the beginning of the list OPEN SET self.openSet.insert(0, cell) # Update the color of the cell self.grid[cell.row][cell.col] = self.FRONTIER # paint the cell self.paint_cell(cell.row, cell.col, "BLUE") # ... if we are runnig BFS ... elif self.selected_algo == "BFS": # ... add the successor at the end of the list OPEN SET self.openSet.append(cell) # Update the color of the cell self.grid[cell.row][cell.col] = self.FRONTIER # paint the cell self.paint_cell(cell.row, cell.col, "BLUE") # ... if we are running A* or Greedy algorithms (step 5 of A* algorithm) ... elif self.selected_algo in ["A*", "Greedy"]: # ... calculate the value f(Sj) ... dxg = current.col - cell.col dyg = current.row - cell.row dxh = self.targetPos.col - cell.col dyh = self.targetPos.row - cell.row if self.diagonal.get(): # with diagonal movements, calculate the Euclidean distance if self.selected_algo == "Greedy": # especially for the Greedy ... cell.g = 0 else: cell.g = current.g + math.sqrt(dxg*dxg + dyg*dyg) cell.h = math.sqrt(dxh*dxh + dyh*dyh) else: # without diagonal movements, calculate the Manhattan distance if self.selected_algo == "Greedy": # especially for the Greedy ... cell.g = 0 else: cell.g = current.g + abs(dxg) + abs(dyg) cell.h = abs(dxh) + abs(dyh) cell.f = cell.g+cell.h # ... If Sj is neither in the OPEN SET nor in the CLOSED SET states ... if cell not in self.openSet and cell not in self.closedSet: # ... then add Sj in the OPEN SET ... # ... evaluated as f(Sj) self.openSet.append(cell) # Update the color of the cell self.grid[cell.row][cell.col] = self.FRONTIER # paint the cell self.paint_cell(cell.row, cell.col, "BLUE") # Else ... else: # ... if already belongs to the OPEN SET, then ... if cell in self.openSet: open_index = self.openSet.index(cell) # ... compare the new value assessment with the old one. # If old <= new ... if self.openSet[open_index].f <= cell.f: # ... then eject the new node with state Sj. # (ie do nothing for this node). pass # Else, ... else: # ... remove the element (Sj, old) from the list # to which it belongs ... self.openSet.pop(open_index) # ... and add the item (Sj, new) to the OPEN SET. self.openSet.append(cell) # Update the color of the cell self.grid[cell.row][cell.col] = self.FRONTIER # paint the cell self.paint_cell(cell.row, cell.col, "BLUE") # ... if already belongs to the CLOSED SET, then ... elif cell in self.closedSet: closed_index = self.closedSet.index(cell) # ... compare the new value assessment with the old one. # If old <= new ... if self.closedSet[closed_index].f <= cell.f: # ... then eject the new node with state Sj. # (ie do nothing for this node). pass # Else, ... else: # ... remove the element (Sj, old) from the list # to which it belongs ... self.closedSet.pop(closed_index) # ... and add the item (Sj, new) to the OPEN SET. self.openSet.append(cell) # Update the color of the cell self.grid[cell.row][cell.col] = self.FRONTIER # paint the cell self.paint_cell(cell.row, cell.col, "BLUE") def create_successors(self, current, make_connected): """ Creates the successors of a state/cell :param current: the cell for which we ask successors :param make_connected: flag that indicates that we are interested only on the coordinates of cells and not on the label 'dist' (concerns only Dijkstra's) :return: the successors of the cell as a list """ r = current.row c = current.col # We create an empty list for the successors of the current cell. temp = [] # With diagonal movements priority is: # 1: Up 2: Up-right 3: Right 4: Down-right # 5: Down 6: Down-left 7: Left 8: Up-left # Without diagonal movements the priority is: # 1: Up 2: Right 3: Down 4: Left # If not at the topmost limit of the grid # and the up-side cell is not an obstacle # and (only in the case are not running the A* or Greedy) # not already belongs neither to the OPEN SET nor to the CLOSED SET ... if r > 0 and self.grid[r-1][c] != self.OBST and\ (self.selected_algo in ["A*", "Greedy", "Dijkstra"] or (self.selected_algo in ["DFS", "BFS"] and not self.Cell(r-1, c) in self.openSet and not self.Cell(r-1, c) in self.closedSet)): cell = self.Cell(r-1, c) # In the case of Dijkstra's algorithm we can not append to # the list of successors the "naked" cell we have just created. # The cell must be accompanied by the label 'dist', # so we need to track it down through the list 'graph' # and then copy it back to the list of successors. # The flag makeConnected is necessary to be able # the present method create_succesors() to collaborate # with the method find_connected_component(), which creates # the connected component when Dijkstra's initializes. if self.selected_algo == "Dijkstra": if make_connected: temp.append(cell) elif cell in self.graph: graph_index = self.graph.index(cell) temp.append(self.graph[graph_index]) else: # ... update the pointer of the up-side cell so it points the current one ... cell.prev = current # ... and add the up-side cell to the successors of the current one. temp.append(cell) if self.diagonal.get(): # If we are not even at the topmost nor at the rightmost border of the grid # and the up-right-side cell is not an obstacle # and one of the upper side or right side cells are not obstacles # (because it is not reasonable to allow the robot to pass through a "slot") # and (only in the case are not running the A* or Greedy) # not already belongs neither to the OPEN SET nor CLOSED SET ... if r > 0 and c < self.columns-1 and self.grid[r-1][c+1] != self.OBST and \ (self.grid[r-1][c] != self.OBST or self.grid[r][c+1] != self.OBST) and \ (self.selected_algo in ["A*", "Greedy", "Dijkstra"] or (self.selected_algo in ["DFS", "BFS"] and not self.Cell(r-1, c+1) in self.openSet and not self.Cell(r-1, c+1) in self.closedSet)): cell = self.Cell(r-1, c+1) if self.selected_algo == "Dijkstra": if make_connected: temp.append(cell) elif cell in self.graph: graph_index = self.graph.index(cell) temp.append(self.graph[graph_index]) else: # ... update the pointer of the up-right-side cell so it points the current one ... cell.prev = current # ... and add the up-right-side cell to the successors of the current one. temp.append(cell) # If not at the rightmost limit of the grid # and the right-side cell is not an obstacle ... # and (only in the case are not running the A* or Greedy) # not already belongs neither to the OPEN SET nor to the CLOSED SET ... if c < self.columns-1 and self.grid[r][c+1] != self.OBST and\ (self.selected_algo in ["A*", "Greedy", "Dijkstra"] or (self.selected_algo in ["DFS", "BFS"] and not self.Cell(r, c+1) in self.openSet and not self.Cell(r, c+1) in self.closedSet)): cell = self.Cell(r, c+1) if self.selected_algo == "Dijkstra": if make_connected: temp.append(cell) elif cell in self.graph: graph_index = self.graph.index(cell) temp.append(self.graph[graph_index]) else: # ... update the pointer of the right-side cell so it points the current one ... cell.prev = current # ... and add the right-side cell to the successors of the current one. temp.append(cell) if self.diagonal.get(): # If we are not even at the lowermost nor at the rightmost border of the grid # and the down-right-side cell is not an obstacle # and one of the down-side or right-side cells are not obstacles # and (only in the case are not running the A* or Greedy) # not already belongs neither to the OPEN SET nor to the CLOSED SET ... if r < self.rows-1 and c < self.columns-1 and self.grid[r+1][c+1] != self.OBST and \ (self.grid[r+1][c] != self.OBST or self.grid[r][c+1] != self.OBST) and \ (self.selected_algo in ["A*", "Greedy", "Dijkstra"] or (self.selected_algo in ["DFS", "BFS"] and not self.Cell(r+1, c+1) in self.openSet and not self.Cell(r+1, c+1) in self.closedSet)): cell = self.Cell(r+1, c+1) if self.selected_algo == "Dijkstra": if make_connected: temp.append(cell) elif cell in self.graph: graph_index = self.graph.index(cell) temp.append(self.graph[graph_index]) else: # ... update the pointer of the downr-right-side cell so it points the current one ... cell.prev = current # ... and add the down-right-side cell to the successors of the current one. temp.append(cell) # If not at the lowermost limit of the grid # and the down-side cell is not an obstacle # and (only in the case are not running the A* or Greedy) # not already belongs neither to the OPEN SET nor to the CLOSED SET ... if r < self.rows-1 and self.grid[r+1][c] != self.OBST and \ (self.selected_algo in ["A*", "Greedy", "Dijkstra"] or (self.selected_algo in ["DFS", "BFS"] and not self.Cell(r+1, c) in self.openSet and not self.Cell(r+1, c) in self.closedSet)): cell = self.Cell(r+1, c) if self.selected_algo == "Dijkstra": if make_connected: temp.append(cell) elif cell in self.graph: graph_index = self.graph.index(cell) temp.append(self.graph[graph_index]) else: # ... update the pointer of the down-side cell so it points the current one ... cell.prev = current # ... and add the down-side cell to the successors of the current one. temp.append(cell) if self.diagonal.get(): # If we are not even at the lowermost nor at the leftmost border of the grid # and the down-left-side cell is not an obstacle # and one of the down-side or left-side cells are not obstacles # and (only in the case are not running the A* or Greedy) # not already belongs neither to the OPEN SET nor to the CLOSED SET ... if r < self.rows-1 and c > 0 and self.grid[r+1][c-1] != self.OBST and \ (self.grid[r+1][c] != self.OBST or self.grid[r][c-1] != self.OBST) and \ (self.selected_algo in ["A*", "Greedy", "Dijkstra"] or (self.selected_algo in ["DFS", "BFS"] and not self.Cell(r+1, c-1) in self.openSet and not self.Cell(r+1, c-1) in self.closedSet)): cell = self.Cell(r+1, c-1) if self.selected_algo == "Dijkstra": if make_connected: temp.append(cell) elif cell in self.graph: graph_index = self.graph.index(cell) temp.append(self.graph[graph_index]) else: # ... update the pointer of the down-left-side cell so it points the current one ... cell.prev = current # ... and add the down-left-side cell to the successors of the current one. temp.append(cell) # If not at the leftmost limit of the grid # and the left-side cell is not an obstacle # and (only in the case are not running the A* or Greedy) # not already belongs neither to the OPEN SET nor to the CLOSED SET ... if c > 0 and self.grid[r][c-1] != self.OBST and \ (self.selected_algo in ["A*", "Greedy", "Dijkstra"] or (self.selected_algo in ["DFS", "BFS"] and not self.Cell(r, c-1) in self.openSet and not self.Cell(r, c-1) in self.closedSet)): cell = self.Cell(r, c-1) if self.selected_algo == "Dijkstra": if make_connected: temp.append(cell) elif cell in self.graph: graph_index = self.graph.index(cell) temp.append(self.graph[graph_index]) else: # ... update the pointer of the left-side cell so it points the current one ... cell.prev = current # ... and add the left-side cell to the successors of the current one. temp.append(cell) if self.diagonal.get(): # If we are not even at the topmost nor at the leftmost border of the grid # and the up-left-side cell is not an obstacle # and one of the up-side or left-side cells are not obstacles # and (only in the case are not running the A* or Greedy) # not already belongs neither to the OPEN SET nor to the CLOSED SET ... if r > 0 and c > 0 and self.grid[r-1][c-1] != self.OBST and \ (self.grid[r-1][c] != self.OBST or self.grid[r][c-1] != self.OBST) and \ (self.selected_algo in ["A*", "Greedy", "Dijkstra"] or (self.selected_algo in ["DFS", "BFS"] and not self.Cell(r-1, c-1) in self.openSet and not self.Cell(r-1, c-1) in self.closedSet)): cell = self.Cell(r-1, c-1) if self.selected_algo == "Dijkstra": if make_connected: temp.append(cell) elif cell in self.graph: graph_index = self.graph.index(cell) temp.append(self.graph[graph_index]) else: # ... update the pointer of the up-left-side cell so it points the current one ... cell.prev = current # ... and add the up-left-side cell to the successors of the current one. temp.append(cell) # When DFS algorithm is in use, cells are added one by one at the beginning of the # OPEN SET list. Because of this, we must reverse the order of successors formed, # so the successor corresponding to the highest priority, to be placed the first in the list. # For the Greedy, A* and Dijkstra's no issue, because the list is sorted # according to 'f' or 'dist' before extracting the first element of. if self.selected_algo == "DFS": return reversed(temp) else: return temp def dist_between(self, u, v): """ Returns the distance between two cells :param u: the first cell :param v: the other cell :return: the distance between the cells u and v """ dx = u.col - v.col dy = u.row - v.row if self.diagonal.get(): # with diagonal movements calculate the Euclidean distance return math.sqrt(dx*dx + dy*dy) else: # without diagonal movements calculate the Manhattan distance return abs(dx) + abs(dy) def plot_route(self): """         Calculates the path from the target to the initial position of the robot, counts the corresponding steps and measures the distance traveled. """ self.repaint() self.searching = False steps = 0 distance = 0.0 index = self.closedSet.index(self.targetPos) cur = self.closedSet[index] self.grid[cur.row][cur.col] = self.TARGET self.paint_cell(cur.row, cur.col, "GREEN") while cur != self.robotStart: steps += 1 if self.diagonal.get(): dx = cur.col - cur.prev.col dy = cur.row - cur.prev.row distance += math.sqrt(dx*dx + dy*dy) else: distance += 1 cur = cur.prev self.grid[cur.row][cur.col] = self.ROUTE self.paint_cell(cur.row, cur.col, "YELLOW") self.grid[self.robotStart.row][self.robotStart.col] = self.ROBOT self.paint_cell(self.robotStart.row, self.robotStart.col, "RED") if self.drawArrows.get(): self.draw_arrows() msg = "Nodes expanded: {0}, Steps: {1}, Distance: {2:.3f}".format(self.expanded, steps, distance) self.message.configure(text=msg) def find_connected_component(self, v): """         Appends to the list containing the nodes of the graph only         the cells belonging to the same connected component with node v. :param v: the starting node """ # This is a Breadth First Search of the graph starting from node v. stack = [v] self.graph.append(v) while stack: v = stack.pop() successors = self.create_successors(v, True) for c in successors: if c not in self.graph: stack.append(c) self.graph.append(c) def initialize_dijkstra(self): """ Initialization of Dijkstra's algorithm """ # When one thinks of Wikipedia pseudocode, observe that the # algorithm is still looking for his target while there are still # nodes in the queue Q. # Only when we run out of queue and the target has not been found, # can answer that there is no solution. # As is known, the algorithm models the problem as a connected graph # It is obvious that no solution exists only when the graph is not # connected and the target is in a different connected component # of this initial position of the robot # To be thus possible negative response from the algorithm, # should search be made ONLY in the coherent component to which the # initial position of the robot belongs. # First create the connected component # to which the initial position of the robot belongs. self.graph.clear() self.find_connected_component(self.robotStart) # Here is the initialization of Dijkstra's algorithm # 2: for each vertex v in Graph; for v in self.graph: # 3: dist[v] := infinity ; v.dist = self.INFINITY # 5: previous[v] := undefined ; v.prev = None # 8: dist[source] := 0; self.graph[self.graph.index(self.robotStart)].dist = 0 # 9: Q := the set of all nodes in Graph; # Instead of the variable Q we will use the list # 'graph' itself, which has already been initialised. # Sorts the list of nodes with respect to 'dist'. self.graph.sort(key=attrgetter("dist")) # Initializes the list of closed nodes self.closedSet.clear() def draw_arrows(self): """ Draws the arrows to predecessors """ # We draw black arrows from each open or closed state to its predecessor. for r in range(self.rows): for c in range(self.columns): tail = head = cell = self.Cell(r, c) # If the current cell is an open state, or is a closed state # but not the initial position of the robot if self.grid[r][c] in [self.FRONTIER, self.CLOSED] and not cell == self.robotStart: # The tail of the arrow is the current cell, while # the arrowhead is the predecessor cell. if self.grid[r][c] == self.FRONTIER: if self.selected_algo == "Dijkstra": tail = self.graph[self.graph.index(cell)] head = tail.prev else: tail = self.openSet[self.openSet.index(cell)] head = tail.prev elif self.grid[r][c] == self.CLOSED: tail = self.closedSet[self.closedSet.index(cell)] head = tail.prev self.draw_arrow(tail, head, self.arrow_size, "BLACK", 2 if self.square_size >= 25 else 1) if self.found: # We draw red arrows along the path from robotStart to targetPos. # index = self.closedSet.index(self.targetPos) cur = self.closedSet[self.closedSet.index(self.targetPos)] while cur != self.robotStart: head = cur cur = cur.prev tail = cur self.draw_arrow(tail, head, self.arrow_size, "RED", 2 if self.square_size >= 25 else 1) def draw_arrow(self, tail, head, a, color, width): """ Draws an arrow from center of tail cell to center of head cell :param tail: the tail of the arrow :param head: the head of the arrow :param a: size of arrow tips :param color: color of the arrow :param width: thickness of the lines """ # The coordinates of the center of the tail cell x1 = 1 + tail.col * self.square_size + self.square_size / 2 y1 = 1 + tail.row * self.square_size + self.square_size / 2 # The coordinates of the center of the head cell x2 = 1 + head.col * self.square_size + self.square_size / 2 y2 = 1 + head.row * self.square_size + self.square_size / 2 sin20 = math.sin(20*math.pi/180) cos20 = math.cos(20*math.pi/180) sin25 = math.sin(25*math.pi/180) cos25 = math.cos(25*math.pi/180) u3 = v3 = u4 = v4 = 0 if x1 == x2 and y1 > y2: # up u3 = x2 - a*sin20 v3 = y2 + a*cos20 u4 = x2 + a*sin20 v4 = v3 elif x1 < x2 and y1 > y2: # up-right u3 = x2 - a*cos25 v3 = y2 + a*sin25 u4 = x2 - a*sin25 v4 = y2 + a*cos25 elif x1 < x2 and y1 == y2: # right u3 = x2 - a*cos20 v3 = y2 - a*sin20 u4 = u3 v4 = y2 + a*sin20 elif x1 < x2 and y1 < y2: # righr-down u3 = x2 - a*cos25 v3 = y2 - a*sin25 u4 = x2 - a*sin25 v4 = y2 - a*cos25 elif x1 == x2 and y1 < y2: # down u3 = x2 - a*sin20 v3 = y2 - a*cos20 u4 = x2 + a*sin20 v4 = v3 elif x1 > x2 and y1 < y2: # left-down u3 = x2 + a*sin25 v3 = y2 - a*cos25 u4 = x2 + a*cos25 v4 = y2 - a*sin25 elif x1 > x2 and y1 == y2: # left u3 = x2 + a*cos20 v3 = y2 - a*sin20 u4 = u3 v4 = y2 + a*sin20 elif x1 > x2 and y1 > y2: # left-up u3 = x2 + a*sin25 v3 = y2 + a*cos25 u4 = x2 + a*cos25 v4 = y2 + a*sin25 self.canvas.create_line(x1, y1, x2, y2, fill=color, width=width) self.canvas.create_line(x2, y2, u3, v3, fill=color, width=width) self.canvas.create_line(x2, y2, u4, v4, fill=color, width=width) @staticmethod def center(window): """ Places a window at the center of the screen """ window.update_idletasks() w = window.winfo_screenwidth() h = window.winfo_screenheight() size = tuple(int(_) for _ in window.geometry().split('+')[0].split('x')) x = w / 2 - size[0] / 2 y = h / 2 - size[1] / 2 window.geometry("%dx%d+%d+%d" % (size + (x, y))) @staticmethod def source_code_callback(self): webbrowser.open_new(r"https://goo.gl/tRaLfe") @staticmethod def video_callback(self): webbrowser.open_new(r"https://youtu.be/7GLqy61X2oU") def on_closing(): if messagebox.askokcancel("Quit", "Do you want to quit?"): os._exit(0) if __name__ == '__main__': app = Tk() app.protocol("WM_DELETE_WINDOW", on_closing) app.title("Maze 5.1") app.geometry("693x545") app.resizable(False, False) Maze51(app) app.mainloop()
45.447702
134
0.538165
from tkinter import * from tkinter import font from tkinter import messagebox from functools import partial from operator import attrgetter import webbrowser import numpy import random import math import os class Maze51: class CreateToolTip(object): def __init__(self, widget, text='widget info'): self.waittime = 500 self.wraplength = 180 self.widget = widget self.text = text self.widget.bind("<Enter>", self.enter) self.widget.bind("<Leave>", self.leave) self.widget.bind("<ButtonPress>", self.leave) self._id = None self.tw = None def enter(self, event=None): self.schedule() def leave(self, event=None): self.unschedule() self.hidetip() def schedule(self): self.unschedule() self._id = self.widget.after(self.waittime, self.showtip) def unschedule(self): _id = self._id self._id = None if _id: self.widget.after_cancel(_id) def showtip(self, event=None): x, y, cx, cy = self.widget.bbox("insert") x += self.widget.winfo_rootx() + 25 y += self.widget.winfo_rooty() + 20 self.tw = Toplevel(self.widget) self.tw.wm_overrideredirect(True) self.tw.wm_geometry("+%d+%d" % (x, y)) label = Label(self.tw, text=self.text, justify='left', background="#ffffff", relief='solid', borderwidth=1, wraplength=self.wraplength) label.pack(ipadx=1) def hidetip(self): tw = self.tw self.tw = None if tw: tw.destroy() class MyMaze(object): def __init__(self, x_dimension, y_dimension): self.dimensionX = x_dimension self.dimensionY = y_dimension self.gridDimensionX = x_dimension * 2 + 1 self.gridDimensionY = y_dimension * 2 + 1 self.mazeGrid = [[' ' for y in range(self.gridDimensionY)] for x in range(self.gridDimensionX)] self.cells = [[self.Cell(x, y, False) for y in range(self.dimensionY)] for x in range(self.dimensionX)] self.generate_maze() self.update_grid() class Cell(object): def __init__(self, x, y, is_wall=True): self.neighbors = [] self.open = True self.x = x self.y = y self.wall = is_wall def add_neighbor(self, other): if other not in self.neighbors: self.neighbors.append(other) if self not in other.neighbors: other.neighbors.append(self) def is_cell_below_neighbor(self): return self.__class__(self.x, self.y + 1) in self.neighbors def is_cell_right_neighbor(self): return self.__class__(self.x + 1, self.y) in self.neighbors def __eq__(self, other): if isinstance(other, self.__class__): return self.x == other.x and self.y == other.y else: return False def generate_maze(self): start_at = self.get_cell(0, 0) start_at.open = False cells = [start_at] while cells: if random.randint(0, 9) == 0: cell = cells.pop(random.randint(0, cells.__len__()) - 1) else: cell = cells.pop(cells.__len__() - 1) neighbors = [] potential_neighbors = [self.get_cell(cell.x + 1, cell.y), self.get_cell(cell.x, cell.y + 1), self.get_cell(cell.x - 1, cell.y), self.get_cell(cell.x, cell.y - 1)] for other in potential_neighbors: if other is None or other.wall or not other.open: continue neighbors.append(other) if not neighbors: continue selected = neighbors[random.randint(0, neighbors.__len__()) - 1] selected.open = False cell.add_neighbor(selected) cells.append(cell) cells.append(selected) def get_cell(self, x, y): if x < 0 or y < 0: return None try: return self.cells[x][y] except IndexError: return None def update_grid(self): back_char = ' ' wall_char = 'X' cell_char = ' ' for x in range(self.gridDimensionX): for y in range(self.gridDimensionY): self.mazeGrid[x][y] = back_char for x in range(self.gridDimensionX): for y in range(self.gridDimensionY): if x % 2 == 0 or y % 2 == 0: self.mazeGrid[x][y] = wall_char for x in range(self.dimensionX): for y in range(self.dimensionY): current = self.get_cell(x, y) grid_x = x * 2 + 1 grid_y = y * 2 + 1 self.mazeGrid[grid_x][grid_y] = cell_char if current.is_cell_below_neighbor(): self.mazeGrid[grid_x][grid_y + 1] = cell_char if current.is_cell_right_neighbor(): self.mazeGrid[grid_x + 1][grid_y] = cell_char class Cell(object): def __init__(self, row, col): self.row = row self.col = col self.g = 0 self.h = 0 self.f = 0 self.dist = 0 # Each state corresponds to a cell # and each state has a predecessor which # stored in this variable self.prev = self.__class__ def __eq__(self, other): if isinstance(other, self.__class__): return self.row == other.row and self.col == other.col else: return False ####################################### # # # Constants of Maze42 class # # # ####################################### INFINITY = sys.maxsize # The representation of the infinite EMPTY = 0 # empty cell OBST = 1 # cell with obstacle ROBOT = 2 # the position of the robot TARGET = 3 # the position of the target FRONTIER = 4 # cells that form the frontier (OPEN SET) CLOSED = 5 # cells that form the CLOSED SET ROUTE = 6 # cells that form the robot-to-target path MSG_DRAW_AND_SELECT = "\"Paint\" obstacles, then click 'Real-Time' or 'Step-by-Step' or 'Animation'" MSG_SELECT_STEP_BY_STEP_ETC = "Click 'Step-by-Step' or 'Animation' or 'Clear'" MSG_NO_SOLUTION = "There is no path to the target !!!" def __init__(self, maze): self.center(maze) self.rows = 41 # the number of rows of the grid self.columns = 41 # the number of columns of the grid self.square_size = int(500/self.rows) # the cell size in pixels self.arrow_size = int(self.square_size/2) # the size of the tips of the arrow pointing the predecessor cell self.openSet = [] # the OPEN SET self.closedSet = [] # the CLOSED SET self.graph = [] # the set of vertices of the graph to be explored by Dijkstra's algorithm self.robotStart = self.Cell(self.rows - 2, 1) self.targetPos = self.Cell(1, self.columns - 2) self.grid = [[]] self.realTime = False self.found = False self.searching = False self.endOfSearch = False self.animation = False self.delay = 500 self.expanded = 0 self.selected_algo = "DFS" self.array = numpy.array([0] * (83 * 83)) self.cur_row = self.cur_col = self.cur_val = 0 app_highlight_font = font.Font(app, family='Helvetica', size=10, weight='bold') "Position of obstacles, robot and target can be changed when search is underway", "The search is performed step-by-step for every click", "The search is performed automatically") for i, action in enumerate(("New grid", "Maze", "Clear", "Real-Time", "Step-by-Step", "Animation")): btn = Button(app, text=action, width=20, font=app_highlight_font, bg="light grey", command=partial(self.select_action, action)) btn.place(x=515, y=65+30*i) self.CreateToolTip(btn, buttons_tool_tips[i]) self.buttons.append(btn) time_delay = Label(app, text="Delay (msec)", width=27, anchor='center', font=("Helvetica", 8)) time_delay.place(x=515, y=243) slider_value = IntVar() slider_value.set(500) self.slider = Scale(app, orient=HORIZONTAL, length=165, width=10, from_=0, to=1000, showvalue=1, variable=slider_value,) self.slider.place(x=515, y=260) self.CreateToolTip(self.slider, "Regulates the delay for each step (0 to 1000 msec)") self.frame = LabelFrame(app, text="Algorithms", width=170, height=100) self.frame.place(x=515, y=300) self.radio_buttons = list() radio_buttons_tool_tips = ("Depth First Search algorithm", "Breadth First Search algorithm", "A* algorithm", "Greedy search algorithm", "Dijkstra's algorithm") for i, algorithm in enumerate(("DFS", "BFS", "A*", "Greedy", "Dijkstra")): btn = Radiobutton(self.frame, text=algorithm, font=app_highlight_font, value=i + 1, command=partial(self.select_algo, algorithm)) btn.place(x=10 if i % 2 == 0 else 90, y=int(i/2)*25) self.CreateToolTip(btn, radio_buttons_tool_tips[i]) btn.deselect() self.radio_buttons.append(btn) self.radio_buttons[0].select() self.diagonal = IntVar() self.diagonalBtn = Checkbutton(app, text="Diagonal movements", font=app_highlight_font, variable=self.diagonal) self.diagonalBtn.place(x=515, y=405) self.CreateToolTip(self.diagonalBtn, "Diagonal movements are also allowed") self.drawArrows = IntVar() self.drawArrowsBtn = Checkbutton(app, text="Arrows to predecessors", font=app_highlight_font, variable=self.drawArrows) self.drawArrowsBtn.place(x=515, y=430) self.CreateToolTip(self.drawArrowsBtn, "Draw arrows to predecessors") memo_colors = ("RED", "GREEN", "BLUE", "CYAN") for i, memo in enumerate(("Robot", "Target", "Frontier", "Closed set")): label = Label(app, text=memo, width=8, anchor='center', fg=memo_colors[i], font=("Helvetica", 11)) label.place(x=515 if i % 2 == 0 else 605, y=460+int(i/2)*20) self.about_button = Button(app, text='About Maze', width=20, font=app_highlight_font, bg="light grey", command=self.about_click) self.about_button.place(x=515, y=505) self.canvas = Canvas(app, bd=0, highlightthickness=0) self.canvas.bind("<Button-1>", self.left_click) self.canvas.bind("<B1-Motion>", self.drag) self.initialize_grid(False) def validate_rows(self, entry): try: value = int(entry) valid = value in range(5, 84) except ValueError: valid = False if not valid: app.bell() # The following line is due to user PRMoureu of stackoverflow. See: # https://stackoverflow.com/questions/46861236/widget-validation-in-tkinter/46863849?noredirect=1#comment80675412_46863849 self.rowsSpinner.after_idle(lambda: self.rowsSpinner.config(validate='focusout')) return valid def invalid_rows(self): self.rows_var.set(41) def validate_cols(self, entry): try: value = int(entry) valid = value in range(5, 84) except ValueError: valid = False if not valid: app.bell() self.colsSpinner.after_idle(lambda: self.colsSpinner.config(validate='focusout')) return valid def invalid_cols(self): self.cols_var.set(41) def select_action(self, action): if action == "New grid": self.reset_click() elif action == "Maze": self.maze_click() elif action == "Clear": self.clear_click() elif action == "Real-Time": self.real_time_click() elif action == "Step-by-Step": self.step_by_step_click() elif action == "Animation": self.animation_click() def select_algo(self, algorithm): self.selected_algo = algorithm def left_click(self, event): row = int(event.y/self.square_size) col = int(event.x/self.square_size) if row in range(self.rows) and col in range(self.columns): if True if self.realTime else (not self.found and not self.searching): if self.realTime: self.fill_grid() self.cur_row = row self.cur_col = col self.cur_val = self.grid[row][col] if self.cur_val == self.EMPTY: self.grid[row][col] = self.OBST self.paint_cell(row, col, "BLACK") if self.cur_val == self.OBST: self.grid[row][col] = self.EMPTY self.paint_cell(row, col, "WHITE") if self.realTime and self.selected_algo == "Dijkstra": self.initialize_dijkstra() if self.realTime: self.real_Time_action() def drag(self, event): row = int(event.y/self.square_size) col = int(event.x/self.square_size) if row in range(self.rows) and col in range(self.columns): if True if self.realTime else (not self.found and not self.searching): if self.realTime: self.fill_grid() if self.Cell(row, col) != self.Cell(self.cur_row, self.cur_col) and\ self.cur_val in [self.ROBOT, self.TARGET]: new_val = self.grid[row][col] if new_val == self.EMPTY: self.grid[row][col] = self.cur_val if self.cur_val == self.ROBOT: self.grid[self.robotStart.row][self.robotStart.col] = self.EMPTY self.paint_cell(self.robotStart.row, self.robotStart.col, "WHITE") self.robotStart.row = row self.robotStart.col = col self.grid[self.robotStart.row][self.robotStart.col] = self.ROBOT self.paint_cell(self.robotStart.row, self.robotStart.col, "RED") else: self.grid[self.targetPos.row][self.targetPos.col] = self.EMPTY self.paint_cell(self.targetPos.row, self.targetPos.col, "WHITE") self.targetPos.row = row self.targetPos.col = col self.grid[self.targetPos.row][self.targetPos.col] = self.TARGET self.paint_cell(self.targetPos.row, self.targetPos.col, "GREEN") self.cur_row = row self.cur_col = col self.cur_val = self.grid[row][col] elif self.grid[row][col] != self.ROBOT and self.grid[row][col] != self.TARGET: self.grid[row][col] = self.OBST self.paint_cell(row, col, "BLACK") if self.realTime and self.selected_algo == "Dijkstra": self.initialize_dijkstra() if self.realTime: self.real_Time_action() def initialize_grid(self, make_maze): self.rows = int(self.rowsSpinner.get()) self.columns = int(self.colsSpinner.get()) if make_maze and self.rows % 2 == 0: self.rows -= 1 if make_maze and self.columns % 2 == 0: self.columns -= 1 self.square_size = int(500/(self.rows if self.rows > self.columns else self.columns)) self.arrow_size = int(self.square_size/2) self.grid = self.array[:self.rows*self.columns] self.grid = self.grid.reshape(self.rows, self.columns) self.canvas.configure(width=self.columns*self.square_size+1, height=self.rows*self.square_size+1) self.canvas.place(x=10, y=10) self.canvas.create_rectangle(0, 0, self.columns*self.square_size+1, self.rows*self.square_size+1, width=0, fill="DARK GREY") for r in list(range(self.rows)): for c in list(range(self.columns)): self.grid[r][c] = self.EMPTY self.robotStart = self.Cell(self.rows-2, 1) self.targetPos = self.Cell(1, self.columns-2) self.fill_grid() if make_maze: maze = self.MyMaze(int(self.rows/2), int(self.columns/2)) for x in range(maze.gridDimensionX): for y in range(maze.gridDimensionY): if maze.mazeGrid[x][y] == 'X': # maze.wall_char: self.grid[x][y] = self.OBST self.repaint() def fill_grid(self): # With the first click on button 'Clear' clears the data # of any search was performed (Frontier, Closed Set, Route) # and leaves intact the obstacles and the robot and target positions # in order to be able to run another algorithm # with the same data. # With the second click removes any obstacles also. if self.searching or self.endOfSearch: for r in list(range(self.rows)): for c in list(range(self.columns)): if self.grid[r][c] in [self.FRONTIER, self.CLOSED, self.ROUTE]: self.grid[r][c] = self.EMPTY if self.grid[r][c] == self.ROBOT: self.robotStart = self.Cell(r, c) self.searching = False else: for r in list(range(self.rows)): for c in list(range(self.columns)): self.grid[r][c] = self.EMPTY self.robotStart = self.Cell(self.rows-2, 1) self.targetPos = self.Cell(1, self.columns-2) if self.selected_algo in ["A*", "Greedy"]: self.robotStart.g = 0 self.robotStart.h = 0 self.robotStart.f = 0 self.expanded = 0 self.found = False self.searching = False self.endOfSearch = False self.openSet.clear() self.closedSet.clear() self.openSet = [self.robotStart] self.closedSet = [] self.grid[self.targetPos.row][self.targetPos.col] = self.TARGET self.grid[self.robotStart.row][self.robotStart.col] = self.ROBOT self.message.configure(text=self.MSG_DRAW_AND_SELECT) self.repaint() def repaint(self): color = "" for r in list(range(self.rows)): for c in list(range(self.columns)): if self.grid[r][c] == self.EMPTY: color = "WHITE" elif self.grid[r][c] == self.ROBOT: color = "RED" elif self.grid[r][c] == self.TARGET: color = "GREEN" elif self.grid[r][c] == self.OBST: color = "BLACK" elif self.grid[r][c] == self.FRONTIER: color = "BLUE" elif self.grid[r][c] == self.CLOSED: color = "CYAN" elif self.grid[r][c] == self.ROUTE: color = "YELLOW" self.paint_cell(r, c, color) def paint_cell(self, row, col, color): self.canvas.create_rectangle(1 + col * self.square_size, 1 + row * self.square_size, 1 + (col + 1) * self.square_size - 1, 1 + (row + 1) * self.square_size - 1, width=0, fill=color) def reset_click(self): self.animation = False self.realTime = False for but in self.buttons: but.configure(state="normal") self.buttons[3].configure(fg="BLACK") # Real-Time button self.slider.configure(state="normal") for but in self.radio_buttons: but.configure(state="normal") self.diagonalBtn.configure(state="normal") self.drawArrowsBtn.configure(state="normal") self.initialize_grid(False) def maze_click(self): self.animation = False self.realTime = False for but in self.buttons: but.configure(state="normal") self.buttons[3].configure(fg="BLACK") # Real-Time button self.slider.configure(state="normal") for but in self.radio_buttons: but.configure(state="normal") self.diagonalBtn.configure(state="normal") self.drawArrowsBtn.configure(state="normal") self.initialize_grid(True) def clear_click(self): self.animation = False self.realTime = False for but in self.buttons: but.configure(state="normal") self.buttons[3].configure(fg="BLACK") # Real-Time button self.slider.configure(state="normal") for but in self.radio_buttons: but.configure(state="normal") self.diagonalBtn.configure(state="normal") self.drawArrowsBtn.configure(state="normal") self.fill_grid() def real_time_click(self): if self.realTime: return self.realTime = True self.searching = True # The Dijkstra's initialization should be done just before the if self.selected_algo == "Dijkstra": self.initialize_dijkstra() self.buttons[3].configure(fg="RED") self.slider.configure(state="disabled") for but in self.radio_buttons: but.configure(state="disabled") self.diagonalBtn.configure(state="disabled") self.drawArrowsBtn.configure(state="disabled") self.real_Time_action() def real_Time_action(self): while not self.endOfSearch: self.check_termination() def step_by_step_click(self): if self.found or self.endOfSearch: return if not self.searching and self.selected_algo == "Dijkstra": self.initialize_dijkstra() self.animation = False self.searching = True self.message.configure(text=self.MSG_SELECT_STEP_BY_STEP_ETC) self.buttons[3].configure(state="disabled") for but in self.radio_buttons: but.configure(state="disabled") self.diagonalBtn.configure(state="disabled") self.drawArrowsBtn.configure(state="disabled") self.check_termination() def animation_click(self): self.animation = True if not self.searching and self.selected_algo == "Dijkstra": self.initialize_dijkstra() self.searching = True self.message.configure(text=self.MSG_SELECT_STEP_BY_STEP_ETC) self.buttons[3].configure(state="disabled") for but in self.radio_buttons: but.configure(state="disabled") self.diagonalBtn.configure(state="disabled") self.drawArrowsBtn.configure(state="disabled") self.delay = self.slider.get() self.animation_action() def animation_action(self): if self.animation: self.check_termination() if self.endOfSearch: return self.canvas.after(self.delay, self.animation_action) def about_click(self): about_box = Toplevel(master=app) about_box.title("") about_box.geometry("340x160") about_box.resizable(False, False) self.center(about_box) about_box.transient(app) about_box.grab_set() title = Label(about_box, text="Maze", width=20, anchor='center', fg='SANDY BROWN', font=("Helvetica", 20)) title.place(x=0, y=0) version = Label(about_box, text="Version: 5.1", width=35, anchor='center', font=("Helvetica", 11, 'bold')) version.place(x=0, y=35) programmer = Label(about_box, text="Designer: Nikos Kanargias", width=35, anchor='center', font=("Helvetica", 12)) programmer.place(x=0, y=60) email = Label(about_box, text="E-mail: nkana@tee.gr", width=40, anchor='center', font=("Helvetica", 10)) email.place(x=0, y=80) source_code = Label(about_box, text="Code and documentation", fg="blue", cursor="hand2", width=35, anchor='center', font=("Helvetica", 12)) f = font.Font(source_code, source_code.cget("font")) f.configure(underline=True) source_code.configure(font=f) source_code.place(x=0, y=100) source_code.bind("<Button-1>", self.source_code_callback) self.CreateToolTip(source_code, "Click this link to retrieve code and documentation from DropBox") video = Label(about_box, text="Watch demo video on YouTube", fg="blue", cursor="hand2", width=35, anchor='center') video.configure(font=f) video.place(x=0, y=125) video.bind("<Button-1>", self.video_callback) self.CreateToolTip(video, "Click this link to watch a demo video on YouTube") def check_termination(self): if (self.selected_algo == "Dijkstra" and not self.graph) or\ self.selected_algo != "Dijkstra" and not self.openSet: self.endOfSearch = True self.grid[self.robotStart.row][self.robotStart.col] = self.ROBOT self.message.configure(text=self.MSG_NO_SOLUTION) self.buttons[4].configure(state="disabled") self.buttons[5].configure(state="disabled") self.slider.configure(state="disabled") self.repaint() if self.drawArrows.get(): self.draw_arrows() else: self.expand_node() if self.found: self.endOfSearch = True self.plot_route() self.buttons[4].configure(state="disabled") self.buttons[5].configure(state="disabled") self.slider.configure(state="disabled") def expand_node(self): if self.selected_algo == "Dijkstra": # 11: while Q is not empty: if not self.graph: return # 12: u := vertex in Q (graph) with smallest distance in dist[] ; # 13: remove u from Q (graph); u = self.graph.pop(0) # Add vertex u in closed set self.closedSet.append(u) # If target has been found ... if u == self.targetPos: self.found = True return # Counts nodes that have expanded. self.expanded += 1 # Update the color of the cell self.grid[u.row][u.col] = self.CLOSED # paint the cell self.paint_cell(u.row, u.col, "CYAN") # 14: if dist[u] = infinity: if u.dist == self.INFINITY: # ... then there is no solution. # 15: break; return # 16: end if # Create the neighbors of u neighbors = self.create_successors(u, False) # 18: for each neighbor v of u: for v in neighbors: # 20: alt := dist[u] + dist_between(u, v) ; alt = u.dist + self.dist_between(u, v) # 21: if alt < dist[v]: if alt < v.dist: # 22: dist[v] := alt ; v.dist = alt # 23: previous[v] := u ; v.prev = u # Update the color of the cell self.grid[v.row][v.col] = self.FRONTIER # paint the cell self.paint_cell(v.row, v.col, "BLUE") # 24: decrease-key v in Q; # (sort list of nodes with respect to dist) self.graph.sort(key=attrgetter("dist")) # The handling of the other four algorithms else: if self.selected_algo in ["DFS", "BFS"]: # Here is the 3rd step of the algorithms DFS and BFS # 3. Remove the first state, Si, from OPEN SET ... current = self.openSet.pop(0) else: # Here is the 3rd step of the algorithms A* and Greedy # 3. Remove the first state, Si, from OPEN SET, # for which f(Si) ≤ f(Sj) for all other # open states Sj ... # (sort first OPEN SET list with respect to 'f') self.openSet.sort(key=attrgetter("f")) current = self.openSet.pop(0) # ... and add it to CLOSED SET. self.closedSet.insert(0, current) # Update the color of the cell self.grid[current.row][current.col] = self.CLOSED # paint the cell self.paint_cell(current.row, current.col, "CYAN") # If the selected node is the target ... if current == self.targetPos: # ... then terminate etc last = self.targetPos last.prev = current.prev self.closedSet.append(last) self.found = True return # Count nodes that have been expanded. self.expanded += 1 # Here is the 4rd step of the algorithms # 4. Create the successors of Si, based on actions # that can be implemented on Si. # Each successor has a pointer to the Si, as its predecessor. # In the case of DFS and BFS algorithms, successors should not # belong neither to the OPEN SET nor the CLOSED SET. successors = self.create_successors(current, False) # Here is the 5th step of the algorithms # 5. For each successor of Si, ... for cell in successors: # ... if we are running DFS ... if self.selected_algo == "DFS": # ... add the successor at the beginning of the list OPEN SET self.openSet.insert(0, cell) # Update the color of the cell self.grid[cell.row][cell.col] = self.FRONTIER # paint the cell self.paint_cell(cell.row, cell.col, "BLUE") # ... if we are runnig BFS ... elif self.selected_algo == "BFS": # ... add the successor at the end of the list OPEN SET self.openSet.append(cell) # Update the color of the cell self.grid[cell.row][cell.col] = self.FRONTIER # paint the cell self.paint_cell(cell.row, cell.col, "BLUE") # ... if we are running A* or Greedy algorithms (step 5 of A* algorithm) ... elif self.selected_algo in ["A*", "Greedy"]: # ... calculate the value f(Sj) ... dxg = current.col - cell.col dyg = current.row - cell.row dxh = self.targetPos.col - cell.col dyh = self.targetPos.row - cell.row if self.diagonal.get(): # with diagonal movements, calculate the Euclidean distance if self.selected_algo == "Greedy": # especially for the Greedy ... cell.g = 0 else: cell.g = current.g + math.sqrt(dxg*dxg + dyg*dyg) cell.h = math.sqrt(dxh*dxh + dyh*dyh) else: # without diagonal movements, calculate the Manhattan distance if self.selected_algo == "Greedy": # especially for the Greedy ... cell.g = 0 else: cell.g = current.g + abs(dxg) + abs(dyg) cell.h = abs(dxh) + abs(dyh) cell.f = cell.g+cell.h # ... If Sj is neither in the OPEN SET nor in the CLOSED SET states ... if cell not in self.openSet and cell not in self.closedSet: # ... then add Sj in the OPEN SET ... # ... evaluated as f(Sj) self.openSet.append(cell) # Update the color of the cell self.grid[cell.row][cell.col] = self.FRONTIER # paint the cell self.paint_cell(cell.row, cell.col, "BLUE") # Else ... else: # ... if already belongs to the OPEN SET, then ... if cell in self.openSet: open_index = self.openSet.index(cell) # ... compare the new value assessment with the old one. # If old <= new ... if self.openSet[open_index].f <= cell.f: # ... then eject the new node with state Sj. # (ie do nothing for this node). pass # Else, ... else: # ... remove the element (Sj, old) from the list # to which it belongs ... self.openSet.pop(open_index) # ... and add the item (Sj, new) to the OPEN SET. self.openSet.append(cell) # Update the color of the cell self.grid[cell.row][cell.col] = self.FRONTIER # paint the cell self.paint_cell(cell.row, cell.col, "BLUE") # ... if already belongs to the CLOSED SET, then ... elif cell in self.closedSet: closed_index = self.closedSet.index(cell) # ... compare the new value assessment with the old one. # If old <= new ... if self.closedSet[closed_index].f <= cell.f: # ... then eject the new node with state Sj. # (ie do nothing for this node). pass # Else, ... else: # ... remove the element (Sj, old) from the list # to which it belongs ... self.closedSet.pop(closed_index) # ... and add the item (Sj, new) to the OPEN SET. self.openSet.append(cell) # Update the color of the cell self.grid[cell.row][cell.col] = self.FRONTIER # paint the cell self.paint_cell(cell.row, cell.col, "BLUE") def create_successors(self, current, make_connected): r = current.row c = current.col # We create an empty list for the successors of the current cell. temp = [] # With diagonal movements priority is: # 1: Up 2: Up-right 3: Right 4: Down-right # 5: Down 6: Down-left 7: Left 8: Up-left # Without diagonal movements the priority is: # 1: Up 2: Right 3: Down 4: Left # If not at the topmost limit of the grid # and the up-side cell is not an obstacle # and (only in the case are not running the A* or Greedy) # not already belongs neither to the OPEN SET nor to the CLOSED SET ... if r > 0 and self.grid[r-1][c] != self.OBST and\ (self.selected_algo in ["A*", "Greedy", "Dijkstra"] or (self.selected_algo in ["DFS", "BFS"] and not self.Cell(r-1, c) in self.openSet and not self.Cell(r-1, c) in self.closedSet)): cell = self.Cell(r-1, c) # In the case of Dijkstra's algorithm we can not append to if self.selected_algo == "Dijkstra": if make_connected: temp.append(cell) elif cell in self.graph: graph_index = self.graph.index(cell) temp.append(self.graph[graph_index]) else: # ... update the pointer of the up-side cell so it points the current one ... cell.prev = current # ... and add the up-side cell to the successors of the current one. temp.append(cell) if self.diagonal.get(): # If we are not even at the topmost nor at the rightmost border of the grid # and the up-right-side cell is not an obstacle # and one of the upper side or right side cells are not obstacles # (because it is not reasonable to allow the robot to pass through a "slot") # and (only in the case are not running the A* or Greedy) # not already belongs neither to the OPEN SET nor CLOSED SET ... if r > 0 and c < self.columns-1 and self.grid[r-1][c+1] != self.OBST and \ (self.grid[r-1][c] != self.OBST or self.grid[r][c+1] != self.OBST) and \ (self.selected_algo in ["A*", "Greedy", "Dijkstra"] or (self.selected_algo in ["DFS", "BFS"] and not self.Cell(r-1, c+1) in self.openSet and not self.Cell(r-1, c+1) in self.closedSet)): cell = self.Cell(r-1, c+1) if self.selected_algo == "Dijkstra": if make_connected: temp.append(cell) elif cell in self.graph: graph_index = self.graph.index(cell) temp.append(self.graph[graph_index]) else: # ... update the pointer of the up-right-side cell so it points the current one ... cell.prev = current # ... and add the up-right-side cell to the successors of the current one. temp.append(cell) # If not at the rightmost limit of the grid # and the right-side cell is not an obstacle ... # and (only in the case are not running the A* or Greedy) # not already belongs neither to the OPEN SET nor to the CLOSED SET ... if c < self.columns-1 and self.grid[r][c+1] != self.OBST and\ (self.selected_algo in ["A*", "Greedy", "Dijkstra"] or (self.selected_algo in ["DFS", "BFS"] and not self.Cell(r, c+1) in self.openSet and not self.Cell(r, c+1) in self.closedSet)): cell = self.Cell(r, c+1) if self.selected_algo == "Dijkstra": if make_connected: temp.append(cell) elif cell in self.graph: graph_index = self.graph.index(cell) temp.append(self.graph[graph_index]) else: # ... update the pointer of the right-side cell so it points the current one ... cell.prev = current # ... and add the right-side cell to the successors of the current one. temp.append(cell) if self.diagonal.get(): # If we are not even at the lowermost nor at the rightmost border of the grid # and the down-right-side cell is not an obstacle # and one of the down-side or right-side cells are not obstacles # and (only in the case are not running the A* or Greedy) # not already belongs neither to the OPEN SET nor to the CLOSED SET ... if r < self.rows-1 and c < self.columns-1 and self.grid[r+1][c+1] != self.OBST and \ (self.grid[r+1][c] != self.OBST or self.grid[r][c+1] != self.OBST) and \ (self.selected_algo in ["A*", "Greedy", "Dijkstra"] or (self.selected_algo in ["DFS", "BFS"] and not self.Cell(r+1, c+1) in self.openSet and not self.Cell(r+1, c+1) in self.closedSet)): cell = self.Cell(r+1, c+1) if self.selected_algo == "Dijkstra": if make_connected: temp.append(cell) elif cell in self.graph: graph_index = self.graph.index(cell) temp.append(self.graph[graph_index]) else: # ... update the pointer of the downr-right-side cell so it points the current one ... cell.prev = current # ... and add the down-right-side cell to the successors of the current one. temp.append(cell) # If not at the lowermost limit of the grid # and the down-side cell is not an obstacle # and (only in the case are not running the A* or Greedy) # not already belongs neither to the OPEN SET nor to the CLOSED SET ... if r < self.rows-1 and self.grid[r+1][c] != self.OBST and \ (self.selected_algo in ["A*", "Greedy", "Dijkstra"] or (self.selected_algo in ["DFS", "BFS"] and not self.Cell(r+1, c) in self.openSet and not self.Cell(r+1, c) in self.closedSet)): cell = self.Cell(r+1, c) if self.selected_algo == "Dijkstra": if make_connected: temp.append(cell) elif cell in self.graph: graph_index = self.graph.index(cell) temp.append(self.graph[graph_index]) else: # ... update the pointer of the down-side cell so it points the current one ... cell.prev = current # ... and add the down-side cell to the successors of the current one. temp.append(cell) if self.diagonal.get(): # If we are not even at the lowermost nor at the leftmost border of the grid # and the down-left-side cell is not an obstacle # and one of the down-side or left-side cells are not obstacles # and (only in the case are not running the A* or Greedy) # not already belongs neither to the OPEN SET nor to the CLOSED SET ... if r < self.rows-1 and c > 0 and self.grid[r+1][c-1] != self.OBST and \ (self.grid[r+1][c] != self.OBST or self.grid[r][c-1] != self.OBST) and \ (self.selected_algo in ["A*", "Greedy", "Dijkstra"] or (self.selected_algo in ["DFS", "BFS"] and not self.Cell(r+1, c-1) in self.openSet and not self.Cell(r+1, c-1) in self.closedSet)): cell = self.Cell(r+1, c-1) if self.selected_algo == "Dijkstra": if make_connected: temp.append(cell) elif cell in self.graph: graph_index = self.graph.index(cell) temp.append(self.graph[graph_index]) else: # ... update the pointer of the down-left-side cell so it points the current one ... cell.prev = current # ... and add the down-left-side cell to the successors of the current one. temp.append(cell) # If not at the leftmost limit of the grid # and the left-side cell is not an obstacle # and (only in the case are not running the A* or Greedy) # not already belongs neither to the OPEN SET nor to the CLOSED SET ... if c > 0 and self.grid[r][c-1] != self.OBST and \ (self.selected_algo in ["A*", "Greedy", "Dijkstra"] or (self.selected_algo in ["DFS", "BFS"] and not self.Cell(r, c-1) in self.openSet and not self.Cell(r, c-1) in self.closedSet)): cell = self.Cell(r, c-1) if self.selected_algo == "Dijkstra": if make_connected: temp.append(cell) elif cell in self.graph: graph_index = self.graph.index(cell) temp.append(self.graph[graph_index]) else: # ... update the pointer of the left-side cell so it points the current one ... cell.prev = current # ... and add the left-side cell to the successors of the current one. temp.append(cell) if self.diagonal.get(): # If we are not even at the topmost nor at the leftmost border of the grid # and the up-left-side cell is not an obstacle # and one of the up-side or left-side cells are not obstacles # and (only in the case are not running the A* or Greedy) # not already belongs neither to the OPEN SET nor to the CLOSED SET ... if r > 0 and c > 0 and self.grid[r-1][c-1] != self.OBST and \ (self.grid[r-1][c] != self.OBST or self.grid[r][c-1] != self.OBST) and \ (self.selected_algo in ["A*", "Greedy", "Dijkstra"] or (self.selected_algo in ["DFS", "BFS"] and not self.Cell(r-1, c-1) in self.openSet and not self.Cell(r-1, c-1) in self.closedSet)): cell = self.Cell(r-1, c-1) if self.selected_algo == "Dijkstra": if make_connected: temp.append(cell) elif cell in self.graph: graph_index = self.graph.index(cell) temp.append(self.graph[graph_index]) else: # ... update the pointer of the up-left-side cell so it points the current one ... cell.prev = current # ... and add the up-left-side cell to the successors of the current one. temp.append(cell) # When DFS algorithm is in use, cells are added one by one at the beginning of the # OPEN SET list. Because of this, we must reverse the order of successors formed, # so the successor corresponding to the highest priority, to be placed the first in the list. # For the Greedy, A* and Dijkstra's no issue, because the list is sorted if self.selected_algo == "DFS": return reversed(temp) else: return temp def dist_between(self, u, v): dx = u.col - v.col dy = u.row - v.row if self.diagonal.get(): return math.sqrt(dx*dx + dy*dy) else: return abs(dx) + abs(dy) def plot_route(self): self.repaint() self.searching = False steps = 0 distance = 0.0 index = self.closedSet.index(self.targetPos) cur = self.closedSet[index] self.grid[cur.row][cur.col] = self.TARGET self.paint_cell(cur.row, cur.col, "GREEN") while cur != self.robotStart: steps += 1 if self.diagonal.get(): dx = cur.col - cur.prev.col dy = cur.row - cur.prev.row distance += math.sqrt(dx*dx + dy*dy) else: distance += 1 cur = cur.prev self.grid[cur.row][cur.col] = self.ROUTE self.paint_cell(cur.row, cur.col, "YELLOW") self.grid[self.robotStart.row][self.robotStart.col] = self.ROBOT self.paint_cell(self.robotStart.row, self.robotStart.col, "RED") if self.drawArrows.get(): self.draw_arrows() msg = "Nodes expanded: {0}, Steps: {1}, Distance: {2:.3f}".format(self.expanded, steps, distance) self.message.configure(text=msg) def find_connected_component(self, v): stack = [v] self.graph.append(v) while stack: v = stack.pop() successors = self.create_successors(v, True) for c in successors: if c not in self.graph: stack.append(c) self.graph.append(c) def initialize_dijkstra(self): self.graph.clear() self.find_connected_component(self.robotStart) # 2: for each vertex v in Graph; for v in self.graph: # 3: dist[v] := infinity ; v.dist = self.INFINITY # 5: previous[v] := undefined ; v.prev = None # 8: dist[source] := 0; self.graph[self.graph.index(self.robotStart)].dist = 0 # 9: Q := the set of all nodes in Graph; # Instead of the variable Q we will use the list # 'graph' itself, which has already been initialised. # Sorts the list of nodes with respect to 'dist'. self.graph.sort(key=attrgetter("dist")) # Initializes the list of closed nodes self.closedSet.clear() def draw_arrows(self): # We draw black arrows from each open or closed state to its predecessor. for r in range(self.rows): for c in range(self.columns): tail = head = cell = self.Cell(r, c) # If the current cell is an open state, or is a closed state # but not the initial position of the robot if self.grid[r][c] in [self.FRONTIER, self.CLOSED] and not cell == self.robotStart: # The tail of the arrow is the current cell, while # the arrowhead is the predecessor cell. if self.grid[r][c] == self.FRONTIER: if self.selected_algo == "Dijkstra": tail = self.graph[self.graph.index(cell)] head = tail.prev else: tail = self.openSet[self.openSet.index(cell)] head = tail.prev elif self.grid[r][c] == self.CLOSED: tail = self.closedSet[self.closedSet.index(cell)] head = tail.prev self.draw_arrow(tail, head, self.arrow_size, "BLACK", 2 if self.square_size >= 25 else 1) if self.found: # We draw red arrows along the path from robotStart to targetPos. # index = self.closedSet.index(self.targetPos) cur = self.closedSet[self.closedSet.index(self.targetPos)] while cur != self.robotStart: head = cur cur = cur.prev tail = cur self.draw_arrow(tail, head, self.arrow_size, "RED", 2 if self.square_size >= 25 else 1) def draw_arrow(self, tail, head, a, color, width): # The coordinates of the center of the tail cell x1 = 1 + tail.col * self.square_size + self.square_size / 2 y1 = 1 + tail.row * self.square_size + self.square_size / 2 # The coordinates of the center of the head cell x2 = 1 + head.col * self.square_size + self.square_size / 2 y2 = 1 + head.row * self.square_size + self.square_size / 2 sin20 = math.sin(20*math.pi/180) cos20 = math.cos(20*math.pi/180) sin25 = math.sin(25*math.pi/180) cos25 = math.cos(25*math.pi/180) u3 = v3 = u4 = v4 = 0 if x1 == x2 and y1 > y2: # up u3 = x2 - a*sin20 v3 = y2 + a*cos20 u4 = x2 + a*sin20 v4 = v3 elif x1 < x2 and y1 > y2: # up-right u3 = x2 - a*cos25 v3 = y2 + a*sin25 u4 = x2 - a*sin25 v4 = y2 + a*cos25 elif x1 < x2 and y1 == y2: # right u3 = x2 - a*cos20 v3 = y2 - a*sin20 u4 = u3 v4 = y2 + a*sin20 elif x1 < x2 and y1 < y2: # righr-down u3 = x2 - a*cos25 v3 = y2 - a*sin25 u4 = x2 - a*sin25 v4 = y2 - a*cos25 elif x1 == x2 and y1 < y2: # down u3 = x2 - a*sin20 v3 = y2 - a*cos20 u4 = x2 + a*sin20 v4 = v3 elif x1 > x2 and y1 < y2: # left-down u3 = x2 + a*sin25 v3 = y2 - a*cos25 u4 = x2 + a*cos25 v4 = y2 - a*sin25 elif x1 > x2 and y1 == y2: # left u3 = x2 + a*cos20 v3 = y2 - a*sin20 u4 = u3 v4 = y2 + a*sin20 elif x1 > x2 and y1 > y2: # left-up u3 = x2 + a*sin25 v3 = y2 + a*cos25 u4 = x2 + a*cos25 v4 = y2 + a*sin25 self.canvas.create_line(x1, y1, x2, y2, fill=color, width=width) self.canvas.create_line(x2, y2, u3, v3, fill=color, width=width) self.canvas.create_line(x2, y2, u4, v4, fill=color, width=width) @staticmethod def center(window): window.update_idletasks() w = window.winfo_screenwidth() h = window.winfo_screenheight() size = tuple(int(_) for _ in window.geometry().split('+')[0].split('x')) x = w / 2 - size[0] / 2 y = h / 2 - size[1] / 2 window.geometry("%dx%d+%d+%d" % (size + (x, y))) @staticmethod def source_code_callback(self): webbrowser.open_new(r"https://goo.gl/tRaLfe") @staticmethod def video_callback(self): webbrowser.open_new(r"https://youtu.be/7GLqy61X2oU") def on_closing(): if messagebox.askokcancel("Quit", "Do you want to quit?"): os._exit(0) if __name__ == '__main__': app = Tk() app.protocol("WM_DELETE_WINDOW", on_closing) app.title("Maze 5.1") app.geometry("693x545") app.resizable(False, False) Maze51(app) app.mainloop()
true
true
f7fe8c1d16ac56938049fc68ef9d8ee45457eee9
6,942
py
Python
clinicaldg/eicu/data.py
MLforHealth/ClinicalDG
2de4a8e155231f07d80036504a6f49b50004654e
[ "MIT" ]
18
2021-03-23T07:45:56.000Z
2022-03-29T00:42:04.000Z
clinicaldg/eicu/data.py
MLforHealth/ClinicalDG
2de4a8e155231f07d80036504a6f49b50004654e
[ "MIT" ]
2
2022-03-20T16:57:28.000Z
2022-03-22T03:56:46.000Z
clinicaldg/eicu/data.py
MLforHealth/ClinicalDG
2de4a8e155231f07d80036504a6f49b50004654e
[ "MIT" ]
1
2022-03-17T19:03:15.000Z
2022-03-17T19:03:15.000Z
import pandas as pd pd.options.mode.chained_assignment = None import numpy as np from clinicaldg.eicu.data_extraction.data_extraction_mortality import data_extraction_mortality import clinicaldg.eicu.Constants as Constants from sklearn.preprocessing import StandardScaler, LabelEncoder from torch.utils.data import ConcatDataset, Dataset hospitals = pd.read_csv((Constants.eicu_dir/'hospital.csv')) hospitals['region'] = hospitals['region'].fillna('Missing') patients = pd.read_csv((Constants.eicu_dir/'patient.csv'))[['patientunitstayid', 'hospitalid', 'gender']] class LabelEncoderExt(object): ''' Label encoder, but when encountering an unseen label on the test set, will set to "Missing" ''' def __init__(self): self.label_encoder = LabelEncoder() def fit(self, data_list): self.label_encoder = self.label_encoder.fit(list(map(str, list(data_list))) + ['Missing']) self.classes_ = self.label_encoder.classes_ return self def transform(self, data_list): data_list = list(map(str, list(data_list))) for unique_item in np.unique(data_list): if unique_item not in self.label_encoder.classes_: data_list = ['Missing' if x==unique_item else x for x in data_list] return self.label_encoder.transform(data_list) class AugmentedDataset(): def __init__(self, augs = [], train_pct = 0.7, val_pct = 0.1): self.reg_mort, self.reg_pat, self.scalers, self.labelencoders = self._get_mortality_data(train_pct, val_pct) for a in augs: a.augment(self.reg_mort, self.reg_pat) def get_torch_dataset(self, envs, dset): ''' envs: a list of region names dset: one of ['train', 'val', 'test']. For the test environment, use "test" for dset ''' datasets = [] for r in envs: datasets.append(eICUDataset(self.reg_mort[r][self.reg_mort[r]['fold'] == dset], self.reg_pat[r][self.reg_pat[r]['fold'] == dset])) return ConcatDataset(datasets) def get_num_levels(self): return ({i: len(self.labelencoders[i].classes_) for i in Constants.ts_cat_features}, {i: len(self.labelencoders[i].classes_) for i in Constants.static_cat_features}, ) def _get_mortality_data(self, train_pct, val_pct): mort_df = data_extraction_mortality(str(Constants.benchmark_dir)) targets = mort_df.groupby('patientunitstayid').agg({'hospitaldischargestatus': 'first'}).reset_index() pat_df = pd.merge(patients, hospitals, on = 'hospitalid', how = 'left') pat_df = pd.merge(pat_df, targets, on = 'patientunitstayid', how = 'inner').rename(columns = {'hospitaldischargestatus': 'target'}) pat_df = pat_df[pat_df.patientunitstayid.isin(mort_df.patientunitstayid)].sample(frac = 1) # shuffle pat_df['fold'] = '' pat_df['fold'].iloc[:int(len(pat_df)*train_pct)] = 'train' pat_df['fold'].iloc[int(len(pat_df)*train_pct):int(len(pat_df)*(train_pct + val_pct))] = 'val' pat_df['fold'].iloc[int(len(pat_df)*(train_pct + val_pct)):] = 'test' mort_df = mort_df.merge(pat_df[['patientunitstayid', 'fold']], on = 'patientunitstayid') # make sure everyone has exactly 48h hours of data ## make multiindex with 48h ## groupby and ffill ## fill any remaining missing features with normal_values iterables = [np.unique(mort_df['patientunitstayid']), list(range(1, mort_df.itemoffset.max()+1))] multiind = pd.MultiIndex.from_product(iterables, names = ['patientunitstayid', 'itemoffset']) ind_df = pd.DataFrame(index = multiind) mort_df = pd.merge(ind_df, mort_df, left_index = True, right_on = ['patientunitstayid', 'itemoffset'], how = 'left') mort_df = mort_df.set_index(['patientunitstayid', 'itemoffset']).sort_index().groupby('patientunitstayid').ffill() for back_col in ['hospitaldischargestatus', 'fold'] + Constants.static_cont_features + Constants.static_cat_features: mort_df[back_col] = mort_df[back_col].fillna(method = 'backfill') for feat, val in Constants.normal_values.items(): mort_df[feat] = mort_df[feat].fillna(val) # scale continuous and static ts features scalers = {} for feat in Constants.ts_cont_features + Constants.static_cont_features: scalers[feat] = StandardScaler().fit(mort_df.loc[mort_df.fold == 'train', feat].values.reshape(-1, 1)) mort_df[feat] = scalers[feat].transform(mort_df[feat].values.reshape(-1, 1))[:, 0] # encode continuous and static cat features labelencoders, num_encodings = {}, {} for feat in Constants.ts_cat_features + Constants.static_cat_features: mort_df[feat] = mort_df[feat].fillna('Missing') labelencoders[feat] = LabelEncoderExt().fit(mort_df.loc[mort_df.fold == 'train', feat]) mort_df[feat] = labelencoders[feat].transform(mort_df[feat]) num_encodings[feat] = len(labelencoders[feat].classes_) reg_mort, reg_pat = {}, {} for reg in pat_df.region.unique(): sub_pat = pat_df[pat_df.region == reg] sub = mort_df[mort_df.index.get_level_values(0).isin(sub_pat.patientunitstayid)] reg_mort[reg] = sub reg_pat[reg] = sub_pat.set_index('patientunitstayid') return reg_mort, reg_pat, scalers, labelencoders class eICUDataset(Dataset): def __init__(self, mort_df, pat_df): self.mort_df = mort_df self.pat_df = pat_df def __len__(self): return self.pat_df.shape[0] def __getitem__(self, idx): pat_id = self.pat_df.index[idx] mort_data = self.mort_df.loc[pat_id] ts_cont_feats = mort_data[Constants.ts_cont_features].values ts_cat_feats = mort_data[Constants.ts_cat_features].values static_not_in_mort = [i for i in Constants.static_cont_features if i not in self.mort_df] static_in_mort = [i for i in Constants.static_cont_features if i in self.mort_df] static_cont_feats = np.concatenate((mort_data[static_in_mort].iloc[0].values, self.pat_df.loc[pat_id, static_not_in_mort].values)).astype(float) static_cat_feats = mort_data[Constants.static_cat_features].iloc[0].values return ({'pat_id': pat_id, 'ts_cont_feats': ts_cont_feats, 'ts_cat_feats': ts_cat_feats, 'static_cont_feats': static_cont_feats, 'static_cat_feats': static_cat_feats, 'gender': int(self.pat_df.loc[pat_id, 'gender'].strip() == 'Male')}, self.pat_df.loc[pat_id, 'target'])
49.942446
152
0.644771
import pandas as pd pd.options.mode.chained_assignment = None import numpy as np from clinicaldg.eicu.data_extraction.data_extraction_mortality import data_extraction_mortality import clinicaldg.eicu.Constants as Constants from sklearn.preprocessing import StandardScaler, LabelEncoder from torch.utils.data import ConcatDataset, Dataset hospitals = pd.read_csv((Constants.eicu_dir/'hospital.csv')) hospitals['region'] = hospitals['region'].fillna('Missing') patients = pd.read_csv((Constants.eicu_dir/'patient.csv'))[['patientunitstayid', 'hospitalid', 'gender']] class LabelEncoderExt(object): def __init__(self): self.label_encoder = LabelEncoder() def fit(self, data_list): self.label_encoder = self.label_encoder.fit(list(map(str, list(data_list))) + ['Missing']) self.classes_ = self.label_encoder.classes_ return self def transform(self, data_list): data_list = list(map(str, list(data_list))) for unique_item in np.unique(data_list): if unique_item not in self.label_encoder.classes_: data_list = ['Missing' if x==unique_item else x for x in data_list] return self.label_encoder.transform(data_list) class AugmentedDataset(): def __init__(self, augs = [], train_pct = 0.7, val_pct = 0.1): self.reg_mort, self.reg_pat, self.scalers, self.labelencoders = self._get_mortality_data(train_pct, val_pct) for a in augs: a.augment(self.reg_mort, self.reg_pat) def get_torch_dataset(self, envs, dset): datasets = [] for r in envs: datasets.append(eICUDataset(self.reg_mort[r][self.reg_mort[r]['fold'] == dset], self.reg_pat[r][self.reg_pat[r]['fold'] == dset])) return ConcatDataset(datasets) def get_num_levels(self): return ({i: len(self.labelencoders[i].classes_) for i in Constants.ts_cat_features}, {i: len(self.labelencoders[i].classes_) for i in Constants.static_cat_features}, ) def _get_mortality_data(self, train_pct, val_pct): mort_df = data_extraction_mortality(str(Constants.benchmark_dir)) targets = mort_df.groupby('patientunitstayid').agg({'hospitaldischargestatus': 'first'}).reset_index() pat_df = pd.merge(patients, hospitals, on = 'hospitalid', how = 'left') pat_df = pd.merge(pat_df, targets, on = 'patientunitstayid', how = 'inner').rename(columns = {'hospitaldischargestatus': 'target'}) pat_df = pat_df[pat_df.patientunitstayid.isin(mort_df.patientunitstayid)].sample(frac = 1) pat_df['fold'] = '' pat_df['fold'].iloc[:int(len(pat_df)*train_pct)] = 'train' pat_df['fold'].iloc[int(len(pat_df)*train_pct):int(len(pat_df)*(train_pct + val_pct))] = 'val' pat_df['fold'].iloc[int(len(pat_df)*(train_pct + val_pct)):] = 'test' mort_df = mort_df.merge(pat_df[['patientunitstayid', 'fold']], on = 'patientunitstayid') f.itemoffset.max()+1))] multiind = pd.MultiIndex.from_product(iterables, names = ['patientunitstayid', 'itemoffset']) ind_df = pd.DataFrame(index = multiind) mort_df = pd.merge(ind_df, mort_df, left_index = True, right_on = ['patientunitstayid', 'itemoffset'], how = 'left') mort_df = mort_df.set_index(['patientunitstayid', 'itemoffset']).sort_index().groupby('patientunitstayid').ffill() for back_col in ['hospitaldischargestatus', 'fold'] + Constants.static_cont_features + Constants.static_cat_features: mort_df[back_col] = mort_df[back_col].fillna(method = 'backfill') for feat, val in Constants.normal_values.items(): mort_df[feat] = mort_df[feat].fillna(val) scalers = {} for feat in Constants.ts_cont_features + Constants.static_cont_features: scalers[feat] = StandardScaler().fit(mort_df.loc[mort_df.fold == 'train', feat].values.reshape(-1, 1)) mort_df[feat] = scalers[feat].transform(mort_df[feat].values.reshape(-1, 1))[:, 0] labelencoders, num_encodings = {}, {} for feat in Constants.ts_cat_features + Constants.static_cat_features: mort_df[feat] = mort_df[feat].fillna('Missing') labelencoders[feat] = LabelEncoderExt().fit(mort_df.loc[mort_df.fold == 'train', feat]) mort_df[feat] = labelencoders[feat].transform(mort_df[feat]) num_encodings[feat] = len(labelencoders[feat].classes_) reg_mort, reg_pat = {}, {} for reg in pat_df.region.unique(): sub_pat = pat_df[pat_df.region == reg] sub = mort_df[mort_df.index.get_level_values(0).isin(sub_pat.patientunitstayid)] reg_mort[reg] = sub reg_pat[reg] = sub_pat.set_index('patientunitstayid') return reg_mort, reg_pat, scalers, labelencoders class eICUDataset(Dataset): def __init__(self, mort_df, pat_df): self.mort_df = mort_df self.pat_df = pat_df def __len__(self): return self.pat_df.shape[0] def __getitem__(self, idx): pat_id = self.pat_df.index[idx] mort_data = self.mort_df.loc[pat_id] ts_cont_feats = mort_data[Constants.ts_cont_features].values ts_cat_feats = mort_data[Constants.ts_cat_features].values static_not_in_mort = [i for i in Constants.static_cont_features if i not in self.mort_df] static_in_mort = [i for i in Constants.static_cont_features if i in self.mort_df] static_cont_feats = np.concatenate((mort_data[static_in_mort].iloc[0].values, self.pat_df.loc[pat_id, static_not_in_mort].values)).astype(float) static_cat_feats = mort_data[Constants.static_cat_features].iloc[0].values return ({'pat_id': pat_id, 'ts_cont_feats': ts_cont_feats, 'ts_cat_feats': ts_cat_feats, 'static_cont_feats': static_cont_feats, 'static_cat_feats': static_cat_feats, 'gender': int(self.pat_df.loc[pat_id, 'gender'].strip() == 'Male')}, self.pat_df.loc[pat_id, 'target'])
true
true
f7fe8c4804d16ffd1db3a338967955f15498fe1f
28,269
py
Python
src/opencmiss/neon/ui/mainwindow.py
hsorby/neon
0fcbddfca8baf50d8ecc310a7cb393ffdec88431
[ "Apache-2.0" ]
null
null
null
src/opencmiss/neon/ui/mainwindow.py
hsorby/neon
0fcbddfca8baf50d8ecc310a7cb393ffdec88431
[ "Apache-2.0" ]
2
2016-01-15T04:17:35.000Z
2016-02-26T04:01:02.000Z
src/opencmiss/neon/ui/mainwindow.py
hsorby/neon
0fcbddfca8baf50d8ecc310a7cb393ffdec88431
[ "Apache-2.0" ]
6
2015-11-29T20:57:16.000Z
2021-06-08T04:02:26.000Z
""" Copyright 2015 University of Auckland Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os.path from PySide2 import QtCore, QtWidgets from opencmiss.neon.ui.ui_mainwindow import Ui_MainWindow from opencmiss.neon.undoredo.commands import CommandEmpty from opencmiss.neon.ui.views.visualisationview import VisualisationView from opencmiss.neon.ui.dialogs.aboutdialog import AboutDialog from opencmiss.neon.ui.editors.loggereditorwidget import LoggerEditorWidget from opencmiss.zincwidgets.regioneditorwidget import RegionEditorWidget from opencmiss.zincwidgets.materialeditorwidget import MaterialEditorWidget from opencmiss.zincwidgets.modelsourceseditorwidget import ModelSourcesEditorWidget, ModelSourcesModel from opencmiss.zincwidgets.sceneviewereditorwidget import SceneviewerEditorWidget from opencmiss.zincwidgets.sceneeditorwidget import SceneEditorWidget from opencmiss.zincwidgets.spectrumeditorwidget import SpectrumEditorWidget from opencmiss.zincwidgets.tessellationeditorwidget import TessellationEditorWidget from opencmiss.zincwidgets.timeeditorwidget import TimeEditorWidget from opencmiss.zincwidgets.fieldlisteditorwidget import FieldListEditorWidget from opencmiss.neon.settings.mainsettings import VERSION_MAJOR class MainWindow(QtWidgets.QMainWindow): def __init__(self, model): super(MainWindow, self).__init__() self._model = model self._ui = Ui_MainWindow() self._ui.setupUi(self) self._visualisation_view_state_update_pending = False # List of possible views self._visualisation_view = VisualisationView(self) self._visualisation_view_ready = False self._view_states = {self._visualisation_view: ''} # self._view_states[self._problem_view] = '' # self._view_states[self._simulation_view] = '' view_list = [self._visualisation_view] self._location = None # The last location/directory used by the application self._current_view = None self._undoRedoStack = QtWidgets.QUndoStack(self) # Pre-create dialogs #self._createDialogs() self._setupEditors() self._registerEditors() self._setupViews(view_list) self._setupOtherWindows() self._registerOtherWindows() self._addDockWidgets() self._makeConnections() # Set the undo redo stack state self._undoRedoStack.push(CommandEmpty()) self._undoRedoStack.clear() self._updateUi() self._readSettings() self._onDocumentChanged() def _makeConnections(self): self._ui.action_Quit.triggered.connect(self.close) self._ui.action_New.triggered.connect(self._newTriggered) self._ui.action_Open.triggered.connect(self._openTriggered) self._ui.action_About.triggered.connect(self._aboutTriggered) self._ui.action_Save.triggered.connect(self._saveTriggered) self._ui.action_Save_As.triggered.connect(self._saveAsTriggered) self._ui.action_Snapshot.triggered.connect(self._snapshotTriggered) self._ui.actionPreferences.triggered.connect(self._preferencesTriggered) self._ui.action_Clear.triggered.connect(self._clearTriggered) self._undoRedoStack.indexChanged.connect(self._undoRedoStackIndexChanged) self._undoRedoStack.canUndoChanged.connect(self._ui.action_Undo.setEnabled) self._undoRedoStack.canRedoChanged.connect(self._ui.action_Redo.setEnabled) self._visualisation_view.graphicsInitialized.connect(self._visualisationViewReady) # self._snapshot_dialog.sceneviewerInitialized.connect(self._snapshotDialogReady) self.dockWidgetContentsRegionEditor.regionSelected.connect(self._regionSelected) # self.dockWidgetContentsProblemEditor.runClicked.connect(self._runSimulationClicked) # self.dockWidgetContentsSimulationEditor.visualiseClicked.connect(self._visualiseSimulationClicked) self._model.documentChanged.connect(self._onDocumentChanged) def _updateUi(self): modified = self._model.isModified() self._ui.action_Save.setEnabled(modified) recents = self._model.getRecents() self._ui.action_Clear.setEnabled(len(recents)) def _addDockWidgets(self): self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dockWidgetModelSourcesEditor) self.tabifyDockWidget(self.dockWidgetModelSourcesEditor, self.dockWidgetTessellationEditor) self.tabifyDockWidget(self.dockWidgetModelSourcesEditor, self.dockWidgetSpectrumEditor) self.tabifyDockWidget(self.dockWidgetModelSourcesEditor, self.dockWidgetMaterialEditor) self.tabifyDockWidget(self.dockWidgetModelSourcesEditor, self.dockWidgetSceneEditor) self.tabifyDockWidget(self.dockWidgetModelSourcesEditor, self.dockWidgetRegionEditor) self.tabifyDockWidget(self.dockWidgetModelSourcesEditor, self.dockWidgetSceneviewerEditor) self.tabifyDockWidget(self.dockWidgetModelSourcesEditor, self.dockWidgetFieldEditor) self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.dockWidgetLoggerEditor) self.tabifyDockWidget(self.dockWidgetLoggerEditor, self.dockWidgetTimeEditor) def _setupEditors(self): self.dockWidgetRegionEditor = QtWidgets.QDockWidget(self) self.dockWidgetRegionEditor.setWindowTitle('Region Editor') self.dockWidgetRegionEditor.setObjectName("dockWidgetRegionEditor") self.dockWidgetContentsRegionEditor = RegionEditorWidget() self.dockWidgetContentsRegionEditor.setObjectName("dockWidgetContentsRegionEditor") self.dockWidgetRegionEditor.setWidget(self.dockWidgetContentsRegionEditor) self.dockWidgetRegionEditor.setHidden(True) self.dockWidgetMaterialEditor = QtWidgets.QDockWidget(self) self.dockWidgetMaterialEditor.setWindowTitle('Material Editor') self.dockWidgetMaterialEditor.setObjectName("dockWidgetMaterialEditor") self.dockWidgetContentsMaterialEditor = MaterialEditorWidget() self.dockWidgetContentsMaterialEditor.setObjectName("dockWidgetContentsMaterialEditor") self.dockWidgetMaterialEditor.setWidget(self.dockWidgetContentsMaterialEditor) self.dockWidgetMaterialEditor.setHidden(True) self.dockWidgetModelSourcesEditor = QtWidgets.QDockWidget(self) self.dockWidgetModelSourcesEditor.setWindowTitle('Model Sources Editor') self.dockWidgetModelSourcesEditor.setObjectName("dockWidgetModelSourcesEditor") self.dockWidgetContentsModelSourcesEditor = ModelSourcesEditorWidget() self.dockWidgetContentsModelSourcesEditor.setObjectName("dockWidgetContentsModelSourcesEditor") self.dockWidgetModelSourcesEditor.setWidget(self.dockWidgetContentsModelSourcesEditor) self.dockWidgetModelSourcesEditor.setHidden(False) self.dockWidgetSceneEditor = QtWidgets.QDockWidget(self) self.dockWidgetSceneEditor.setWindowTitle('Scene Editor') self.dockWidgetSceneEditor.setObjectName("dockWidgetSceneEditor") self.dockWidgetContentsSceneEditor = SceneEditorWidget() self.dockWidgetContentsSceneEditor.setObjectName("dockWidgetContentsSceneEditor") self.dockWidgetSceneEditor.setWidget(self.dockWidgetContentsSceneEditor) self.dockWidgetSceneEditor.setHidden(True) self.dockWidgetSceneviewerEditor = QtWidgets.QDockWidget(self) self.dockWidgetSceneviewerEditor.setWindowTitle('Sceneviewer Editor') self.dockWidgetSceneviewerEditor.setObjectName("dockWidgetSceneviewerEditor") self.dockWidgetContentsSceneviewerEditor = SceneviewerEditorWidget(self.dockWidgetSceneviewerEditor) self.dockWidgetContentsSceneviewerEditor.setObjectName("dockWidgetContentsSceneviewerEditor") self.dockWidgetSceneviewerEditor.setWidget(self.dockWidgetContentsSceneviewerEditor) self.dockWidgetSceneviewerEditor.setHidden(True) self.dockWidgetSceneviewerEditor.visibilityChanged.connect(self.dockWidgetContentsSceneviewerEditor.setEnableUpdates) self.dockWidgetSpectrumEditor = QtWidgets.QDockWidget(self) self.dockWidgetSpectrumEditor.setWindowTitle('Spectrum Editor') self.dockWidgetSpectrumEditor.setObjectName("dockWidgetSpectrumEditor") self.dockWidgetContentsSpectrumEditor = SpectrumEditorWidget(self.dockWidgetSpectrumEditor) self.dockWidgetContentsSpectrumEditor.setObjectName("dockWidgetContentsSpectrumEditor") self.dockWidgetSpectrumEditor.setWidget(self.dockWidgetContentsSpectrumEditor) self.dockWidgetSpectrumEditor.setHidden(True) self.dockWidgetTessellationEditor = QtWidgets.QDockWidget(self) self.dockWidgetTessellationEditor.setWindowTitle('Tessellation Editor') self.dockWidgetTessellationEditor.setObjectName("dockWidgetTessellationEditor") self.dockWidgetContentsTessellationEditor = TessellationEditorWidget() self.dockWidgetContentsTessellationEditor.setObjectName("dockWidgetContentsTessellationEditor") self.dockWidgetTessellationEditor.setWidget(self.dockWidgetContentsTessellationEditor) self.dockWidgetTessellationEditor.setHidden(True) self.dockWidgetTimeEditor = QtWidgets.QDockWidget(self) self.dockWidgetTimeEditor.setWindowTitle('Time Editor') self.dockWidgetTimeEditor.setObjectName("dockWidgetTimeEditor") self.dockWidgetContentsTimeEditor = TimeEditorWidget() self.dockWidgetContentsTimeEditor.setObjectName("dockWidgetContentsTimeEditor") self.dockWidgetTimeEditor.setWidget(self.dockWidgetContentsTimeEditor) self.dockWidgetTimeEditor.setHidden(True) self.dockWidgetFieldEditor = QtWidgets.QDockWidget(self) self.dockWidgetFieldEditor.setWindowTitle('Field Editor') self.dockWidgetFieldEditor.setObjectName("dockWidgetFieldEditor") self.dockWidgetContentsFieldEditor = FieldListEditorWidget() self.dockWidgetContentsFieldEditor.setObjectName("dockWidgetContentsFieldEditor") self.dockWidgetFieldEditor.setWidget(self.dockWidgetContentsFieldEditor) self.dockWidgetFieldEditor.setHidden(True) def _registerEditors(self): # self._registerEditor(self._problem_view, self.dockWidgetProblemEditor) # self._registerEditor(self._simulation_view, self.dockWidgetSimulationEditor) self._registerEditor(self._visualisation_view, self.dockWidgetRegionEditor) self._registerEditor(self._visualisation_view, self.dockWidgetMaterialEditor) self._registerEditor(self._visualisation_view, self.dockWidgetModelSourcesEditor) self._registerEditor(self._visualisation_view, self.dockWidgetSceneEditor) self._registerEditor(self._visualisation_view, self.dockWidgetSceneviewerEditor) self._registerEditor(self._visualisation_view, self.dockWidgetSpectrumEditor) self._registerEditor(self._visualisation_view, self.dockWidgetTessellationEditor) self._registerEditor(self._visualisation_view, self.dockWidgetTimeEditor) self._registerEditor(self._visualisation_view, self.dockWidgetFieldEditor) self._ui.menu_View.addSeparator() def _registerEditor(self, view, editor): action_name = getEditorMenuName(view) action = self._getEditorAction(action_name) if action is None: menu = self._ui.menu_View.addMenu(action_name) menu.setEnabled(False) else: menu = action.menu() toggle_action = editor.toggleViewAction() toggle_action.triggered.connect(self._view_dock_widget) menu.addAction(toggle_action) view.registerDependentEditor(editor) def _view_dock_widget(self, show): """ If we are showing the dock widget we will make it current i.e. make sure it is visible if tabbed. """ if show: sender_text = self.sender().text() for tab_bar in self.findChildren(QtWidgets.QTabBar): for index in range(tab_bar.count()): tab_text = tab_bar.tabText(index) if tab_text == sender_text: tab_bar.setCurrentIndex(index) return def _getEditorAction(self, action_name): action = None actions = self._ui.menu_View.actions() existing_actions = [a for a in actions if a.text() == action_name] if existing_actions: action = existing_actions[0] return action # def _createDialogs(self): # self._snapshot_dialog = SnapshotDialog(self, self._ui.one_gl_widget_to_rule_them_all) # self._snapshot_dialog.setZincContext(self._model.getZincContext()) # self._preferences_dialog = PreferencesDialog(self) def _writeSettings(self): settings = QtCore.QSettings() settings.beginGroup('MainWindow') settings.setValue('location', self._location) settings.setValue('geometry', self.saveGeometry()) settings.setValue('current_view', self._ui.viewStackedWidget.currentIndex()) settings.beginWriteArray('recents') recents = self._model.getRecents() for i, r in enumerate(recents): settings.setArrayIndex(i) settings.setValue('item', r) settings.endArray() settings.endGroup() settings.beginGroup('views') self._storeCurrentView() # needed in case user never changed view for key in self._view_states: settings.setValue(key.getName(), self._view_states[key]) settings.endGroup() settings.beginGroup('SnapshotDialog') # settings.setValue('state', self._snapshot_dialog.serialize()) settings.endGroup() settings.beginGroup('Problems') # settings.setValue('state', self._problem_view.serialize()) settings.endGroup() def _readSettings(self): settings = QtCore.QSettings() settings.beginGroup('MainWindow') geometry = settings.value('geometry') if geometry is not None: self.restoreGeometry(geometry) self._location = settings.value('location', QtCore.QDir.homePath()) size = settings.beginReadArray('recents') for i in range(size): settings.setArrayIndex(i) self._addRecent(settings.value('item')) settings.endArray() currentViewIndex = settings.value('current_view', '0') settings.endGroup() settings.beginGroup('views') for key in self._view_states: state = settings.value(key.getName(), '') self._view_states[key] = state settings.endGroup() self._setCurrentView(currentViewIndex) self._postChangeView() settings.beginGroup('SnapshotDialog') # self._snapshot_dialog.deserialize(settings.value('state', '')) settings.endGroup() settings.beginGroup('Problems') # self._problem_view.deserialize(settings.value('state', '')) settings.endGroup() self._updateUi() def _addRecent(self, recent): actions = self._ui.menu_Open_recent.actions() insert_before_action = actions[0] self._model.addRecent(recent) recent_action = QtWidgets.QAction(self._ui.menu_Open_recent) recent_action.setText(recent) self._ui.menu_Open_recent.insertAction(insert_before_action, recent_action) recent_action.triggered.connect(self._open) def _setCurrentView(self, index): v = self._ui.viewStackedWidget.widget(int(index)) self._changeView(v) self._postChangeView() actions = self._ui.menu_View.actions() for action in actions: if action.data() == v: action.setChecked(True) def _storeCurrentView(self): current_view = self._ui.viewStackedWidget.currentWidget() view_state = self.saveState(VERSION_MAJOR) self._view_states[current_view] = view_state def _preChangeView(self): current_view = self._ui.viewStackedWidget.currentWidget() dependent_editors = current_view.getDependentEditors() view_state = self.saveState(VERSION_MAJOR) self._view_states[current_view] = view_state for ed in dependent_editors: ed.setHidden(True) action_name = getEditorMenuName(current_view) action = self._getEditorAction(action_name) if action is not None: menu = action.menu() menu.setEnabled(False) def _changeView(self, view): self._ui.viewStackedWidget.setCurrentWidget(view) def _postChangeView(self): current_view = self._ui.viewStackedWidget.currentWidget() view_state = self._view_states[current_view] # self.restoreState(view_state, VERSION_MAJOR) action_name = getEditorMenuName(current_view) action = self._getEditorAction(action_name) if action is not None: menu = action.menu() menu.setEnabled(True) def _setupOtherWindows(self): self.dockWidgetLoggerEditor = QtWidgets.QDockWidget("Log Viewer", self) # self.dockWidgetLoggerEditor.setWindowTitle('Logger') self.dockWidgetLoggerEditor.setObjectName("dockWidgetLoggerEditor") logger_widget = LoggerEditorWidget(self.dockWidgetLoggerEditor) # logger_widget.setObjectName("dockWidgetContentsLoggerEditor") self.dockWidgetLoggerEditor.setWidget(logger_widget) self.dockWidgetLoggerEditor.setHidden(True) def _registerOtherWindows(self): self._registerOtherWindow(self.dockWidgetLoggerEditor) def _registerOtherWindow(self, editor): action = self._getEditorAction("Other Windows") if action is None: menu = self._ui.menu_View.addMenu("Other Windows") menu.setEnabled(True) else: menu = action.menu() toggle_action = editor.toggleViewAction() toggle_action.triggered.connect(self._view_dock_widget) menu.addAction(toggle_action) def _setupViews(self, views): action_group = QtWidgets.QActionGroup(self) zincContext = self._model.getZincContext() for v in views: self._ui.viewStackedWidget.addWidget(v) v.setZincContext(zincContext) action_view = QtWidgets.QAction(v.getName(), self) action_view.setData(v) action_view.setCheckable(True) action_view.setActionGroup(action_group) action_view.triggered.connect(self._viewTriggered) self._ui.menu_View.addAction(action_view) self._ui.menu_View.addSeparator() def _runSimulationClicked(self): sender = self.sender() if sender == self.dockWidgetContentsProblemEditor: actions = self._ui.menu_View.actions() simulate_action = [a for a in actions if a.text() == self._simulation_view.getName()][0] simulate_action.activate(QtWidgets.QAction.ActionEvent.Trigger) problem = self._model.getDocument().getProject().getProblem() if problem.validate(): self._simulation_view.setProblem(problem) self._simulation_view.setPreferences(self._model.getPreferences()) self._simulation_view.run() else: print('pop up error box') def _visualiseSimulationClicked(self): sender = self.sender() if sender == self.dockWidgetContentsSimulationEditor: actions = self._ui.menu_View.actions() visualise_action = [a for a in actions if a.text() == self._visualisation_view.getName()][0] visualise_action.activate(QtWidgets.QAction.ActionEvent.Trigger) simulation = self._simulation_view.getSimulation() if simulation.validate(): self._model.visualiseSimulation(simulation) else: print('pop up error box') def _viewTriggered(self): v = self.sender().data() self._preChangeView() self._changeView(v) self._postChangeView() def _regionChange(self, changedRegion, treeChange): """ Notifies sceneviewer if affected by tree change i.e. needs new scene. :param changedRegion: The top region changed :param treeChange: True if structure of tree, or zinc objects reconstructed """ # following may need changing once sceneviewer can look at sub scenes, since resets to root scene: if treeChange and (changedRegion is self._model.getDocument().getRootRegion()): zincRootRegion = changedRegion.getZincRegion() self._visualisation_view.setScene(zincRootRegion.getScene()) def _onDocumentChanged(self): document = self._model.getDocument() rootRegion = document.getRootRegion() rootRegion.connectRegionChange(self._regionChange) zincRootRegion = rootRegion.getZincRegion() # need to pass new Zinc context to dialogs and widgets using global modules zincContext = document.getZincContext() self._visualisation_view.setZincContext(zincContext) # self._simulation_view.setZincContext(zincContext) self.dockWidgetContentsSpectrumEditor.setSpectrums(document.getSpectrums()) self.dockWidgetContentsMaterialEditor.setMaterials(document.getMaterials()) self.dockWidgetContentsTessellationEditor.setTessellations(document.getTessellations()) self.dockWidgetContentsTimeEditor.setZincContext(zincContext) # self._snapshot_dialog.setZincContext(zincContext) model_sources_model = ModelSourcesModel(document, []) self.dockWidgetContentsModelSourcesEditor.setModelSourcesModel(zincRootRegion, model_sources_model) # need to pass new root region to the following self.dockWidgetContentsRegionEditor.setRootRegion(rootRegion) self.dockWidgetContentsSceneEditor.setZincRootRegion(zincRootRegion) self.dockWidgetContentsFieldEditor.setRootArgonRegion(rootRegion) self.dockWidgetContentsFieldEditor.setTimekeeper(zincContext.getTimekeepermodule().getDefaultTimekeeper()) if self._visualisation_view_ready: self._restoreSceneviewerState() else: self._visualisation_view_state_update_pending = True # project = document.getProject() # index = self._model.getProjectModel().getIndex(project) # self._problem_view.setCurrentIndex(index.row()) # self._simulation_view.setCurrentIndex(index.row()) # self._problem_view.setProblem(project.getProblem()) def _regionSelected(self, region): # self.dockWidgetContentsModelSourcesEditor.setRegion(region) zincRegion = region.getZincRegion() # scene = zincRegion.getScene() # self.dockWidgetContentsSceneEditor.setScene(scene) self.dockWidgetContentsFieldEditor.setFieldmodule(zincRegion.getFieldmodule()) self.dockWidgetContentsFieldEditor.setArgonRegion(region) def _visualisationViewReady(self): self._visualisation_view_ready = True if self._visualisation_view_state_update_pending: self._restoreSceneviewerState() def _saveTriggered(self): if self._model.getLocation() is None: self._saveAsTriggered() else: self._recordSceneviewerState() self._model.save() def _saveAsTriggered(self): filename, _ = QtWidgets.QFileDialog.getSaveFileName(self, caption='Choose file ...', dir=self._location, filter="Neon Files (*.neon *.json);;All (*.*)") if filename: self._location = os.path.dirname(filename) self._model.setLocation(filename) self._recordSceneviewerState() self._model.save() def _restoreSceneviewerState(self): document = self._model.getDocument() sceneviewer_state = document.getSceneviewer().serialize() self._visualisation_view.setSceneviewerState(sceneviewer_state) self.dockWidgetContentsSceneviewerEditor.setSceneviewer(self._visualisation_view.getSceneviewer()) self._visualisation_view_state_update_pending = False def _recordSceneviewerState(self): sceneviewer_state = self._visualisation_view.getSceneviewerState() document = self._model.getDocument() document.getSceneviewer().deserialize(sceneviewer_state) def _undoRedoStackIndexChanged(self, index): self._model.setCurrentUndoRedoIndex(index) def _aboutTriggered(self): d = AboutDialog(self) d.exec_() def _snapshotDialogReady(self): document = self._model.getDocument() rootRegion = document.getRootRegion() zincRootRegion = rootRegion.getZincRegion() scene = zincRootRegion.getScene() self._snapshot_dialog.setScene(scene) def _snapshotTriggered(self): if self._snapshot_dialog.getLocation() is None and self._location is not None: self._snapshot_dialog.setLocation(self._location) if self._snapshot_dialog.exec_(): if self._location is None: self._location = self._snapshot_dialog.getLocation() filename = self._snapshot_dialog.getFilename() wysiwyg = self._snapshot_dialog.getWYSIWYG() width = self._snapshot_dialog.getWidth() height = self._snapshot_dialog.getHeight() self._visualisation_view.saveImage(filename, wysiwyg, width, height) def _preferencesTriggered(self): if self._preferences_dialog.exec_(): pass # Save the state def _newTriggered(self): self._model.new() def _openModel(self, filename): success = self._model.load(filename) if success: self._location = os.path.dirname(filename) self._addRecent(filename) else: QtWidgets.QMessageBox.warning(self, "Load failure", "Failed to load file " + filename + ". Refer to logger window for more details", QtWidgets.QMessageBox.Ok) self._model.new() # in case document half constructed; emits documentChanged self._updateUi() def _openTriggered(self): filename, _ = QtWidgets.QFileDialog.getOpenFileName(self, caption='Choose file ...', dir=self._location, filter="Neon Files (*.neon *.json);;All (*.*)") if filename: self._openModel(filename) def _open(self): """ Open a model from a recent file. """ filename = self.sender().text() self._ui.menu_Open_recent.removeAction(self.sender()) self._model.removeRecent(filename) self._openModel(filename) def _clearTriggered(self): self._model.clearRecents() actions = self._ui.menu_Open_recent.actions() for action in actions[:-2]: self._ui.menu_Open_recent.removeAction(action) self._updateUi() def confirmClose(self): # Check to see if the Workflow is in a saved state. if self._model.isModified(): ret = QtWidgets.QMessageBox.warning(self, 'Unsaved Changes', 'You have unsaved changes, would you like to save these changes now?', QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) if ret == QtWidgets.QMessageBox.Yes: self._saveTriggered() def _quitApplication(self): self.confirmClose() # self._setCurrentView('0') self._writeSettings() def closeEvent(self, event): self._quitApplication() super(MainWindow, self).closeEvent(event) def getEditorMenuName(view): return view.getName() + ' Editors'
44.871429
170
0.718738
import os.path from PySide2 import QtCore, QtWidgets from opencmiss.neon.ui.ui_mainwindow import Ui_MainWindow from opencmiss.neon.undoredo.commands import CommandEmpty from opencmiss.neon.ui.views.visualisationview import VisualisationView from opencmiss.neon.ui.dialogs.aboutdialog import AboutDialog from opencmiss.neon.ui.editors.loggereditorwidget import LoggerEditorWidget from opencmiss.zincwidgets.regioneditorwidget import RegionEditorWidget from opencmiss.zincwidgets.materialeditorwidget import MaterialEditorWidget from opencmiss.zincwidgets.modelsourceseditorwidget import ModelSourcesEditorWidget, ModelSourcesModel from opencmiss.zincwidgets.sceneviewereditorwidget import SceneviewerEditorWidget from opencmiss.zincwidgets.sceneeditorwidget import SceneEditorWidget from opencmiss.zincwidgets.spectrumeditorwidget import SpectrumEditorWidget from opencmiss.zincwidgets.tessellationeditorwidget import TessellationEditorWidget from opencmiss.zincwidgets.timeeditorwidget import TimeEditorWidget from opencmiss.zincwidgets.fieldlisteditorwidget import FieldListEditorWidget from opencmiss.neon.settings.mainsettings import VERSION_MAJOR class MainWindow(QtWidgets.QMainWindow): def __init__(self, model): super(MainWindow, self).__init__() self._model = model self._ui = Ui_MainWindow() self._ui.setupUi(self) self._visualisation_view_state_update_pending = False self._visualisation_view = VisualisationView(self) self._visualisation_view_ready = False self._view_states = {self._visualisation_view: ''} view_list = [self._visualisation_view] self._location = None self._current_view = None self._undoRedoStack = QtWidgets.QUndoStack(self) self._setupEditors() self._registerEditors() self._setupViews(view_list) self._setupOtherWindows() self._registerOtherWindows() self._addDockWidgets() self._makeConnections() self._undoRedoStack.push(CommandEmpty()) self._undoRedoStack.clear() self._updateUi() self._readSettings() self._onDocumentChanged() def _makeConnections(self): self._ui.action_Quit.triggered.connect(self.close) self._ui.action_New.triggered.connect(self._newTriggered) self._ui.action_Open.triggered.connect(self._openTriggered) self._ui.action_About.triggered.connect(self._aboutTriggered) self._ui.action_Save.triggered.connect(self._saveTriggered) self._ui.action_Save_As.triggered.connect(self._saveAsTriggered) self._ui.action_Snapshot.triggered.connect(self._snapshotTriggered) self._ui.actionPreferences.triggered.connect(self._preferencesTriggered) self._ui.action_Clear.triggered.connect(self._clearTriggered) self._undoRedoStack.indexChanged.connect(self._undoRedoStackIndexChanged) self._undoRedoStack.canUndoChanged.connect(self._ui.action_Undo.setEnabled) self._undoRedoStack.canRedoChanged.connect(self._ui.action_Redo.setEnabled) self._visualisation_view.graphicsInitialized.connect(self._visualisationViewReady) self.dockWidgetContentsRegionEditor.regionSelected.connect(self._regionSelected) self._model.documentChanged.connect(self._onDocumentChanged) def _updateUi(self): modified = self._model.isModified() self._ui.action_Save.setEnabled(modified) recents = self._model.getRecents() self._ui.action_Clear.setEnabled(len(recents)) def _addDockWidgets(self): self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dockWidgetModelSourcesEditor) self.tabifyDockWidget(self.dockWidgetModelSourcesEditor, self.dockWidgetTessellationEditor) self.tabifyDockWidget(self.dockWidgetModelSourcesEditor, self.dockWidgetSpectrumEditor) self.tabifyDockWidget(self.dockWidgetModelSourcesEditor, self.dockWidgetMaterialEditor) self.tabifyDockWidget(self.dockWidgetModelSourcesEditor, self.dockWidgetSceneEditor) self.tabifyDockWidget(self.dockWidgetModelSourcesEditor, self.dockWidgetRegionEditor) self.tabifyDockWidget(self.dockWidgetModelSourcesEditor, self.dockWidgetSceneviewerEditor) self.tabifyDockWidget(self.dockWidgetModelSourcesEditor, self.dockWidgetFieldEditor) self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.dockWidgetLoggerEditor) self.tabifyDockWidget(self.dockWidgetLoggerEditor, self.dockWidgetTimeEditor) def _setupEditors(self): self.dockWidgetRegionEditor = QtWidgets.QDockWidget(self) self.dockWidgetRegionEditor.setWindowTitle('Region Editor') self.dockWidgetRegionEditor.setObjectName("dockWidgetRegionEditor") self.dockWidgetContentsRegionEditor = RegionEditorWidget() self.dockWidgetContentsRegionEditor.setObjectName("dockWidgetContentsRegionEditor") self.dockWidgetRegionEditor.setWidget(self.dockWidgetContentsRegionEditor) self.dockWidgetRegionEditor.setHidden(True) self.dockWidgetMaterialEditor = QtWidgets.QDockWidget(self) self.dockWidgetMaterialEditor.setWindowTitle('Material Editor') self.dockWidgetMaterialEditor.setObjectName("dockWidgetMaterialEditor") self.dockWidgetContentsMaterialEditor = MaterialEditorWidget() self.dockWidgetContentsMaterialEditor.setObjectName("dockWidgetContentsMaterialEditor") self.dockWidgetMaterialEditor.setWidget(self.dockWidgetContentsMaterialEditor) self.dockWidgetMaterialEditor.setHidden(True) self.dockWidgetModelSourcesEditor = QtWidgets.QDockWidget(self) self.dockWidgetModelSourcesEditor.setWindowTitle('Model Sources Editor') self.dockWidgetModelSourcesEditor.setObjectName("dockWidgetModelSourcesEditor") self.dockWidgetContentsModelSourcesEditor = ModelSourcesEditorWidget() self.dockWidgetContentsModelSourcesEditor.setObjectName("dockWidgetContentsModelSourcesEditor") self.dockWidgetModelSourcesEditor.setWidget(self.dockWidgetContentsModelSourcesEditor) self.dockWidgetModelSourcesEditor.setHidden(False) self.dockWidgetSceneEditor = QtWidgets.QDockWidget(self) self.dockWidgetSceneEditor.setWindowTitle('Scene Editor') self.dockWidgetSceneEditor.setObjectName("dockWidgetSceneEditor") self.dockWidgetContentsSceneEditor = SceneEditorWidget() self.dockWidgetContentsSceneEditor.setObjectName("dockWidgetContentsSceneEditor") self.dockWidgetSceneEditor.setWidget(self.dockWidgetContentsSceneEditor) self.dockWidgetSceneEditor.setHidden(True) self.dockWidgetSceneviewerEditor = QtWidgets.QDockWidget(self) self.dockWidgetSceneviewerEditor.setWindowTitle('Sceneviewer Editor') self.dockWidgetSceneviewerEditor.setObjectName("dockWidgetSceneviewerEditor") self.dockWidgetContentsSceneviewerEditor = SceneviewerEditorWidget(self.dockWidgetSceneviewerEditor) self.dockWidgetContentsSceneviewerEditor.setObjectName("dockWidgetContentsSceneviewerEditor") self.dockWidgetSceneviewerEditor.setWidget(self.dockWidgetContentsSceneviewerEditor) self.dockWidgetSceneviewerEditor.setHidden(True) self.dockWidgetSceneviewerEditor.visibilityChanged.connect(self.dockWidgetContentsSceneviewerEditor.setEnableUpdates) self.dockWidgetSpectrumEditor = QtWidgets.QDockWidget(self) self.dockWidgetSpectrumEditor.setWindowTitle('Spectrum Editor') self.dockWidgetSpectrumEditor.setObjectName("dockWidgetSpectrumEditor") self.dockWidgetContentsSpectrumEditor = SpectrumEditorWidget(self.dockWidgetSpectrumEditor) self.dockWidgetContentsSpectrumEditor.setObjectName("dockWidgetContentsSpectrumEditor") self.dockWidgetSpectrumEditor.setWidget(self.dockWidgetContentsSpectrumEditor) self.dockWidgetSpectrumEditor.setHidden(True) self.dockWidgetTessellationEditor = QtWidgets.QDockWidget(self) self.dockWidgetTessellationEditor.setWindowTitle('Tessellation Editor') self.dockWidgetTessellationEditor.setObjectName("dockWidgetTessellationEditor") self.dockWidgetContentsTessellationEditor = TessellationEditorWidget() self.dockWidgetContentsTessellationEditor.setObjectName("dockWidgetContentsTessellationEditor") self.dockWidgetTessellationEditor.setWidget(self.dockWidgetContentsTessellationEditor) self.dockWidgetTessellationEditor.setHidden(True) self.dockWidgetTimeEditor = QtWidgets.QDockWidget(self) self.dockWidgetTimeEditor.setWindowTitle('Time Editor') self.dockWidgetTimeEditor.setObjectName("dockWidgetTimeEditor") self.dockWidgetContentsTimeEditor = TimeEditorWidget() self.dockWidgetContentsTimeEditor.setObjectName("dockWidgetContentsTimeEditor") self.dockWidgetTimeEditor.setWidget(self.dockWidgetContentsTimeEditor) self.dockWidgetTimeEditor.setHidden(True) self.dockWidgetFieldEditor = QtWidgets.QDockWidget(self) self.dockWidgetFieldEditor.setWindowTitle('Field Editor') self.dockWidgetFieldEditor.setObjectName("dockWidgetFieldEditor") self.dockWidgetContentsFieldEditor = FieldListEditorWidget() self.dockWidgetContentsFieldEditor.setObjectName("dockWidgetContentsFieldEditor") self.dockWidgetFieldEditor.setWidget(self.dockWidgetContentsFieldEditor) self.dockWidgetFieldEditor.setHidden(True) def _registerEditors(self): self._registerEditor(self._visualisation_view, self.dockWidgetRegionEditor) self._registerEditor(self._visualisation_view, self.dockWidgetMaterialEditor) self._registerEditor(self._visualisation_view, self.dockWidgetModelSourcesEditor) self._registerEditor(self._visualisation_view, self.dockWidgetSceneEditor) self._registerEditor(self._visualisation_view, self.dockWidgetSceneviewerEditor) self._registerEditor(self._visualisation_view, self.dockWidgetSpectrumEditor) self._registerEditor(self._visualisation_view, self.dockWidgetTessellationEditor) self._registerEditor(self._visualisation_view, self.dockWidgetTimeEditor) self._registerEditor(self._visualisation_view, self.dockWidgetFieldEditor) self._ui.menu_View.addSeparator() def _registerEditor(self, view, editor): action_name = getEditorMenuName(view) action = self._getEditorAction(action_name) if action is None: menu = self._ui.menu_View.addMenu(action_name) menu.setEnabled(False) else: menu = action.menu() toggle_action = editor.toggleViewAction() toggle_action.triggered.connect(self._view_dock_widget) menu.addAction(toggle_action) view.registerDependentEditor(editor) def _view_dock_widget(self, show): if show: sender_text = self.sender().text() for tab_bar in self.findChildren(QtWidgets.QTabBar): for index in range(tab_bar.count()): tab_text = tab_bar.tabText(index) if tab_text == sender_text: tab_bar.setCurrentIndex(index) return def _getEditorAction(self, action_name): action = None actions = self._ui.menu_View.actions() existing_actions = [a for a in actions if a.text() == action_name] if existing_actions: action = existing_actions[0] return action def _writeSettings(self): settings = QtCore.QSettings() settings.beginGroup('MainWindow') settings.setValue('location', self._location) settings.setValue('geometry', self.saveGeometry()) settings.setValue('current_view', self._ui.viewStackedWidget.currentIndex()) settings.beginWriteArray('recents') recents = self._model.getRecents() for i, r in enumerate(recents): settings.setArrayIndex(i) settings.setValue('item', r) settings.endArray() settings.endGroup() settings.beginGroup('views') self._storeCurrentView() for key in self._view_states: settings.setValue(key.getName(), self._view_states[key]) settings.endGroup() settings.beginGroup('SnapshotDialog') settings.endGroup() settings.beginGroup('Problems') settings.endGroup() def _readSettings(self): settings = QtCore.QSettings() settings.beginGroup('MainWindow') geometry = settings.value('geometry') if geometry is not None: self.restoreGeometry(geometry) self._location = settings.value('location', QtCore.QDir.homePath()) size = settings.beginReadArray('recents') for i in range(size): settings.setArrayIndex(i) self._addRecent(settings.value('item')) settings.endArray() currentViewIndex = settings.value('current_view', '0') settings.endGroup() settings.beginGroup('views') for key in self._view_states: state = settings.value(key.getName(), '') self._view_states[key] = state settings.endGroup() self._setCurrentView(currentViewIndex) self._postChangeView() settings.beginGroup('SnapshotDialog') settings.endGroup() settings.beginGroup('Problems') settings.endGroup() self._updateUi() def _addRecent(self, recent): actions = self._ui.menu_Open_recent.actions() insert_before_action = actions[0] self._model.addRecent(recent) recent_action = QtWidgets.QAction(self._ui.menu_Open_recent) recent_action.setText(recent) self._ui.menu_Open_recent.insertAction(insert_before_action, recent_action) recent_action.triggered.connect(self._open) def _setCurrentView(self, index): v = self._ui.viewStackedWidget.widget(int(index)) self._changeView(v) self._postChangeView() actions = self._ui.menu_View.actions() for action in actions: if action.data() == v: action.setChecked(True) def _storeCurrentView(self): current_view = self._ui.viewStackedWidget.currentWidget() view_state = self.saveState(VERSION_MAJOR) self._view_states[current_view] = view_state def _preChangeView(self): current_view = self._ui.viewStackedWidget.currentWidget() dependent_editors = current_view.getDependentEditors() view_state = self.saveState(VERSION_MAJOR) self._view_states[current_view] = view_state for ed in dependent_editors: ed.setHidden(True) action_name = getEditorMenuName(current_view) action = self._getEditorAction(action_name) if action is not None: menu = action.menu() menu.setEnabled(False) def _changeView(self, view): self._ui.viewStackedWidget.setCurrentWidget(view) def _postChangeView(self): current_view = self._ui.viewStackedWidget.currentWidget() view_state = self._view_states[current_view] action_name = getEditorMenuName(current_view) action = self._getEditorAction(action_name) if action is not None: menu = action.menu() menu.setEnabled(True) def _setupOtherWindows(self): self.dockWidgetLoggerEditor = QtWidgets.QDockWidget("Log Viewer", self) self.dockWidgetLoggerEditor.setObjectName("dockWidgetLoggerEditor") logger_widget = LoggerEditorWidget(self.dockWidgetLoggerEditor) self.dockWidgetLoggerEditor.setWidget(logger_widget) self.dockWidgetLoggerEditor.setHidden(True) def _registerOtherWindows(self): self._registerOtherWindow(self.dockWidgetLoggerEditor) def _registerOtherWindow(self, editor): action = self._getEditorAction("Other Windows") if action is None: menu = self._ui.menu_View.addMenu("Other Windows") menu.setEnabled(True) else: menu = action.menu() toggle_action = editor.toggleViewAction() toggle_action.triggered.connect(self._view_dock_widget) menu.addAction(toggle_action) def _setupViews(self, views): action_group = QtWidgets.QActionGroup(self) zincContext = self._model.getZincContext() for v in views: self._ui.viewStackedWidget.addWidget(v) v.setZincContext(zincContext) action_view = QtWidgets.QAction(v.getName(), self) action_view.setData(v) action_view.setCheckable(True) action_view.setActionGroup(action_group) action_view.triggered.connect(self._viewTriggered) self._ui.menu_View.addAction(action_view) self._ui.menu_View.addSeparator() def _runSimulationClicked(self): sender = self.sender() if sender == self.dockWidgetContentsProblemEditor: actions = self._ui.menu_View.actions() simulate_action = [a for a in actions if a.text() == self._simulation_view.getName()][0] simulate_action.activate(QtWidgets.QAction.ActionEvent.Trigger) problem = self._model.getDocument().getProject().getProblem() if problem.validate(): self._simulation_view.setProblem(problem) self._simulation_view.setPreferences(self._model.getPreferences()) self._simulation_view.run() else: print('pop up error box') def _visualiseSimulationClicked(self): sender = self.sender() if sender == self.dockWidgetContentsSimulationEditor: actions = self._ui.menu_View.actions() visualise_action = [a for a in actions if a.text() == self._visualisation_view.getName()][0] visualise_action.activate(QtWidgets.QAction.ActionEvent.Trigger) simulation = self._simulation_view.getSimulation() if simulation.validate(): self._model.visualiseSimulation(simulation) else: print('pop up error box') def _viewTriggered(self): v = self.sender().data() self._preChangeView() self._changeView(v) self._postChangeView() def _regionChange(self, changedRegion, treeChange): if treeChange and (changedRegion is self._model.getDocument().getRootRegion()): zincRootRegion = changedRegion.getZincRegion() self._visualisation_view.setScene(zincRootRegion.getScene()) def _onDocumentChanged(self): document = self._model.getDocument() rootRegion = document.getRootRegion() rootRegion.connectRegionChange(self._regionChange) zincRootRegion = rootRegion.getZincRegion() zincContext = document.getZincContext() self._visualisation_view.setZincContext(zincContext) self.dockWidgetContentsSpectrumEditor.setSpectrums(document.getSpectrums()) self.dockWidgetContentsMaterialEditor.setMaterials(document.getMaterials()) self.dockWidgetContentsTessellationEditor.setTessellations(document.getTessellations()) self.dockWidgetContentsTimeEditor.setZincContext(zincContext) model_sources_model = ModelSourcesModel(document, []) self.dockWidgetContentsModelSourcesEditor.setModelSourcesModel(zincRootRegion, model_sources_model) self.dockWidgetContentsRegionEditor.setRootRegion(rootRegion) self.dockWidgetContentsSceneEditor.setZincRootRegion(zincRootRegion) self.dockWidgetContentsFieldEditor.setRootArgonRegion(rootRegion) self.dockWidgetContentsFieldEditor.setTimekeeper(zincContext.getTimekeepermodule().getDefaultTimekeeper()) if self._visualisation_view_ready: self._restoreSceneviewerState() else: self._visualisation_view_state_update_pending = True def _regionSelected(self, region): zincRegion = region.getZincRegion() self.dockWidgetContentsFieldEditor.setFieldmodule(zincRegion.getFieldmodule()) self.dockWidgetContentsFieldEditor.setArgonRegion(region) def _visualisationViewReady(self): self._visualisation_view_ready = True if self._visualisation_view_state_update_pending: self._restoreSceneviewerState() def _saveTriggered(self): if self._model.getLocation() is None: self._saveAsTriggered() else: self._recordSceneviewerState() self._model.save() def _saveAsTriggered(self): filename, _ = QtWidgets.QFileDialog.getSaveFileName(self, caption='Choose file ...', dir=self._location, filter="Neon Files (*.neon *.json);;All (*.*)") if filename: self._location = os.path.dirname(filename) self._model.setLocation(filename) self._recordSceneviewerState() self._model.save() def _restoreSceneviewerState(self): document = self._model.getDocument() sceneviewer_state = document.getSceneviewer().serialize() self._visualisation_view.setSceneviewerState(sceneviewer_state) self.dockWidgetContentsSceneviewerEditor.setSceneviewer(self._visualisation_view.getSceneviewer()) self._visualisation_view_state_update_pending = False def _recordSceneviewerState(self): sceneviewer_state = self._visualisation_view.getSceneviewerState() document = self._model.getDocument() document.getSceneviewer().deserialize(sceneviewer_state) def _undoRedoStackIndexChanged(self, index): self._model.setCurrentUndoRedoIndex(index) def _aboutTriggered(self): d = AboutDialog(self) d.exec_() def _snapshotDialogReady(self): document = self._model.getDocument() rootRegion = document.getRootRegion() zincRootRegion = rootRegion.getZincRegion() scene = zincRootRegion.getScene() self._snapshot_dialog.setScene(scene) def _snapshotTriggered(self): if self._snapshot_dialog.getLocation() is None and self._location is not None: self._snapshot_dialog.setLocation(self._location) if self._snapshot_dialog.exec_(): if self._location is None: self._location = self._snapshot_dialog.getLocation() filename = self._snapshot_dialog.getFilename() wysiwyg = self._snapshot_dialog.getWYSIWYG() width = self._snapshot_dialog.getWidth() height = self._snapshot_dialog.getHeight() self._visualisation_view.saveImage(filename, wysiwyg, width, height) def _preferencesTriggered(self): if self._preferences_dialog.exec_(): pass def _newTriggered(self): self._model.new() def _openModel(self, filename): success = self._model.load(filename) if success: self._location = os.path.dirname(filename) self._addRecent(filename) else: QtWidgets.QMessageBox.warning(self, "Load failure", "Failed to load file " + filename + ". Refer to logger window for more details", QtWidgets.QMessageBox.Ok) self._model.new() self._updateUi() def _openTriggered(self): filename, _ = QtWidgets.QFileDialog.getOpenFileName(self, caption='Choose file ...', dir=self._location, filter="Neon Files (*.neon *.json);;All (*.*)") if filename: self._openModel(filename) def _open(self): filename = self.sender().text() self._ui.menu_Open_recent.removeAction(self.sender()) self._model.removeRecent(filename) self._openModel(filename) def _clearTriggered(self): self._model.clearRecents() actions = self._ui.menu_Open_recent.actions() for action in actions[:-2]: self._ui.menu_Open_recent.removeAction(action) self._updateUi() def confirmClose(self): if self._model.isModified(): ret = QtWidgets.QMessageBox.warning(self, 'Unsaved Changes', 'You have unsaved changes, would you like to save these changes now?', QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) if ret == QtWidgets.QMessageBox.Yes: self._saveTriggered() def _quitApplication(self): self.confirmClose() self._writeSettings() def closeEvent(self, event): self._quitApplication() super(MainWindow, self).closeEvent(event) def getEditorMenuName(view): return view.getName() + ' Editors'
true
true
f7fe8c9b0817d1ea9a115995a0048e191acfeb38
143
py
Python
web/frontend/urls.py
Comp-490-SeniorProject/site
031a1c25a3cc901fa764d408d795ed12dfebdb00
[ "MIT" ]
null
null
null
web/frontend/urls.py
Comp-490-SeniorProject/site
031a1c25a3cc901fa764d408d795ed12dfebdb00
[ "MIT" ]
38
2021-10-12T21:49:57.000Z
2022-03-29T22:53:26.000Z
web/frontend/urls.py
Comp-490-SeniorProject/site
031a1c25a3cc901fa764d408d795ed12dfebdb00
[ "MIT" ]
1
2021-12-07T03:49:49.000Z
2021-12-07T03:49:49.000Z
from django.urls import path from web.frontend import views app_name = "frontend" urlpatterns = [ path("", views.index, name="index"), ]
15.888889
40
0.699301
from django.urls import path from web.frontend import views app_name = "frontend" urlpatterns = [ path("", views.index, name="index"), ]
true
true
f7fe8ce8eddcdb18d69171a8b4ebc832e2c2dee9
10,123
py
Python
tests/integration/backward_compatible/proxy/ringbuffer_test.py
tonytheonlypony/hazelcast-python-client
3aafeaf2ebc05aee4f2386c62c079db496a7c81f
[ "Apache-2.0" ]
98
2015-12-08T14:26:27.000Z
2022-03-23T17:44:11.000Z
tests/integration/backward_compatible/proxy/ringbuffer_test.py
tonytheonlypony/hazelcast-python-client
3aafeaf2ebc05aee4f2386c62c079db496a7c81f
[ "Apache-2.0" ]
396
2016-02-23T11:07:55.000Z
2022-03-31T14:26:34.000Z
tests/integration/backward_compatible/proxy/ringbuffer_test.py
tonytheonlypony/hazelcast-python-client
3aafeaf2ebc05aee4f2386c62c079db496a7c81f
[ "Apache-2.0" ]
62
2015-12-09T11:20:53.000Z
2022-01-28T01:30:54.000Z
import os import time import unittest from hazelcast.proxy.ringbuffer import OVERFLOW_POLICY_FAIL, MAX_BATCH_SIZE from hazelcast.serialization.api import IdentifiedDataSerializable from tests.base import SingleMemberTestCase from tests.util import random_string, compare_client_version CAPACITY = 10 class RingBufferTest(SingleMemberTestCase): @classmethod def configure_client(cls, config): config["cluster_name"] = cls.cluster.id return config @classmethod def configure_cluster(cls): path = os.path.abspath(__file__) dir_path = os.path.dirname(path) with open(os.path.join(dir_path, "hazelcast.xml")) as f: return f.read() def setUp(self): self.ringbuffer = self.client.get_ringbuffer( "ClientRingbufferTestWithTTL-" + random_string() ).blocking() def tearDown(self): self.ringbuffer.destroy() def test_capacity(self): self.assertEqual(self.ringbuffer.capacity(), CAPACITY) def test_add_size(self): self.assertEqual(0, self.ringbuffer.add("value")) self.assertEqual(1, self.ringbuffer.add("value")) self.assertEqual(2, self.ringbuffer.add("value")) self.assertEqual(3, self.ringbuffer.size()) def test_add_when_full(self): self.fill_ringbuffer() self.assertEqual(-1, self.ringbuffer.add(CAPACITY + 1, OVERFLOW_POLICY_FAIL)) def test_add_all(self): self.assertEqual(CAPACITY - 1, self.ringbuffer.add_all(list(range(0, CAPACITY)))) def test_add_all_when_full(self): self.assertEqual( -1, self.ringbuffer.add_all(list(range(0, CAPACITY * 2)), OVERFLOW_POLICY_FAIL) ) def test_add_all_when_empty_list(self): with self.assertRaises(AssertionError): self.ringbuffer.add_all([]) def test_add_all_when_too_large_batch(self): with self.assertRaises(AssertionError): self.ringbuffer.add_all(list(range(0, MAX_BATCH_SIZE + 1))) def test_head_sequence(self): self.fill_ringbuffer(CAPACITY * 2) self.assertEqual(CAPACITY, self.ringbuffer.head_sequence()) def test_tail_sequence(self): self.fill_ringbuffer(CAPACITY * 2) self.assertEqual(CAPACITY * 2 - 1, self.ringbuffer.tail_sequence()) def test_remaining_capacity(self): self.fill_ringbuffer(CAPACITY // 2) self.assertEqual(CAPACITY // 2, self.ringbuffer.remaining_capacity()) def test_read_one(self): self.ringbuffer.add("item") self.ringbuffer.add("item-2") self.ringbuffer.add("item-3") self.assertEqual("item", self.ringbuffer.read_one(0)) self.assertEqual("item-2", self.ringbuffer.read_one(1)) self.assertEqual("item-3", self.ringbuffer.read_one(2)) def test_read_one_negative_sequence(self): with self.assertRaises(AssertionError): self.ringbuffer.read_one(-1) def test_read_many(self): self.fill_ringbuffer(CAPACITY) items = self.ringbuffer.read_many(0, 0, CAPACITY) self.assertEqual(items, list(range(0, CAPACITY))) def test_read_many_when_negative_start_seq(self): with self.assertRaises(AssertionError): self.ringbuffer.read_many(-1, 0, CAPACITY) def test_read_many_when_min_count_greater_than_max_count(self): with self.assertRaises(AssertionError): self.ringbuffer.read_many(0, CAPACITY, 0) def test_read_many_when_min_count_greater_than_capacity(self): with self.assertRaises(AssertionError): self.ringbuffer.read_many(0, CAPACITY + 1, CAPACITY + 1) def test_read_many_when_max_count_greater_than_batch_size(self): with self.assertRaises(AssertionError): self.ringbuffer.read_many(0, 0, MAX_BATCH_SIZE + 1) def fill_ringbuffer(self, n=CAPACITY): for x in range(0, n): self.ringbuffer.add(x) def test_str(self): self.assertTrue(str(self.ringbuffer).startswith("Ringbuffer")) @unittest.skipIf( compare_client_version("4.1") < 0, "Tests the features added in 4.1 version of the client" ) class RingbufferReadManyTest(SingleMemberTestCase): @classmethod def configure_client(cls, config): config["cluster_name"] = cls.cluster.id return config @classmethod def configure_cluster(cls): path = os.path.abspath(__file__) dir_path = os.path.dirname(path) with open(os.path.join(dir_path, "hazelcast.xml")) as f: return f.read() def setUp(self): self.ringbuffer = self.client.get_ringbuffer( "ClientRingbufferTestWithTTL-" + random_string() ).blocking() def tearDown(self): self.ringbuffer.destroy() def test_when_start_sequence_is_no_longer_available_gets_clamped(self): self.fill_ringbuffer(item_count=CAPACITY + 1) result_set = self.ringbuffer.read_many(0, 1, CAPACITY) self.assertEqual(CAPACITY, result_set.read_count) self.assertEqual(CAPACITY, result_set.size) self.assertEqual(CAPACITY + 1, result_set.next_sequence_to_read_from) for i in range(1, CAPACITY + 1): self.assertEqual(i, result_set[i - 1]) self.assertEqual(i, result_set.get_sequence(i - 1)) def test_when_start_sequence_is_equal_to_tail_sequence(self): self.fill_ringbuffer() result_set = self.ringbuffer.read_many(CAPACITY - 1, 1, CAPACITY) self.assertEqual(1, result_set.read_count) self.assertEqual(1, result_set.size) self.assertEqual(CAPACITY, result_set.next_sequence_to_read_from) self.assertEqual(CAPACITY - 1, result_set[0]) self.assertEqual(CAPACITY - 1, result_set.get_sequence(0)) def test_when_start_sequence_is_beyond_tail_sequence_then_blocks(self): self.fill_ringbuffer() result_set_future = self.ringbuffer._wrapped.read_many(CAPACITY + 1, 1, CAPACITY) time.sleep(0.5) self.assertFalse(result_set_future.done()) def test_when_min_count_items_are_not_available_then_blocks(self): self.fill_ringbuffer() result_set_future = self.ringbuffer._wrapped.read_many(CAPACITY - 1, 2, 3) time.sleep(0.5) self.assertFalse(result_set_future.done()) def test_when_some_waiting_needed(self): self.fill_ringbuffer() result_set_future = self.ringbuffer._wrapped.read_many(CAPACITY - 1, 2, 3) time.sleep(0.5) self.assertFalse(result_set_future.done()) self.ringbuffer.add(CAPACITY) self.assertTrueEventually(lambda: self.assertTrue(result_set_future.done())) result_set = result_set_future.result() self.assertEqual(2, result_set.read_count) self.assertEqual(2, result_set.size) self.assertEqual(CAPACITY + 1, result_set.next_sequence_to_read_from) self.assertEqual(CAPACITY - 1, result_set[0]) self.assertEqual(CAPACITY - 1, result_set.get_sequence(0)) self.assertEqual(CAPACITY, result_set[1]) self.assertEqual(CAPACITY, result_set.get_sequence(1)) def test_min_zero_when_item_available(self): self.fill_ringbuffer() result_set = self.ringbuffer.read_many(0, 0, 1) self.assertEqual(1, result_set.read_count) self.assertEqual(1, result_set.size) def test_min_zero_when_no_item_available(self): result_set = self.ringbuffer.read_many(0, 0, 1) self.assertEqual(0, result_set.read_count) self.assertEqual(0, result_set.size) def test_max_count(self): # If more results are available than needed, the surplus results # should not be read. self.fill_ringbuffer() max_count = CAPACITY // 2 result_set = self.ringbuffer.read_many(0, 0, max_count) self.assertEqual(max_count, result_set.read_count) self.assertEqual(max_count, result_set.size) self.assertEqual(max_count, result_set.next_sequence_to_read_from) for i in range(max_count): self.assertEqual(i, result_set[i]) self.assertEqual(i, result_set.get_sequence(i)) def test_filter(self): def item_factory(i): if i % 2 == 0: return "good%s" % i return "bad%s" % i self.fill_ringbuffer(item_factory) expected_size = CAPACITY // 2 result_set = self.ringbuffer.read_many(0, 0, CAPACITY, PrefixFilter("good")) self.assertEqual(CAPACITY, result_set.read_count) self.assertEqual(expected_size, result_set.size) self.assertEqual(CAPACITY, result_set.next_sequence_to_read_from) for i in range(expected_size): self.assertEqual(item_factory(i * 2), result_set[i]) self.assertEqual(i * 2, result_set.get_sequence(i)) def test_filter_with_max_count(self): def item_factory(i): if i % 2 == 0: return "good%s" % i return "bad%s" % i self.fill_ringbuffer(item_factory) expected_size = 3 result_set = self.ringbuffer.read_many(0, 0, expected_size, PrefixFilter("good")) self.assertEqual(expected_size * 2 - 1, result_set.read_count) self.assertEqual(expected_size, result_set.size) self.assertEqual(expected_size * 2 - 1, result_set.next_sequence_to_read_from) for i in range(expected_size): self.assertEqual(item_factory(i * 2), result_set[i]) self.assertEqual(i * 2, result_set.get_sequence(i)) def fill_ringbuffer(self, item_factory=lambda i: i, item_count=CAPACITY): for i in range(0, item_count): self.ringbuffer.add(item_factory(i)) class PrefixFilter(IdentifiedDataSerializable): def __init__(self, prefix): self.prefix = prefix def write_data(self, object_data_output): object_data_output.write_string(self.prefix) def read_data(self, object_data_input): self.prefix = object_data_input.read_string() def get_factory_id(self): return 666 def get_class_id(self): return 14
35.149306
94
0.681122
import os import time import unittest from hazelcast.proxy.ringbuffer import OVERFLOW_POLICY_FAIL, MAX_BATCH_SIZE from hazelcast.serialization.api import IdentifiedDataSerializable from tests.base import SingleMemberTestCase from tests.util import random_string, compare_client_version CAPACITY = 10 class RingBufferTest(SingleMemberTestCase): @classmethod def configure_client(cls, config): config["cluster_name"] = cls.cluster.id return config @classmethod def configure_cluster(cls): path = os.path.abspath(__file__) dir_path = os.path.dirname(path) with open(os.path.join(dir_path, "hazelcast.xml")) as f: return f.read() def setUp(self): self.ringbuffer = self.client.get_ringbuffer( "ClientRingbufferTestWithTTL-" + random_string() ).blocking() def tearDown(self): self.ringbuffer.destroy() def test_capacity(self): self.assertEqual(self.ringbuffer.capacity(), CAPACITY) def test_add_size(self): self.assertEqual(0, self.ringbuffer.add("value")) self.assertEqual(1, self.ringbuffer.add("value")) self.assertEqual(2, self.ringbuffer.add("value")) self.assertEqual(3, self.ringbuffer.size()) def test_add_when_full(self): self.fill_ringbuffer() self.assertEqual(-1, self.ringbuffer.add(CAPACITY + 1, OVERFLOW_POLICY_FAIL)) def test_add_all(self): self.assertEqual(CAPACITY - 1, self.ringbuffer.add_all(list(range(0, CAPACITY)))) def test_add_all_when_full(self): self.assertEqual( -1, self.ringbuffer.add_all(list(range(0, CAPACITY * 2)), OVERFLOW_POLICY_FAIL) ) def test_add_all_when_empty_list(self): with self.assertRaises(AssertionError): self.ringbuffer.add_all([]) def test_add_all_when_too_large_batch(self): with self.assertRaises(AssertionError): self.ringbuffer.add_all(list(range(0, MAX_BATCH_SIZE + 1))) def test_head_sequence(self): self.fill_ringbuffer(CAPACITY * 2) self.assertEqual(CAPACITY, self.ringbuffer.head_sequence()) def test_tail_sequence(self): self.fill_ringbuffer(CAPACITY * 2) self.assertEqual(CAPACITY * 2 - 1, self.ringbuffer.tail_sequence()) def test_remaining_capacity(self): self.fill_ringbuffer(CAPACITY // 2) self.assertEqual(CAPACITY // 2, self.ringbuffer.remaining_capacity()) def test_read_one(self): self.ringbuffer.add("item") self.ringbuffer.add("item-2") self.ringbuffer.add("item-3") self.assertEqual("item", self.ringbuffer.read_one(0)) self.assertEqual("item-2", self.ringbuffer.read_one(1)) self.assertEqual("item-3", self.ringbuffer.read_one(2)) def test_read_one_negative_sequence(self): with self.assertRaises(AssertionError): self.ringbuffer.read_one(-1) def test_read_many(self): self.fill_ringbuffer(CAPACITY) items = self.ringbuffer.read_many(0, 0, CAPACITY) self.assertEqual(items, list(range(0, CAPACITY))) def test_read_many_when_negative_start_seq(self): with self.assertRaises(AssertionError): self.ringbuffer.read_many(-1, 0, CAPACITY) def test_read_many_when_min_count_greater_than_max_count(self): with self.assertRaises(AssertionError): self.ringbuffer.read_many(0, CAPACITY, 0) def test_read_many_when_min_count_greater_than_capacity(self): with self.assertRaises(AssertionError): self.ringbuffer.read_many(0, CAPACITY + 1, CAPACITY + 1) def test_read_many_when_max_count_greater_than_batch_size(self): with self.assertRaises(AssertionError): self.ringbuffer.read_many(0, 0, MAX_BATCH_SIZE + 1) def fill_ringbuffer(self, n=CAPACITY): for x in range(0, n): self.ringbuffer.add(x) def test_str(self): self.assertTrue(str(self.ringbuffer).startswith("Ringbuffer")) @unittest.skipIf( compare_client_version("4.1") < 0, "Tests the features added in 4.1 version of the client" ) class RingbufferReadManyTest(SingleMemberTestCase): @classmethod def configure_client(cls, config): config["cluster_name"] = cls.cluster.id return config @classmethod def configure_cluster(cls): path = os.path.abspath(__file__) dir_path = os.path.dirname(path) with open(os.path.join(dir_path, "hazelcast.xml")) as f: return f.read() def setUp(self): self.ringbuffer = self.client.get_ringbuffer( "ClientRingbufferTestWithTTL-" + random_string() ).blocking() def tearDown(self): self.ringbuffer.destroy() def test_when_start_sequence_is_no_longer_available_gets_clamped(self): self.fill_ringbuffer(item_count=CAPACITY + 1) result_set = self.ringbuffer.read_many(0, 1, CAPACITY) self.assertEqual(CAPACITY, result_set.read_count) self.assertEqual(CAPACITY, result_set.size) self.assertEqual(CAPACITY + 1, result_set.next_sequence_to_read_from) for i in range(1, CAPACITY + 1): self.assertEqual(i, result_set[i - 1]) self.assertEqual(i, result_set.get_sequence(i - 1)) def test_when_start_sequence_is_equal_to_tail_sequence(self): self.fill_ringbuffer() result_set = self.ringbuffer.read_many(CAPACITY - 1, 1, CAPACITY) self.assertEqual(1, result_set.read_count) self.assertEqual(1, result_set.size) self.assertEqual(CAPACITY, result_set.next_sequence_to_read_from) self.assertEqual(CAPACITY - 1, result_set[0]) self.assertEqual(CAPACITY - 1, result_set.get_sequence(0)) def test_when_start_sequence_is_beyond_tail_sequence_then_blocks(self): self.fill_ringbuffer() result_set_future = self.ringbuffer._wrapped.read_many(CAPACITY + 1, 1, CAPACITY) time.sleep(0.5) self.assertFalse(result_set_future.done()) def test_when_min_count_items_are_not_available_then_blocks(self): self.fill_ringbuffer() result_set_future = self.ringbuffer._wrapped.read_many(CAPACITY - 1, 2, 3) time.sleep(0.5) self.assertFalse(result_set_future.done()) def test_when_some_waiting_needed(self): self.fill_ringbuffer() result_set_future = self.ringbuffer._wrapped.read_many(CAPACITY - 1, 2, 3) time.sleep(0.5) self.assertFalse(result_set_future.done()) self.ringbuffer.add(CAPACITY) self.assertTrueEventually(lambda: self.assertTrue(result_set_future.done())) result_set = result_set_future.result() self.assertEqual(2, result_set.read_count) self.assertEqual(2, result_set.size) self.assertEqual(CAPACITY + 1, result_set.next_sequence_to_read_from) self.assertEqual(CAPACITY - 1, result_set[0]) self.assertEqual(CAPACITY - 1, result_set.get_sequence(0)) self.assertEqual(CAPACITY, result_set[1]) self.assertEqual(CAPACITY, result_set.get_sequence(1)) def test_min_zero_when_item_available(self): self.fill_ringbuffer() result_set = self.ringbuffer.read_many(0, 0, 1) self.assertEqual(1, result_set.read_count) self.assertEqual(1, result_set.size) def test_min_zero_when_no_item_available(self): result_set = self.ringbuffer.read_many(0, 0, 1) self.assertEqual(0, result_set.read_count) self.assertEqual(0, result_set.size) def test_max_count(self): self.fill_ringbuffer() max_count = CAPACITY // 2 result_set = self.ringbuffer.read_many(0, 0, max_count) self.assertEqual(max_count, result_set.read_count) self.assertEqual(max_count, result_set.size) self.assertEqual(max_count, result_set.next_sequence_to_read_from) for i in range(max_count): self.assertEqual(i, result_set[i]) self.assertEqual(i, result_set.get_sequence(i)) def test_filter(self): def item_factory(i): if i % 2 == 0: return "good%s" % i return "bad%s" % i self.fill_ringbuffer(item_factory) expected_size = CAPACITY // 2 result_set = self.ringbuffer.read_many(0, 0, CAPACITY, PrefixFilter("good")) self.assertEqual(CAPACITY, result_set.read_count) self.assertEqual(expected_size, result_set.size) self.assertEqual(CAPACITY, result_set.next_sequence_to_read_from) for i in range(expected_size): self.assertEqual(item_factory(i * 2), result_set[i]) self.assertEqual(i * 2, result_set.get_sequence(i)) def test_filter_with_max_count(self): def item_factory(i): if i % 2 == 0: return "good%s" % i return "bad%s" % i self.fill_ringbuffer(item_factory) expected_size = 3 result_set = self.ringbuffer.read_many(0, 0, expected_size, PrefixFilter("good")) self.assertEqual(expected_size * 2 - 1, result_set.read_count) self.assertEqual(expected_size, result_set.size) self.assertEqual(expected_size * 2 - 1, result_set.next_sequence_to_read_from) for i in range(expected_size): self.assertEqual(item_factory(i * 2), result_set[i]) self.assertEqual(i * 2, result_set.get_sequence(i)) def fill_ringbuffer(self, item_factory=lambda i: i, item_count=CAPACITY): for i in range(0, item_count): self.ringbuffer.add(item_factory(i)) class PrefixFilter(IdentifiedDataSerializable): def __init__(self, prefix): self.prefix = prefix def write_data(self, object_data_output): object_data_output.write_string(self.prefix) def read_data(self, object_data_input): self.prefix = object_data_input.read_string() def get_factory_id(self): return 666 def get_class_id(self): return 14
true
true
f7fe8d28e8dc1fb58856177bde8fe5f919326feb
6,780
py
Python
bci_framework/framework/widgets/annotations.py
UN-GCPDS/bci-framework-
b51f530967561738dc34752acf6add20cbb02283
[ "BSD-2-Clause" ]
null
null
null
bci_framework/framework/widgets/annotations.py
UN-GCPDS/bci-framework-
b51f530967561738dc34752acf6add20cbb02283
[ "BSD-2-Clause" ]
null
null
null
bci_framework/framework/widgets/annotations.py
UN-GCPDS/bci-framework-
b51f530967561738dc34752acf6add20cbb02283
[ "BSD-2-Clause" ]
null
null
null
""" =========== Annotations =========== """ from datetime import datetime from typing import Optional from PySide6.QtWidgets import QTableWidgetItem ######################################################################## class Annotations: """Widget connected with Kafka to stream messages.""" # ---------------------------------------------------------------------- def __init__(self, parent, core): """Constructor""" self.parent_frame = parent self.core = core self.connect() # ---------------------------------------------------------------------- def set_enable(self, enable): """""" self.parent_frame.pushButton_save_annotation.setEnabled(enable) self.parent_frame.pushButton_save_marker.setEnabled(enable) self.parent_frame.pushButton_save_command.setEnabled(enable) # ---------------------------------------------------------------------- def connect(self) -> None: """Connect events.""" self.parent_frame.pushButton_save_annotation.clicked.connect( self.save_annotation) self.parent_frame.pushButton_save_marker.clicked.connect( self.save_marker) self.parent_frame.pushButton_save_command.clicked.connect( self.save_command) self.parent_frame.pushButton_remove_annotations.clicked.connect(lambda: self.parent_frame.tableWidget_annotations.setRowCount(0)) self.parent_frame.pushButton_remove_markers.clicked.connect(lambda: self.parent_frame.tableWidget_markers.setRowCount(0)) self.parent_frame.pushButton_remove_commands.clicked.connect(lambda: self.parent_frame.tableWidget_commands.setRowCount(0)) # ---------------------------------------------------------------------- def save_annotation(self) -> None: """Write the annotation in the streaming.""" content = self.parent_frame.textEdit_annotations.toPlainText() duration = self.parent_frame.doubleSpinBox_annotation_duration.value() data_ = {'duration': duration, 'description': content, 'onset': datetime.now()} self.core.thread_kafka.produser.send('annotation', data_) # ---------------------------------------------------------------------- def save_marker(self) -> None: """Write the marker in the streaming.""" marker = self.parent_frame.lineEdit_marker.text() data_ = {'marker': marker, 'datetime': datetime.now()} self.core.thread_kafka.produser.send('marker', data_) # ---------------------------------------------------------------------- def save_command(self) -> None: """Write the command in the streaming.""" command = self.parent_frame.lineEdit_command.text() data_ = {'command': command, 'datetime': datetime.now()} self.core.thread_kafka.produser.send('command', data_) # ---------------------------------------------------------------------- def add_annotation(self, onset, duration: str, description: str, action: Optional[bool] = True) -> None: """Write the annotation in the GUI.""" row = self.parent_frame.tableWidget_annotations.rowCount() self.parent_frame.tableWidget_annotations.insertRow(row) item = QTableWidgetItem(onset.strftime("%x %X")) self.parent_frame.tableWidget_annotations.setItem(row, 0, item) item = QTableWidgetItem(f"{duration}") self.parent_frame.tableWidget_annotations.setItem(row, 1, item) item = QTableWidgetItem(description) self.parent_frame.tableWidget_annotations.setItem(row, 2, item) if description == 'start_record': self.core.records.record_signal(True) elif description == 'stop_record': self.core.records.record_signal(False) # ---------------------------------------------------------------------- def add_marker(self, onset: str, marker: str, timestamp: Optional[bool] = True) -> None: """Write the marker in the GUI.""" row = self.parent_frame.tableWidget_markers.rowCount() self.parent_frame.tableWidget_markers.insertRow(row) if timestamp: item = QTableWidgetItem(onset.strftime("%x %X")) else: item = QTableWidgetItem(onset) self.parent_frame.tableWidget_markers.setItem(row, 0, item) item = QTableWidgetItem(f"{marker}") self.parent_frame.tableWidget_markers.setItem(row, 1, item) # ---------------------------------------------------------------------- def add_command(self, onset: str, command: str) -> None: """Write the command in the GUI.""" row = self.parent_frame.tableWidget_commands.rowCount() self.parent_frame.tableWidget_commands.insertRow(row) item = QTableWidgetItem(onset.strftime("%x %X")) self.parent_frame.tableWidget_commands.setItem(row, 0, item) item = QTableWidgetItem(f"{marker}") self.parent_frame.tableWidget_commands.setItem(row, 1, item) # ---------------------------------------------------------------------- def bulk_annotations(self, annotations): """""" columns = ['Onset', 'Duration', 'Description'] self.parent_frame.tableWidget_annotations.clear() self.parent_frame.tableWidget_annotations.setRowCount(0) self.parent_frame.tableWidget_annotations.setColumnCount( len(columns)) self.parent_frame.tableWidget_annotations.setHorizontalHeaderLabels( columns) for onset, duration, description in annotations: if not description in ['start_record', 'stop_record']: self.add_annotation( onset, duration, description, action=False) self.parent_frame.tableWidget_annotations.sortByColumn(0) # ---------------------------------------------------------------------- def bulk_markers(self, markers): """""" columns = ['Datetime', 'Marker'] self.parent_frame.tableWidget_markers.clear() self.parent_frame.tableWidget_markers.setRowCount(0) self.parent_frame.tableWidget_markers.setColumnCount(len(columns)) self.parent_frame.tableWidget_markers.setHorizontalHeaderLabels( columns) for marker in markers: for onset in markers[marker]: self.add_marker(f'{onset/1000:.2f} s', marker, timestamp=False) self.parent_frame.tableWidget_markers.sortByColumn(0)
45.503356
129
0.558112
from datetime import datetime from typing import Optional from PySide6.QtWidgets import QTableWidgetItem t_annotations.setItem(row, 0, item) item = QTableWidgetItem(f"{duration}") self.parent_frame.tableWidget_annotations.setItem(row, 1, item) item = QTableWidgetItem(description) self.parent_frame.tableWidget_annotations.setItem(row, 2, item) if description == 'start_record': self.core.records.record_signal(True) elif description == 'stop_record': self.core.records.record_signal(False) def add_marker(self, onset: str, marker: str, timestamp: Optional[bool] = True) -> None: row = self.parent_frame.tableWidget_markers.rowCount() self.parent_frame.tableWidget_markers.insertRow(row) if timestamp: item = QTableWidgetItem(onset.strftime("%x %X")) else: item = QTableWidgetItem(onset) self.parent_frame.tableWidget_markers.setItem(row, 0, item) item = QTableWidgetItem(f"{marker}") self.parent_frame.tableWidget_markers.setItem(row, 1, item) def add_command(self, onset: str, command: str) -> None: row = self.parent_frame.tableWidget_commands.rowCount() self.parent_frame.tableWidget_commands.insertRow(row) item = QTableWidgetItem(onset.strftime("%x %X")) self.parent_frame.tableWidget_commands.setItem(row, 0, item) item = QTableWidgetItem(f"{marker}") self.parent_frame.tableWidget_commands.setItem(row, 1, item) def bulk_annotations(self, annotations): columns = ['Onset', 'Duration', 'Description'] self.parent_frame.tableWidget_annotations.clear() self.parent_frame.tableWidget_annotations.setRowCount(0) self.parent_frame.tableWidget_annotations.setColumnCount( len(columns)) self.parent_frame.tableWidget_annotations.setHorizontalHeaderLabels( columns) for onset, duration, description in annotations: if not description in ['start_record', 'stop_record']: self.add_annotation( onset, duration, description, action=False) self.parent_frame.tableWidget_annotations.sortByColumn(0) def bulk_markers(self, markers): columns = ['Datetime', 'Marker'] self.parent_frame.tableWidget_markers.clear() self.parent_frame.tableWidget_markers.setRowCount(0) self.parent_frame.tableWidget_markers.setColumnCount(len(columns)) self.parent_frame.tableWidget_markers.setHorizontalHeaderLabels( columns) for marker in markers: for onset in markers[marker]: self.add_marker(f'{onset/1000:.2f} s', marker, timestamp=False) self.parent_frame.tableWidget_markers.sortByColumn(0)
true
true
f7fe8e6b1efe67b3a1d0bed83a9cbf8737d68a1d
2,835
py
Python
facebook_example/member/models.py
BeshoyAtef/StudentsPortal
2df13b92ff3bfb84cc4d5aa8fd844339dabf4643
[ "BSD-3-Clause" ]
null
null
null
facebook_example/member/models.py
BeshoyAtef/StudentsPortal
2df13b92ff3bfb84cc4d5aa8fd844339dabf4643
[ "BSD-3-Clause" ]
null
null
null
facebook_example/member/models.py
BeshoyAtef/StudentsPortal
2df13b92ff3bfb84cc4d5aa8fd844339dabf4643
[ "BSD-3-Clause" ]
null
null
null
from django.conf import settings from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django_facebook.models import FacebookModel, get_user_model from django_facebook.utils import get_profile_model import logging logger = logging.getLogger(__name__) from django_facebook.models import * from django.db import models from django.dispatch.dispatcher import receiver from django_facebook.models import FacebookModel from django.db.models.signals import post_save from django_facebook.utils import get_user_model, get_profile_model from facebook_example import settings try: # There can only be one custom user model defined at the same time if getattr(settings, 'AUTH_USER_MODEL', None) == 'member.CustomFacebookUser': from django.contrib.auth.models import AbstractUser, UserManager class CustomFacebookUser(AbstractUser, FacebookModel): ''' The django 1.5 approach to adding the facebook related fields ''' objects = UserManager() # add any customizations you like state = models.CharField(max_length=255, blank=True, null=True) except ImportError as e: logger.info('Couldnt setup FacebookUser, got error %s', e) pass # Create your models here. class UserProfile(FacebookModel): ''' Inherit the properties from django facebook ''' mobilenumber = models.CharField(max_length=20 , null=True) email2 = models.EmailField(max_length=254, unique=True) user = models.IntegerField(blank=False,unique=True) class MyCustomProfile(models.Model): ''' Inherit the properties from django facebook ''' user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name="profile") mobilenumber = models.CharField(max_length=20 , null=True) email2 = models.EmailField(max_length=254, unique=True) # user_id = models.IntegerField(blank=False,unique=True) @receiver(post_save) def create_profile(sender, instance, created, **kwargs): """Create a matching profile whenever a user object is created.""" if sender == get_user_model(): user = instance profile_model = get_profile_model() if profile_model == UserProfile and created: profile, new = UserProfile.objects.get_or_create(user=instance) # class MyCustomProfile(FacebookModel): # user = models.OneToOneField(settings.AUTH_USER_MODEL) # @receiver(post_save) # def create_profile(sender, instance, created, **kwargs): # # Create a matching profile whenever a user object is created. # if sender == get_user_model(): # user = instance # profile_model = get_profile_model() # if profile_model == MyCustomProfile and created: # profile, new = MyCustomProfile.objects.get_or_create(user=instance)
38.835616
81
0.736508
from django.conf import settings from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django_facebook.models import FacebookModel, get_user_model from django_facebook.utils import get_profile_model import logging logger = logging.getLogger(__name__) from django_facebook.models import * from django.db import models from django.dispatch.dispatcher import receiver from django_facebook.models import FacebookModel from django.db.models.signals import post_save from django_facebook.utils import get_user_model, get_profile_model from facebook_example import settings try: if getattr(settings, 'AUTH_USER_MODEL', None) == 'member.CustomFacebookUser': from django.contrib.auth.models import AbstractUser, UserManager class CustomFacebookUser(AbstractUser, FacebookModel): objects = UserManager() state = models.CharField(max_length=255, blank=True, null=True) except ImportError as e: logger.info('Couldnt setup FacebookUser, got error %s', e) pass class UserProfile(FacebookModel): mobilenumber = models.CharField(max_length=20 , null=True) email2 = models.EmailField(max_length=254, unique=True) user = models.IntegerField(blank=False,unique=True) class MyCustomProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name="profile") mobilenumber = models.CharField(max_length=20 , null=True) email2 = models.EmailField(max_length=254, unique=True) @receiver(post_save) def create_profile(sender, instance, created, **kwargs): if sender == get_user_model(): user = instance profile_model = get_profile_model() if profile_model == UserProfile and created: profile, new = UserProfile.objects.get_or_create(user=instance)
true
true
f7fe905d5e78bb1dbb32471c4cb29305e6d41633
5,220
py
Python
src/lactolyse/analyses/lactate_threshold.py
dblenkus/performance
bae6105812c2f2414d0c10ddd465bf589503f61a
[ "Apache-2.0" ]
1
2020-01-14T20:23:34.000Z
2020-01-14T20:23:34.000Z
src/lactolyse/analyses/lactate_threshold.py
dblenkus/performance
bae6105812c2f2414d0c10ddd465bf589503f61a
[ "Apache-2.0" ]
13
2018-07-21T06:48:45.000Z
2019-05-29T20:57:13.000Z
src/lactolyse/analyses/lactate_threshold.py
dblenkus/performance
bae6105812c2f2414d0c10ddd465bf589503f61a
[ "Apache-2.0" ]
null
null
null
"""Lactate threshold analysis.""" import logging import numpy as np from .base import BaseAnalysis from .utils import FittedPolynomial logger = logging.getLogger(__name__) class LactateThresholdAnalyses(BaseAnalysis): """Lactate threshold analysis.""" name = 'lactate_threshold' template = 'lactate_treshold.tex' def _calculate_dmax_context(self, inputs, lac_poly, hr_poly): """Calculate context for d-max method.""" # If polynomial has a local minimum on the interval (of # measurments), take it as a minimum value. if lac_poly.deriv_roots.size: # If there are two roots, we know (based on the shape of the # polynomial) that first one is maximum and second one is # minimum. min_x = max(lac_poly.deriv_roots) # If the minimum is not on the interval (or it doesn't exist), # we check for the inflection point and take it if it exists. elif lac_poly.deriv_roots.size: # Second derivation of third degree polynomial have exactly # one root (the question is only if it is on the interval). min_x = lac_poly.second_deriv_roots[0] # If both conditions are false, we can just take the start of # the interval, as we know that it is the "most flat" part of # the polynomial on the interval. else: min_x = lac_poly.min_x max_x = lac_poly.max_x # Find the point where polynomial starts to raise - threshold is # 0.3 - and take only real roots (hopefully there is only one). roots = np.roots(lac_poly.poly - (lac_poly.poly(min_x) + 0.3)) roots = roots[np.logical_and(np.isreal(roots), roots > min_x, roots < max_x)] start_x = max(roots).real # Calculate the vector cross product. v_x = np.poly1d(max_x - start_x) v_y = np.poly1d(lac_poly.poly(max_x) - lac_poly.poly(start_x)) u_x = np.poly1d([1, -start_x]) u_y = lac_poly.poly - lac_poly.poly(start_x) cross_z = v_x * u_y - v_y * u_x ftp = np.roots(cross_z.deriv()) ftp = ftp[np.logical_and(ftp > start_x, ftp < max_x)] ftp = ftp[0] return { 'power': ftp, 'start_point': [start_x, lac_poly.poly(start_x)], 'end_point': [max_x, lac_poly.poly(max_x)], 'start_hr': hr_poly.poly(start_x), 'heart_rate': hr_poly.poly(ftp), 'lactate': lac_poly.poly(ftp), } def _calculate_cross_context(self, inputs, lac_poly, hr_poly): """Calculate context for cross method.""" if lac_poly.deriv_roots.size: start_point = min(lac_poly.deriv_roots) else: start_point = inputs['power'][0] max_x = lac_poly.max_x start_line = np.poly1d( np.polyfit( [start_point, start_point + 5], [lac_poly.poly(start_point), lac_poly.poly(start_point + 5)], 1, ) ) end_line = np.poly1d( np.polyfit( [max_x - 5, max_x], [lac_poly.poly(max_x - 5), lac_poly.poly(max_x)], 1 ) ) cross = np.roots(start_line - end_line) power = cross[0] return { 'power': power, 'start_point': [start_point, lac_poly.poly(start_point)], 'end_point': [inputs['power'][-1], lac_poly.poly(inputs['power'][-1])], 'cross': [power, start_line(power)], 'heart_rate': hr_poly.poly(power), 'lactate': lac_poly.poly(power), } def _calculate_at_context(self, inputs, threshold, lac_poly, hr_poly): """Calculate context for at method.""" roots = np.roots(lac_poly.poly - threshold) roots = roots[np.isreal(roots)] roots = filter( lambda val: inputs['power'][0] < val < inputs['power'][-1], roots ) power = list(roots)[0].real return { 'power': power, 'heart_rate': hr_poly.poly(power), 'lactate': lac_poly.poly(power), } def render_context(self, inputs): """Render the context.""" for attr in ['power', 'heart_rate', 'lactate']: if attr not in inputs: raise ValueError("Missing input '{}'.".format(attr)) lac_poly = FittedPolynomial(inputs['power'], inputs['lactate']) hr_poly = FittedPolynomial(inputs['power'], inputs['heart_rate']) return { 'inputs': inputs, 'lac_poly': lac_poly, 'dmax': self._calculate_dmax_context(inputs, lac_poly, hr_poly), 'cross': self._calculate_cross_context(inputs, lac_poly, hr_poly), 'at2': self._calculate_at_context(inputs, 2, lac_poly, hr_poly), 'at4': self._calculate_at_context(inputs, 4, lac_poly, hr_poly), } def get_results(self, context): """Return the result of the analysis.""" return { 'dmax': context['dmax']['power'], 'cross': context['cross']['power'], 'at2': context['at2']['power'], 'at4': context['at4']['power'], }
35.753425
87
0.578544
import logging import numpy as np from .base import BaseAnalysis from .utils import FittedPolynomial logger = logging.getLogger(__name__) class LactateThresholdAnalyses(BaseAnalysis): name = 'lactate_threshold' template = 'lactate_treshold.tex' def _calculate_dmax_context(self, inputs, lac_poly, hr_poly): if lac_poly.deriv_roots.size: min_x = max(lac_poly.deriv_roots) # we check for the inflection point and take it if it exists. elif lac_poly.deriv_roots.size: # Second derivation of third degree polynomial have exactly # one root (the question is only if it is on the interval). min_x = lac_poly.second_deriv_roots[0] # If both conditions are false, we can just take the start of # the interval, as we know that it is the "most flat" part of # the polynomial on the interval. else: min_x = lac_poly.min_x max_x = lac_poly.max_x # Find the point where polynomial starts to raise - threshold is # 0.3 - and take only real roots (hopefully there is only one). roots = np.roots(lac_poly.poly - (lac_poly.poly(min_x) + 0.3)) roots = roots[np.logical_and(np.isreal(roots), roots > min_x, roots < max_x)] start_x = max(roots).real # Calculate the vector cross product. v_x = np.poly1d(max_x - start_x) v_y = np.poly1d(lac_poly.poly(max_x) - lac_poly.poly(start_x)) u_x = np.poly1d([1, -start_x]) u_y = lac_poly.poly - lac_poly.poly(start_x) cross_z = v_x * u_y - v_y * u_x ftp = np.roots(cross_z.deriv()) ftp = ftp[np.logical_and(ftp > start_x, ftp < max_x)] ftp = ftp[0] return { 'power': ftp, 'start_point': [start_x, lac_poly.poly(start_x)], 'end_point': [max_x, lac_poly.poly(max_x)], 'start_hr': hr_poly.poly(start_x), 'heart_rate': hr_poly.poly(ftp), 'lactate': lac_poly.poly(ftp), } def _calculate_cross_context(self, inputs, lac_poly, hr_poly): if lac_poly.deriv_roots.size: start_point = min(lac_poly.deriv_roots) else: start_point = inputs['power'][0] max_x = lac_poly.max_x start_line = np.poly1d( np.polyfit( [start_point, start_point + 5], [lac_poly.poly(start_point), lac_poly.poly(start_point + 5)], 1, ) ) end_line = np.poly1d( np.polyfit( [max_x - 5, max_x], [lac_poly.poly(max_x - 5), lac_poly.poly(max_x)], 1 ) ) cross = np.roots(start_line - end_line) power = cross[0] return { 'power': power, 'start_point': [start_point, lac_poly.poly(start_point)], 'end_point': [inputs['power'][-1], lac_poly.poly(inputs['power'][-1])], 'cross': [power, start_line(power)], 'heart_rate': hr_poly.poly(power), 'lactate': lac_poly.poly(power), } def _calculate_at_context(self, inputs, threshold, lac_poly, hr_poly): roots = np.roots(lac_poly.poly - threshold) roots = roots[np.isreal(roots)] roots = filter( lambda val: inputs['power'][0] < val < inputs['power'][-1], roots ) power = list(roots)[0].real return { 'power': power, 'heart_rate': hr_poly.poly(power), 'lactate': lac_poly.poly(power), } def render_context(self, inputs): for attr in ['power', 'heart_rate', 'lactate']: if attr not in inputs: raise ValueError("Missing input '{}'.".format(attr)) lac_poly = FittedPolynomial(inputs['power'], inputs['lactate']) hr_poly = FittedPolynomial(inputs['power'], inputs['heart_rate']) return { 'inputs': inputs, 'lac_poly': lac_poly, 'dmax': self._calculate_dmax_context(inputs, lac_poly, hr_poly), 'cross': self._calculate_cross_context(inputs, lac_poly, hr_poly), 'at2': self._calculate_at_context(inputs, 2, lac_poly, hr_poly), 'at4': self._calculate_at_context(inputs, 4, lac_poly, hr_poly), } def get_results(self, context): return { 'dmax': context['dmax']['power'], 'cross': context['cross']['power'], 'at2': context['at2']['power'], 'at4': context['at4']['power'], }
true
true
f7fe91bb7fea8e7716c174a498d3d5323bb31a62
5,183
py
Python
recommender6_slopeone.py
nabeeltariq2/res-repo
faa4277b537e1075fa38d79c1a9fa31b0fd8c3af
[ "Apache-2.0" ]
null
null
null
recommender6_slopeone.py
nabeeltariq2/res-repo
faa4277b537e1075fa38d79c1a9fa31b0fd8c3af
[ "Apache-2.0" ]
null
null
null
recommender6_slopeone.py
nabeeltariq2/res-repo
faa4277b537e1075fa38d79c1a9fa31b0fd8c3af
[ "Apache-2.0" ]
null
null
null
# from __future__ import absolute_import, division, print_function, unicode_literals # from surprise import evaluate, print_perf, dump, Reader, Dataset #import algorithms from surprise from surprise import evaluate, print_perf, Reader, Dataset, accuracy # from surprise import KNNBasic, KNNWithMeans, KNNWithZScore, AlgoBase, SlopeOne, CoClustering, NormalPredictor,NMF, SVD, BaselineOnly import time start_time = time.time() from surprise import SlopeOne import numpy as np import pandas as pd from sqlalchemy import create_engine np.random.seed(101) from collections import defaultdict import os, io, sys from sqlalchemy.orm import sessionmaker, scoped_session from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship, backref import config # from surprise import dump # from model import add_pageview # algorithm = NMF(n_epochs=10) def compute_recommendations(user_id, prediction_table, numeric_prediction_table): algo = 'SlopeOne' algorithm = SlopeOne() # add_pageview(user_id=user_id, item_id=None, page="Model Predictions", activity_type="Initialize Predictions - " + algo, rating=None) #pageview engine = create_engine(config.DB_URI, echo=True) session = scoped_session(sessionmaker(bind=engine, autocommit = False, autoflush = False)) #reading in the database df_ratings = pd.read_sql('SELECT * FROM ratings;', con = engine) df_ratings=df_ratings[['user_id','item_id','rating']] df_ratings = df_ratings.dropna() df_ratings = df_ratings.drop_duplicates() df_ratings2 = pd.read_csv('data/ratings.csv', low_memory=False) df_ratings2 = df_ratings2.rename(columns = {'movie_id': 'item_id'}) df_ratings2 = df_ratings2[['user_id','item_id','rating']] df_ratings2 = df_ratings2.dropna() df_ratings2 = df_ratings2.drop_duplicates() df_ratings = pd.concat([df_ratings, df_ratings2], axis=0) reader = Reader(line_format='user item rating', sep=',', rating_scale=(1, 10)) data = Dataset.load_from_df(df_ratings, reader=reader) trainset = data.build_full_trainset() # algorithm = eval(algo + "()")# set the algorithm............................................... algorithm.train(trainset) items = pd.read_sql('SELECT distinct id FROM items;', con = engine) df_user_items = df_ratings.loc[df_ratings['user_id'] == user_id] total_items = items.id.unique() user_items = df_user_items.item_id.unique() # user_id = str(user_id) prediction_items = [x for x in total_items if x not in user_items] predictions = pd.DataFrame(columns=['user_id', 'item_id', 'prediction']) predicted_ratings = [] for i in prediction_items: a = user_id b = i est = algorithm.predict(a, b) predicted_ratings.append(est[3]) predictions['item_id'] = prediction_items predictions['user_id'] = pd.Series([user_id for x in range(len(predictions.index))], index=predictions.index) predictions['prediction'] = predicted_ratings predictions = predictions.sort_values('prediction', ascending=False) test_prediction = predictions predictions = predictions.head(n=10) cols =['pred_1', 'pred_2','pred_3','pred_4', 'pred_5','pred_6','pred_7','pred_8', 'pred_9','pred_10'] df_pred = predictions[['item_id']].T df_pred.columns = cols df_pred['id'] = user_id df_pred = df_pred[['id','pred_1', 'pred_2','pred_3','pred_4', 'pred_5','pred_6','pred_7','pred_8', 'pred_9','pred_10']] df_pred['id'] = df_pred['id'].astype(int) df_pred.to_sql(prediction_table, engine,if_exists='append', index=False)#if_exists='append' session.commit() df_num_ratings = test_prediction df_num_ratings = df_num_ratings.head(n=20) df_num_ratings['algorithm'] = algo df_num_ratings.rename(columns={'prediction':'predicted_rating'}, inplace=True) df_num_ratings.to_sql('numeric_predictions',engine,if_exists='append', index=False)#if_exists='append' session.commit() predcols =['num_1', 'num_2','num_3','num_4', 'num_5','num_6','num_7','num_8', 'num_9','num_10'] df_num_ratings_transpose = predictions[['prediction']].T df_num_ratings_transpose.columns = predcols df_num_ratings_transpose['id'] = user_id df_num_ratings_transpose = df_num_ratings_transpose[['id','num_1', 'num_2','num_3','num_4', 'num_5','num_6','num_7','num_8', 'num_9','num_10']] df_num_ratings_transpose['id'] = df_num_ratings_transpose['id'].astype(int) df_num_ratings_transpose.to_sql(numeric_prediction_table,engine,if_exists='append', index=False)#if_exists='append' session.commit() # add_pageview(user_id=user_id, item_id=None, page="Model Predictions", activity_type="Finish Computing Predictions - " + algo, rating=None) #pageview
28.016216
154
0.65985
from surprise import evaluate, print_perf, Reader, Dataset, accuracy import time start_time = time.time() from surprise import SlopeOne import numpy as np import pandas as pd from sqlalchemy import create_engine np.random.seed(101) from collections import defaultdict import os, io, sys from sqlalchemy.orm import sessionmaker, scoped_session from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship, backref import config def compute_recommendations(user_id, prediction_table, numeric_prediction_table): algo = 'SlopeOne' algorithm = SlopeOne() ngine = create_engine(config.DB_URI, echo=True) session = scoped_session(sessionmaker(bind=engine, autocommit = False, autoflush = False)) df_ratings = pd.read_sql('SELECT * FROM ratings;', con = engine) df_ratings=df_ratings[['user_id','item_id','rating']] df_ratings = df_ratings.dropna() df_ratings = df_ratings.drop_duplicates() df_ratings2 = pd.read_csv('data/ratings.csv', low_memory=False) df_ratings2 = df_ratings2.rename(columns = {'movie_id': 'item_id'}) df_ratings2 = df_ratings2[['user_id','item_id','rating']] df_ratings2 = df_ratings2.dropna() df_ratings2 = df_ratings2.drop_duplicates() df_ratings = pd.concat([df_ratings, df_ratings2], axis=0) reader = Reader(line_format='user item rating', sep=',', rating_scale=(1, 10)) data = Dataset.load_from_df(df_ratings, reader=reader) trainset = data.build_full_trainset() distinct id FROM items;', con = engine) df_user_items = df_ratings.loc[df_ratings['user_id'] == user_id] total_items = items.id.unique() user_items = df_user_items.item_id.unique() prediction_items = [x for x in total_items if x not in user_items] predictions = pd.DataFrame(columns=['user_id', 'item_id', 'prediction']) predicted_ratings = [] for i in prediction_items: a = user_id b = i est = algorithm.predict(a, b) predicted_ratings.append(est[3]) predictions['item_id'] = prediction_items predictions['user_id'] = pd.Series([user_id for x in range(len(predictions.index))], index=predictions.index) predictions['prediction'] = predicted_ratings predictions = predictions.sort_values('prediction', ascending=False) test_prediction = predictions predictions = predictions.head(n=10) cols =['pred_1', 'pred_2','pred_3','pred_4', 'pred_5','pred_6','pred_7','pred_8', 'pred_9','pred_10'] df_pred = predictions[['item_id']].T df_pred.columns = cols df_pred['id'] = user_id df_pred = df_pred[['id','pred_1', 'pred_2','pred_3','pred_4', 'pred_5','pred_6','pred_7','pred_8', 'pred_9','pred_10']] df_pred['id'] = df_pred['id'].astype(int) df_pred.to_sql(prediction_table, engine,if_exists='append', index=False) session.commit() df_num_ratings = test_prediction df_num_ratings = df_num_ratings.head(n=20) df_num_ratings['algorithm'] = algo df_num_ratings.rename(columns={'prediction':'predicted_rating'}, inplace=True) df_num_ratings.to_sql('numeric_predictions',engine,if_exists='append', index=False) session.commit() predcols =['num_1', 'num_2','num_3','num_4', 'num_5','num_6','num_7','num_8', 'num_9','num_10'] df_num_ratings_transpose = predictions[['prediction']].T df_num_ratings_transpose.columns = predcols df_num_ratings_transpose['id'] = user_id df_num_ratings_transpose = df_num_ratings_transpose[['id','num_1', 'num_2','num_3','num_4', 'num_5','num_6','num_7','num_8', 'num_9','num_10']] df_num_ratings_transpose['id'] = df_num_ratings_transpose['id'].astype(int) df_num_ratings_transpose.to_sql(numeric_prediction_table,engine,if_exists='append', index=False) session.commit()
true
true
f7fe92de27e332ed4bde871e61045dabc3d46969
957
py
Python
mmgen/datasets/__init__.py
HXWAndCL/mmgeneration
9afb1d740bf56a4ecde5064d5bb2a4e2d777638b
[ "Apache-2.0" ]
1
2021-09-29T02:57:18.000Z
2021-09-29T02:57:18.000Z
mmgen/datasets/__init__.py
HXWAndCL/mmgeneration
9afb1d740bf56a4ecde5064d5bb2a4e2d777638b
[ "Apache-2.0" ]
null
null
null
mmgen/datasets/__init__.py
HXWAndCL/mmgeneration
9afb1d740bf56a4ecde5064d5bb2a4e2d777638b
[ "Apache-2.0" ]
null
null
null
from .builder import build_dataloader, build_dataset from .dataset_wrappers import RepeatDataset from .grow_scale_image_dataset import GrowScaleImgDataset from .paired_image_dataset import PairedImageDataset from .pipelines import (Collect, Compose, Flip, ImageToTensor, LoadImageFromFile, Normalize, Resize, ToTensor) from .quick_test_dataset import QuickTestImageDataset from .samplers import DistributedSampler from .singan_dataset import SinGANDataset from .unconditional_image_dataset import UnconditionalImageDataset from .unpaired_image_dataset import UnpairedImageDataset __all__ = [ 'build_dataloader', 'build_dataset', 'LoadImageFromFile', 'DistributedSampler', 'UnconditionalImageDataset', 'Compose', 'ToTensor', 'ImageToTensor', 'Collect', 'Flip', 'Resize', 'RepeatDataset', 'Normalize', 'GrowScaleImgDataset', 'SinGANDataset', 'PairedImageDataset', 'UnpairedImageDataset', 'QuickTestImageDataset' ]
47.85
79
0.800418
from .builder import build_dataloader, build_dataset from .dataset_wrappers import RepeatDataset from .grow_scale_image_dataset import GrowScaleImgDataset from .paired_image_dataset import PairedImageDataset from .pipelines import (Collect, Compose, Flip, ImageToTensor, LoadImageFromFile, Normalize, Resize, ToTensor) from .quick_test_dataset import QuickTestImageDataset from .samplers import DistributedSampler from .singan_dataset import SinGANDataset from .unconditional_image_dataset import UnconditionalImageDataset from .unpaired_image_dataset import UnpairedImageDataset __all__ = [ 'build_dataloader', 'build_dataset', 'LoadImageFromFile', 'DistributedSampler', 'UnconditionalImageDataset', 'Compose', 'ToTensor', 'ImageToTensor', 'Collect', 'Flip', 'Resize', 'RepeatDataset', 'Normalize', 'GrowScaleImgDataset', 'SinGANDataset', 'PairedImageDataset', 'UnpairedImageDataset', 'QuickTestImageDataset' ]
true
true
f7fe937eb62cc9e180b385fc1e2890b36b572aed
7,616
py
Python
tutorials/misc/plot_ecog.py
mehdikuchi/mne-python
864426c4839bab05fd0d142ee20938c336c0b78e
[ "BSD-3-Clause" ]
null
null
null
tutorials/misc/plot_ecog.py
mehdikuchi/mne-python
864426c4839bab05fd0d142ee20938c336c0b78e
[ "BSD-3-Clause" ]
null
null
null
tutorials/misc/plot_ecog.py
mehdikuchi/mne-python
864426c4839bab05fd0d142ee20938c336c0b78e
[ "BSD-3-Clause" ]
null
null
null
""" .. _tut_working_with_ecog: ====================== Working with ECoG data ====================== MNE supports working with more than just MEG and EEG data. Here we show some of the functions that can be used to facilitate working with electrocorticography (ECoG) data. """ # Authors: Eric Larson <larson.eric.d@gmail.com> # Chris Holdgraf <choldgraf@gmail.com> # Adam Li <adam2392@gmail.com> # # License: BSD (3-clause) import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import mne from mne.viz import plot_alignment, snapshot_brain_montage print(__doc__) # paths to mne datasets - sample ECoG and FreeSurfer subject misc_path = mne.datasets.misc.data_path() sample_path = mne.datasets.sample.data_path() subject = 'sample' subjects_dir = sample_path + '/subjects' ############################################################################### # Let's load some ECoG electrode locations and names, and turn them into # a :class:`mne.channels.DigMontage` class. # First, use pandas to read in the .tsv file. # In this tutorial, the electrode coordinates are assumed to be in meters elec_df = pd.read_csv(misc_path + '/ecog/sample_ecog_electrodes.tsv', sep='\t', header=0, index_col=None) ch_names = elec_df['name'].tolist() ch_coords = elec_df[['x', 'y', 'z']].to_numpy(dtype=float) ch_pos = dict(zip(ch_names, ch_coords)) # Ideally the nasion/LPA/RPA will also be present from the digitization, here # we use fiducials estimated from the subject's FreeSurfer MNI transformation: lpa, nasion, rpa = mne.coreg.get_mni_fiducials( subject, subjects_dir=subjects_dir) lpa, nasion, rpa = lpa['r'], nasion['r'], rpa['r'] ############################################################################### # Now we make a :class:`mne.channels.DigMontage` stating that the ECoG # contacts are in the FreeSurfer surface RAS (i.e., MRI) coordinate system. montage = mne.channels.make_dig_montage( ch_pos, coord_frame='mri', nasion=nasion, lpa=lpa, rpa=rpa) print('Created %s channel positions' % len(ch_names)) ############################################################################### # Now we get the :term:`trans` that transforms from our MRI coordinate system # to the head coordinate frame. This transform will be applied to the # data when applying the montage so that standard plotting functions like # :func:`mne.viz.plot_evoked_topomap` will be aligned properly. trans = mne.channels.compute_native_head_t(montage) print(trans) ############################################################################### # Now that we have our montage, we can load in our corresponding # time-series data and set the montage to the raw data. # first we'll load in the sample dataset raw = mne.io.read_raw_edf(misc_path + '/ecog/sample_ecog.edf') # drop bad channels raw.info['bads'].extend([ch for ch in raw.ch_names if ch not in ch_names]) raw.load_data() raw.drop_channels(raw.info['bads']) raw.crop(0, 2) # just process 2 sec of data for speed # attach montage raw.set_montage(montage) # set channel types to ECoG (instead of EEG) raw.set_channel_types({ch_name: 'ecog' for ch_name in raw.ch_names}) ############################################################################### # We can then plot the locations of our electrodes on our subject's brain. # We'll use :func:`~mne.viz.snapshot_brain_montage` to save the plot as image # data (along with xy positions of each electrode in the image), so that later # we can plot frequency band power on top of it. # # .. note:: These are not real electrodes for this subject, so they # do not align to the cortical surface perfectly. fig = plot_alignment(raw.info, subject=subject, subjects_dir=subjects_dir, surfaces=['pial'], trans=trans, coord_frame='mri') mne.viz.set_3d_view(fig, 200, 70, focalpoint=[0, -0.005, 0.03]) xy, im = snapshot_brain_montage(fig, montage) ############################################################################### # Next, we'll compute the signal power in the gamma (30-90 Hz) and alpha # (8-12 Hz) bands. gamma_power_t = raw.copy().filter(30, 90).apply_hilbert( envelope=True).get_data() alpha_power_t = raw.copy().filter(8, 12).apply_hilbert( envelope=True).get_data() gamma_power = gamma_power_t.mean(axis=-1) alpha_power = alpha_power_t.mean(axis=-1) ############################################################################### # Now let's use matplotlib to overplot frequency band power onto the electrodes # which can be plotted on top of the brain from # :func:`~mne.viz.snapshot_brain_montage`. # Convert from a dictionary to array to plot xy_pts = np.vstack([xy[ch] for ch in raw.info['ch_names']]) # colormap to view spectral power cmap = 'viridis' # Create a 1x2 figure showing the average power in gamma and alpha bands. fig, axs = plt.subplots(1, 2, figsize=(20, 10)) # choose a colormap range wide enough for both frequency bands _gamma_alpha_power = np.concatenate((gamma_power, alpha_power)).flatten() vmin, vmax = np.percentile(_gamma_alpha_power, [10, 90]) for ax, band_power, band in zip(axs, [gamma_power, alpha_power], ['Gamma', 'Alpha']): ax.imshow(im) ax.set_axis_off() sc = ax.scatter(*xy_pts.T, c=band_power, s=200, cmap=cmap, vmin=vmin, vmax=vmax) ax.set_title(f'{band} band power', size='x-large') fig.colorbar(sc, ax=axs) ############################################################################### # Say we want to visualize the evolution of the power in the gamma band, # instead of just plotting the average. We can use # `matplotlib.animation.FuncAnimation` to create an animation and apply this # to the brain figure. # create an initialization and animation function # to pass to FuncAnimation def init(): """Create an empty frame.""" return paths, def animate(i, activity): """Animate the plot.""" paths.set_array(activity[:, i]) return paths, # create the figure and apply the animation of the # gamma frequency band activity fig, ax = plt.subplots(figsize=(10, 10)) ax.imshow(im) ax.set_axis_off() paths = ax.scatter(*xy_pts.T, c=np.zeros(len(xy_pts)), s=200, cmap=cmap, vmin=vmin, vmax=vmax) fig.colorbar(paths, ax=ax) ax.set_title('Gamma frequency over time (Hilbert transform)', size='large') # avoid edge artifacts and decimate, showing just a short chunk show_power = gamma_power_t[:, 100:150] anim = animation.FuncAnimation(fig, animate, init_func=init, fargs=(show_power,), frames=show_power.shape[1], interval=200, blit=True) ############################################################################### # Alternatively, we can project the sensor data to the nearest locations on # the pial surface and visualize that: # sphinx_gallery_thumbnail_number = 4 evoked = mne.EvokedArray(gamma_power_t, raw.info) stc = mne.stc_near_sensors(evoked, trans, subject, subjects_dir=subjects_dir) clim = dict(kind='value', lims=[vmin * 0.9, vmin, vmax]) brain = stc.plot(surface='pial', hemi='both', initial_time=0.68, colormap='viridis', clim=clim, views='parietal', subjects_dir=subjects_dir, size=(600, 600)) # You can save a movie like the one on our documentation website with: # brain.save_movie(time_dilation=20, tmin=0.62, tmax=0.72, # interpolation='linear', framerate=5, # time_viewer=True)
39.666667
79
0.63708
import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import mne from mne.viz import plot_alignment, snapshot_brain_montage print(__doc__) misc_path = mne.datasets.misc.data_path() sample_path = mne.datasets.sample.data_path() subject = 'sample' subjects_dir = sample_path + '/subjects'
true
true
f7fe93d37af27cc8887be6f6e40a9eb3b5215dc7
954
py
Python
kubernetes_asyncio/test/test_admissionregistration_api.py
lsst-sqre/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
[ "Apache-2.0" ]
null
null
null
kubernetes_asyncio/test/test_admissionregistration_api.py
lsst-sqre/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
[ "Apache-2.0" ]
null
null
null
kubernetes_asyncio/test/test_admissionregistration_api.py
lsst-sqre/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: v1.19.15 Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import unittest import kubernetes_asyncio.client from kubernetes_asyncio.client.api.admissionregistration_api import AdmissionregistrationApi # noqa: E501 from kubernetes_asyncio.client.rest import ApiException class TestAdmissionregistrationApi(unittest.TestCase): """AdmissionregistrationApi unit test stubs""" def setUp(self): self.api = kubernetes_asyncio.client.api.admissionregistration_api.AdmissionregistrationApi() # noqa: E501 def tearDown(self): pass def test_get_api_group(self): """Test case for get_api_group """ pass if __name__ == '__main__': unittest.main()
23.85
124
0.737945
from __future__ import absolute_import import unittest import kubernetes_asyncio.client from kubernetes_asyncio.client.api.admissionregistration_api import AdmissionregistrationApi from kubernetes_asyncio.client.rest import ApiException class TestAdmissionregistrationApi(unittest.TestCase): def setUp(self): self.api = kubernetes_asyncio.client.api.admissionregistration_api.AdmissionregistrationApi() def tearDown(self): pass def test_get_api_group(self): pass if __name__ == '__main__': unittest.main()
true
true
f7fe93f298d692c1154a36dc5858a9ef416e0f5f
6,296
py
Python
pyfr/integrators/steppers.py
jappa/PyFR
d99120c1db245c7a2a35c72dae51ea72c49efef5
[ "BSD-3-Clause" ]
null
null
null
pyfr/integrators/steppers.py
jappa/PyFR
d99120c1db245c7a2a35c72dae51ea72c49efef5
[ "BSD-3-Clause" ]
null
null
null
pyfr/integrators/steppers.py
jappa/PyFR
d99120c1db245c7a2a35c72dae51ea72c49efef5
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- from abc import abstractmethod from pyfr.integrators.base import BaseIntegrator from pyfr.util import proxylist class BaseStepper(BaseIntegrator): def __init__(self, *args, **kwargs): super(BaseStepper, self).__init__(*args, **kwargs) backend = self._backend elemats = self._system.ele_banks # Create a proxylist of matrix-banks for each storage register self._regs = regs = [] self._regidx = regidx = [] for i in xrange(self._stepper_nregs): b = proxylist([backend.matrix_bank(em, i) for em in elemats]) regs.append(b) regidx.append(i) # Add kernel cache self._axnpby_kerns = {} def collect_stats(self, stats): super(BaseStepper, self).collect_stats(stats) stats.set('solver-time-integrator', 'nsteps', self.nsteps) stats.set('solver-time-integrator', 'nfevals', self._stepper_nfevals) def _get_axnpby_kerns(self, n): try: return self._axnpby_kerns[n] except KeyError: k = self._kernel('axnpby', nargs=n) # Cache and return self._axnpby_kerns[n] = k return k def _add(self, *args): # Get a suitable set of axnpby kernels axnpby = self._get_axnpby_kerns(len(args)/2) # Bank indices are in odd-numbered arguments self._prepare_reg_banks(*args[1::2]) # Bind and run the axnpby kernels self._queue % axnpby(*args[::2]) class EulerStepper(BaseStepper): stepper_name = 'euler' @property def _stepper_has_errest(self): return False @property def _stepper_nfevals(self): return self.nsteps @property def _stepper_nregs(self): return 2 @property def _stepper_order(self): return 1 def step(self, t, dt): add, negdivf = self._add, self._system ut, f = self._regidx negdivf(ut, f) add(1.0, ut, dt, f) return ut class RK4Stepper(BaseStepper): stepper_name = 'rk4' @property def _stepper_has_errest(self): return False @property def _stepper_nfevals(self): return 4*self.nsteps @property def _stepper_nregs(self): return 3 @property def _stepper_order(self): return 4 def step(self, t, dt): add, negdivf = self._add, self._system # Get the bank indices for each register r0, r1, r2 = self._regidx # Ensure r0 references the bank containing u(t) if r0 != self._idxcurr: r0, r1 = r1, r0 # First stage; r1 = -∇·f(r0) negdivf(r0, r1) # Second stage; r2 = r0 + dt/2*r1; r2 = -∇·f(r2) add(0.0, r2, 1.0, r0, dt/2.0, r1) negdivf(r2, r2) # As no subsequent stages depend on the first stage we can # reuse its register to start accumulating the solution with # r1 = r0 + dt/6*r1 + dt/3*r2 add(dt/6.0, r1, 1.0, r0, dt/3.0, r2) # Third stage; here we reuse the r2 register # r2 = r0 + dt/2*r2 # r2 = -∇·f(r2) add(dt/2.0, r2, 1.0, r0) negdivf(r2, r2) # Accumulate; r1 = r1 + dt/3*r2 add(1.0, r1, dt/3.0, r2) # Fourth stage; again we reuse r2 # r2 = r0 + dt*r2 # r2 = -∇·f(r2) add(dt, r2, 1.0, r0) negdivf(r2, r2) # Final accumulation r1 = r1 + dt/6*r2 = u(t + dt) add(1.0, r1, dt/6.0, r2) # Return the index of the bank containing u(t + dt) return r1 class DOPRI5Stepper(BaseStepper): stepper_name = 'dopri5' @property def _stepper_has_errest(self): return False @property def _stepper_nfevals(self): return 6*self.nsteps + self.nrjctsteps + 1 @property def _stepper_nregs(self): return 7 @property def _stepper_order(self): return 5 def step(self, t, dt): add, negdivf = self._add, self._system # Register bank indices (r0 = u(t); r1..6 = temp RK 'k' stages) r0, r1, r2, r3, r4, r5, r6 = self._regidx # Usually the first stage, -∇·f(r0 = u(t)), is available in # r1 (this is as the scheme is FSAL), except when the last step # was rejected. In this case we compute it here. if not self.nacptchain: negdivf(r0, r1) # Second stage; r2 = r0 + dt/5*r1; r2 = -∇·f(r2) add(0.0, r2, 1.0, r0, dt/5.0, r1) negdivf(r2, r2) # Third stage; r3 = r0 + (3/40)*dt*r1 + (9/40)*dt*r2; r3 = -∇·f(r3) add(0.0, r3, 1.0, r0, 3.0/40.0*dt, r1, 9.0/40.0*dt, r2) negdivf(r3, r3) # Fourth stage # r4 = r0 + (44/45)*dt*r1 + (-56/15)*dt*r2 + (32/9)*dt*r3 # r4 = -∇·f(r4) add(0.0, r4, 1.0, r0, 44.0/45.0*dt, r1, -56.0/15.0*dt, r2, 32.0/9.0*dt, r3) negdivf(r4, r4) # Fifth stage # r5 = r0 + (19372/6561)*dt*r1 + (-25360/2187)*dt*r2 # + (64448/6561)*dt*r3 + (-212/729)*dt*r4 # r5 = -∇·f(r5) add(0.0, r5, 1.0, r0, 19372.0/6561.0*dt, r1, -25360.0/2187.0*dt, r2, 64448.0/6561.0*dt, r3, -212.0/729.0*dt, r4) negdivf(r5, r5) # Sixth stage; as neither the seventh stage nor the solution # coefficients depend on the second stage we are able to reuse its # register here # r2 = r0 + (9017/3168)*dt*r1 + (-355/33)*dt*r2 + (46732/5247)*dt*r3 # + (49/176)*dt*r4 + (-5103/18656)*dt*r5 # r2 = -∇·f(r2) add(-355.0/33.0*dt, r2, 1.0, r0, 9017.0/3168.0*dt, r1, 46732.0/5247.0*dt, r3, 49.0/176.0*dt, r4, -5103.0/18656.0*dt, r5) negdivf(r2, r2) # Seventh stage; note that r2 contains the sixth stage # r0 = r0 + (35/384)*dt*r1 + (500/1113)*dt*r3 + (125/192)*dt*r4 # + (-2187/6784)*dt*r5 + (11/84)*dt*r2 # r6 = -∇·f(r0) add(1.0, r0, 35.0/384.0*dt, r1, 500.0/1113.0*dt, r3, 125.0/192.0*dt, r4, -2187.0/6784.0*dt, r5, 11.0/84.0*dt, r2) negdivf(r0, r6) # Swizzle r1 (first stage) and r6 (seventh stage) self._regidx[1], self._regidx[6] = r6, r1 # Return the index of the bank containing u(t + dt) return r0
28.233184
77
0.548761
from abc import abstractmethod from pyfr.integrators.base import BaseIntegrator from pyfr.util import proxylist class BaseStepper(BaseIntegrator): def __init__(self, *args, **kwargs): super(BaseStepper, self).__init__(*args, **kwargs) backend = self._backend elemats = self._system.ele_banks self._regs = regs = [] self._regidx = regidx = [] for i in xrange(self._stepper_nregs): b = proxylist([backend.matrix_bank(em, i) for em in elemats]) regs.append(b) regidx.append(i) self._axnpby_kerns = {} def collect_stats(self, stats): super(BaseStepper, self).collect_stats(stats) stats.set('solver-time-integrator', 'nsteps', self.nsteps) stats.set('solver-time-integrator', 'nfevals', self._stepper_nfevals) def _get_axnpby_kerns(self, n): try: return self._axnpby_kerns[n] except KeyError: k = self._kernel('axnpby', nargs=n) self._axnpby_kerns[n] = k return k def _add(self, *args): axnpby = self._get_axnpby_kerns(len(args)/2) self._prepare_reg_banks(*args[1::2]) self._queue % axnpby(*args[::2]) class EulerStepper(BaseStepper): stepper_name = 'euler' @property def _stepper_has_errest(self): return False @property def _stepper_nfevals(self): return self.nsteps @property def _stepper_nregs(self): return 2 @property def _stepper_order(self): return 1 def step(self, t, dt): add, negdivf = self._add, self._system ut, f = self._regidx negdivf(ut, f) add(1.0, ut, dt, f) return ut class RK4Stepper(BaseStepper): stepper_name = 'rk4' @property def _stepper_has_errest(self): return False @property def _stepper_nfevals(self): return 4*self.nsteps @property def _stepper_nregs(self): return 3 @property def _stepper_order(self): return 4 def step(self, t, dt): add, negdivf = self._add, self._system r0, r1, r2 = self._regidx if r0 != self._idxcurr: r0, r1 = r1, r0 negdivf(r0, r1) add(0.0, r2, 1.0, r0, dt/2.0, r1) negdivf(r2, r2) add(dt/6.0, r1, 1.0, r0, dt/3.0, r2) add(dt/2.0, r2, 1.0, r0) negdivf(r2, r2) add(1.0, r1, dt/3.0, r2) add(dt, r2, 1.0, r0) negdivf(r2, r2) add(1.0, r1, dt/6.0, r2) return r1 class DOPRI5Stepper(BaseStepper): stepper_name = 'dopri5' @property def _stepper_has_errest(self): return False @property def _stepper_nfevals(self): return 6*self.nsteps + self.nrjctsteps + 1 @property def _stepper_nregs(self): return 7 @property def _stepper_order(self): return 5 def step(self, t, dt): add, negdivf = self._add, self._system r0, r1, r2, r3, r4, r5, r6 = self._regidx if not self.nacptchain: negdivf(r0, r1) add(0.0, r2, 1.0, r0, dt/5.0, r1) negdivf(r2, r2) add(0.0, r3, 1.0, r0, 3.0/40.0*dt, r1, 9.0/40.0*dt, r2) negdivf(r3, r3) add(0.0, r4, 1.0, r0, 44.0/45.0*dt, r1, -56.0/15.0*dt, r2, 32.0/9.0*dt, r3) negdivf(r4, r4) add(0.0, r5, 1.0, r0, 19372.0/6561.0*dt, r1, -25360.0/2187.0*dt, r2, 64448.0/6561.0*dt, r3, -212.0/729.0*dt, r4) negdivf(r5, r5) add(-355.0/33.0*dt, r2, 1.0, r0, 9017.0/3168.0*dt, r1, 46732.0/5247.0*dt, r3, 49.0/176.0*dt, r4, -5103.0/18656.0*dt, r5) negdivf(r2, r2) add(1.0, r0, 35.0/384.0*dt, r1, 500.0/1113.0*dt, r3, 125.0/192.0*dt, r4, -2187.0/6784.0*dt, r5, 11.0/84.0*dt, r2) negdivf(r0, r6) self._regidx[1], self._regidx[6] = r6, r1 return r0
true
true
f7fe9480e9caa5b2addbc0bbda880e1c1b74575c
4,336
py
Python
isi_sdk_8_0/isi_sdk_8_0/models/compatibilities_class_available_available_item.py
mohitjain97/isilon_sdk_python
a371f438f542568edb8cda35e929e6b300b1177c
[ "Unlicense" ]
24
2018-06-22T14:13:23.000Z
2022-03-23T01:21:26.000Z
isi_sdk_8_0/isi_sdk_8_0/models/compatibilities_class_available_available_item.py
mohitjain97/isilon_sdk_python
a371f438f542568edb8cda35e929e6b300b1177c
[ "Unlicense" ]
46
2018-04-30T13:28:22.000Z
2022-03-21T21:11:07.000Z
isi_sdk_8_0/isi_sdk_8_0/models/compatibilities_class_available_available_item.py
mohitjain97/isilon_sdk_python
a371f438f542568edb8cda35e929e6b300b1177c
[ "Unlicense" ]
29
2018-06-19T00:14:04.000Z
2022-02-08T17:51:19.000Z
# coding: utf-8 """ Isilon SDK Isilon SDK - Language bindings for the OneFS API # noqa: E501 OpenAPI spec version: 3 Contact: sdk@isilon.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class CompatibilitiesClassAvailableAvailableItem(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'class_1': 'str', 'class_2': 'str' } attribute_map = { 'class_1': 'class_1', 'class_2': 'class_2' } def __init__(self, class_1=None, class_2=None): # noqa: E501 """CompatibilitiesClassAvailableAvailableItem - a model defined in Swagger""" # noqa: E501 self._class_1 = None self._class_2 = None self.discriminator = None self.class_1 = class_1 self.class_2 = class_2 @property def class_1(self): """Gets the class_1 of this CompatibilitiesClassAvailableAvailableItem. # noqa: E501 The first class in an available compatibility # noqa: E501 :return: The class_1 of this CompatibilitiesClassAvailableAvailableItem. # noqa: E501 :rtype: str """ return self._class_1 @class_1.setter def class_1(self, class_1): """Sets the class_1 of this CompatibilitiesClassAvailableAvailableItem. The first class in an available compatibility # noqa: E501 :param class_1: The class_1 of this CompatibilitiesClassAvailableAvailableItem. # noqa: E501 :type: str """ if class_1 is None: raise ValueError("Invalid value for `class_1`, must not be `None`") # noqa: E501 self._class_1 = class_1 @property def class_2(self): """Gets the class_2 of this CompatibilitiesClassAvailableAvailableItem. # noqa: E501 The second class in an available compatibility # noqa: E501 :return: The class_2 of this CompatibilitiesClassAvailableAvailableItem. # noqa: E501 :rtype: str """ return self._class_2 @class_2.setter def class_2(self, class_2): """Sets the class_2 of this CompatibilitiesClassAvailableAvailableItem. The second class in an available compatibility # noqa: E501 :param class_2: The class_2 of this CompatibilitiesClassAvailableAvailableItem. # noqa: E501 :type: str """ if class_2 is None: raise ValueError("Invalid value for `class_2`, must not be `None`") # noqa: E501 self._class_2 = class_2 def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, CompatibilitiesClassAvailableAvailableItem): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
29.903448
101
0.599631
import pprint import re import six class CompatibilitiesClassAvailableAvailableItem(object): swagger_types = { 'class_1': 'str', 'class_2': 'str' } attribute_map = { 'class_1': 'class_1', 'class_2': 'class_2' } def __init__(self, class_1=None, class_2=None): self._class_1 = None self._class_2 = None self.discriminator = None self.class_1 = class_1 self.class_2 = class_2 @property def class_1(self): return self._class_1 @class_1.setter def class_1(self, class_1): if class_1 is None: raise ValueError("Invalid value for `class_1`, must not be `None`") self._class_1 = class_1 @property def class_2(self): return self._class_2 @class_2.setter def class_2(self, class_2): if class_2 is None: raise ValueError("Invalid value for `class_2`, must not be `None`") self._class_2 = class_2 def to_dict(self): result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): return pprint.pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, CompatibilitiesClassAvailableAvailableItem): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
f7fe9647502d58cc2c2378dd840d093c46e34c6a
480
py
Python
Python/118pascal's_triangle.py
Apocrypse/LeetCode
3ada2605ce8c8f6dadebf37a30c9c00a0d1ede39
[ "MIT" ]
4
2020-03-17T03:08:51.000Z
2022-03-14T17:33:28.000Z
Python/118pascal's_triangle.py
Apocrypse/LeetCode
3ada2605ce8c8f6dadebf37a30c9c00a0d1ede39
[ "MIT" ]
null
null
null
Python/118pascal's_triangle.py
Apocrypse/LeetCode
3ada2605ce8c8f6dadebf37a30c9c00a0d1ede39
[ "MIT" ]
3
2021-04-29T16:51:02.000Z
2022-03-19T17:37:56.000Z
class Solution: def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ if not numRows: return [] pascal = [[1]] row = 1 while row != numRows: cur = pascal[-1] tmp = [1] for i in range(row-1): tmp.append(cur[i]+cur[i+1]) tmp.append(1) pascal.append(tmp) row += 1 return pascal
24
43
0.410417
class Solution: def generate(self, numRows): if not numRows: return [] pascal = [[1]] row = 1 while row != numRows: cur = pascal[-1] tmp = [1] for i in range(row-1): tmp.append(cur[i]+cur[i+1]) tmp.append(1) pascal.append(tmp) row += 1 return pascal
true
true
f7fe966c3b3d70911f2c02b9c929b27cbfc3d656
7,900
py
Python
cms/appresolver.py
aleray/django-cms
9604c580413eadbd746713e27216b33fdb4d9d62
[ "BSD-3-Clause" ]
2
2016-02-19T04:19:22.000Z
2016-02-19T04:19:36.000Z
cms/appresolver.py
bhodorog/django-cms
8b22b400f15b366749101d0041142e5529d5f2d4
[ "BSD-3-Clause" ]
null
null
null
cms/appresolver.py
bhodorog/django-cms
8b22b400f15b366749101d0041142e5529d5f2d4
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- from cms.apphook_pool import apphook_pool from cms.exceptions import NoHomeFound from cms.utils.moderator import get_page_queryset from django.conf import settings from django.conf.urls.defaults import patterns from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import RegexURLResolver, Resolver404, reverse, \ RegexURLPattern from django.utils.importlib import import_module APP_RESOLVERS = [] def clear_app_resolvers(): global APP_RESOLVERS APP_RESOLVERS = [] def applications_page_check(request, current_page=None, path=None): """Tries to find if given path was resolved over application. Applications have higher priority than other cms pages. """ if current_page: return current_page if path is None: # We should get in this branch only if an apphook is active on / # This removes the non-CMS part of the URL. path = request.path.replace(reverse('pages-root'), '', 1) # check if application resolver can resolve this for resolver in APP_RESOLVERS: try: page_id = resolver.resolve_page_id(path) # yes, it is application page page = get_page_queryset(request).get(id=page_id) # If current page was matched, then we have some override for content # from cms, but keep current page. Otherwise return page to which was application assigned. return page except Resolver404: # Raised if the page is not managed by an apphook pass return None class AppRegexURLResolver(RegexURLResolver): page_id = None url_patterns = None def resolve_page_id(self, path): """Resolves requested path similar way how resolve does, but instead of return callback,.. returns page_id to which was application assigned. """ tried = [] match = self.regex.search(path) if match: new_path = path[match.end():] for pattern in self.url_patterns: try: sub_match = pattern.resolve(new_path) except Resolver404, e: if 'tried' in e.args[0]: tried.extend([(pattern.regex.pattern + ' ' + t) for t in e.args[0]['tried']]) elif 'path' in e.args[0]: tried.extend([(pattern.regex.pattern + ' ' + t) for t in e.args[0]['path']]) else: if sub_match: return pattern.page_id tried.append(pattern.regex.pattern) raise Resolver404, {'tried': tried, 'path': new_path} def recurse_patterns(path, pattern_list, page_id): """ Recurse over a list of to-be-hooked patterns for a given path prefix """ newpatterns = [] for pattern in pattern_list: app_pat = pattern.regex.pattern if app_pat.startswith('^'): app_pat = app_pat[1:] regex = r'^%s%s' % (path, app_pat) if isinstance(pattern, RegexURLResolver): # this is an 'include', recurse! resolver = RegexURLResolver(regex, 'cms_appresolver', pattern.default_kwargs, pattern.app_name, pattern.namespace) resolver.page_id = page_id # see lines 243 and 236 of urlresolvers.py to understand the next line resolver._urlconf_module = recurse_patterns(regex, pattern.url_patterns, page_id) else: # Re-do the RegexURLPattern with the new regular expression resolver = RegexURLPattern(regex, pattern.callback, pattern.default_args, pattern.name) resolver.page_id = page_id newpatterns.append(resolver) return newpatterns def _flatten_patterns(patterns): flat = [] for pattern in patterns: if isinstance(pattern, RegexURLResolver): flat += _flatten_patterns(pattern.url_patterns) else: flat.append(pattern) return flat def get_app_urls(urls): for urlconf in urls: if isinstance(urlconf, basestring): mod = import_module(urlconf) if not hasattr(mod, 'urlpatterns'): raise ImproperlyConfigured( "URLConf `%s` has no urlpatterns attribute" % urlconf) yield getattr(mod, 'urlpatterns') else: yield urlconf def get_patterns_for_title(path, title): """ Resolve the urlconf module for a path+title combination Returns a list of url objects. """ app = apphook_pool.get_apphook(title.application_urls) patterns = [] for pattern_list in get_app_urls(app.urls): if not path.endswith('/'): path += '/' page_id = title.page.id patterns += recurse_patterns(path, pattern_list, page_id) patterns = _flatten_patterns(patterns) return patterns def get_app_patterns(): """ Get a list of patterns for all hooked apps. How this works: By looking through all titles with an app hook (application_urls) we find all urlconf modules we have to hook into titles. If we use the ML URL Middleware, we namespace those patterns with the title language. All 'normal' patterns from the urlconf get re-written by prefixing them with the title path and then included into the cms url patterns. """ from cms.models import Title try: current_site = Site.objects.get_current() except Site.DoesNotExist: current_site = None included = [] # we don't have a request here so get_page_queryset() can't be used, # so, if CMS_MODERATOR, use, public() queryset, otherwise # use draft(). This can be done, because url patterns are used just # in frontend is_draft = not settings.CMS_MODERATOR title_qs = Title.objects.filter(page__publisher_is_draft=is_draft, page__site=current_site) if 'cms.middleware.multilingual.MultilingualURLMiddleware' in settings.MIDDLEWARE_CLASSES: use_namespaces = True hooked_applications = {} else: use_namespaces = False hooked_applications = [] # Loop over all titles with an application hooked to them for title in title_qs.exclude(application_urls=None).exclude(application_urls='').select_related(): path = title.path if use_namespaces: mixid = "%s:%s:%s" % (path + "/", title.application_urls, title.language) else: mixid = "%s:%s" % (path + "/", title.application_urls) if mixid in included: # don't add the same thing twice continue if not settings.APPEND_SLASH: path += '/' if use_namespaces: if title.language not in hooked_applications: hooked_applications[title.language] = [] hooked_applications[title.language] += get_patterns_for_title(path, title) else: hooked_applications += get_patterns_for_title(path, title) included.append(mixid) # Build the app patterns to be included in the cms urlconfs app_patterns = [] if use_namespaces: for ns, currentpatterns in hooked_applications.items(): extra_patterns = patterns('', *currentpatterns) resolver = AppRegexURLResolver(r'', 'app_resolver', namespace=ns) resolver.url_patterns = extra_patterns app_patterns.append(resolver) APP_RESOLVERS.append(resolver) else: extra_patterns = patterns('', *hooked_applications) resolver = AppRegexURLResolver(r'', 'app_resolver') resolver.url_patterns = extra_patterns app_patterns.append(resolver) APP_RESOLVERS.append(resolver) return app_patterns
38.349515
103
0.638101
from cms.apphook_pool import apphook_pool from cms.exceptions import NoHomeFound from cms.utils.moderator import get_page_queryset from django.conf import settings from django.conf.urls.defaults import patterns from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import RegexURLResolver, Resolver404, reverse, \ RegexURLPattern from django.utils.importlib import import_module APP_RESOLVERS = [] def clear_app_resolvers(): global APP_RESOLVERS APP_RESOLVERS = [] def applications_page_check(request, current_page=None, path=None): """Tries to find if given path was resolved over application. Applications have higher priority than other cms pages. """ if current_page: return current_page if path is None: path = request.path.replace(reverse('pages-root'), '', 1) for resolver in APP_RESOLVERS: try: page_id = resolver.resolve_page_id(path) page = get_page_queryset(request).get(id=page_id) return page except Resolver404: pass return None class AppRegexURLResolver(RegexURLResolver): page_id = None url_patterns = None def resolve_page_id(self, path): """Resolves requested path similar way how resolve does, but instead of return callback,.. returns page_id to which was application assigned. """ tried = [] match = self.regex.search(path) if match: new_path = path[match.end():] for pattern in self.url_patterns: try: sub_match = pattern.resolve(new_path) except Resolver404, e: if 'tried' in e.args[0]: tried.extend([(pattern.regex.pattern + ' ' + t) for t in e.args[0]['tried']]) elif 'path' in e.args[0]: tried.extend([(pattern.regex.pattern + ' ' + t) for t in e.args[0]['path']]) else: if sub_match: return pattern.page_id tried.append(pattern.regex.pattern) raise Resolver404, {'tried': tried, 'path': new_path} def recurse_patterns(path, pattern_list, page_id): """ Recurse over a list of to-be-hooked patterns for a given path prefix """ newpatterns = [] for pattern in pattern_list: app_pat = pattern.regex.pattern if app_pat.startswith('^'): app_pat = app_pat[1:] regex = r'^%s%s' % (path, app_pat) if isinstance(pattern, RegexURLResolver): resolver = RegexURLResolver(regex, 'cms_appresolver', pattern.default_kwargs, pattern.app_name, pattern.namespace) resolver.page_id = page_id resolver._urlconf_module = recurse_patterns(regex, pattern.url_patterns, page_id) else: resolver = RegexURLPattern(regex, pattern.callback, pattern.default_args, pattern.name) resolver.page_id = page_id newpatterns.append(resolver) return newpatterns def _flatten_patterns(patterns): flat = [] for pattern in patterns: if isinstance(pattern, RegexURLResolver): flat += _flatten_patterns(pattern.url_patterns) else: flat.append(pattern) return flat def get_app_urls(urls): for urlconf in urls: if isinstance(urlconf, basestring): mod = import_module(urlconf) if not hasattr(mod, 'urlpatterns'): raise ImproperlyConfigured( "URLConf `%s` has no urlpatterns attribute" % urlconf) yield getattr(mod, 'urlpatterns') else: yield urlconf def get_patterns_for_title(path, title): """ Resolve the urlconf module for a path+title combination Returns a list of url objects. """ app = apphook_pool.get_apphook(title.application_urls) patterns = [] for pattern_list in get_app_urls(app.urls): if not path.endswith('/'): path += '/' page_id = title.page.id patterns += recurse_patterns(path, pattern_list, page_id) patterns = _flatten_patterns(patterns) return patterns def get_app_patterns(): """ Get a list of patterns for all hooked apps. How this works: By looking through all titles with an app hook (application_urls) we find all urlconf modules we have to hook into titles. If we use the ML URL Middleware, we namespace those patterns with the title language. All 'normal' patterns from the urlconf get re-written by prefixing them with the title path and then included into the cms url patterns. """ from cms.models import Title try: current_site = Site.objects.get_current() except Site.DoesNotExist: current_site = None included = [] is_draft = not settings.CMS_MODERATOR title_qs = Title.objects.filter(page__publisher_is_draft=is_draft, page__site=current_site) if 'cms.middleware.multilingual.MultilingualURLMiddleware' in settings.MIDDLEWARE_CLASSES: use_namespaces = True hooked_applications = {} else: use_namespaces = False hooked_applications = [] for title in title_qs.exclude(application_urls=None).exclude(application_urls='').select_related(): path = title.path if use_namespaces: mixid = "%s:%s:%s" % (path + "/", title.application_urls, title.language) else: mixid = "%s:%s" % (path + "/", title.application_urls) if mixid in included: continue if not settings.APPEND_SLASH: path += '/' if use_namespaces: if title.language not in hooked_applications: hooked_applications[title.language] = [] hooked_applications[title.language] += get_patterns_for_title(path, title) else: hooked_applications += get_patterns_for_title(path, title) included.append(mixid) # Build the app patterns to be included in the cms urlconfs app_patterns = [] if use_namespaces: for ns, currentpatterns in hooked_applications.items(): extra_patterns = patterns('', *currentpatterns) resolver = AppRegexURLResolver(r'', 'app_resolver', namespace=ns) resolver.url_patterns = extra_patterns app_patterns.append(resolver) APP_RESOLVERS.append(resolver) else: extra_patterns = patterns('', *hooked_applications) resolver = AppRegexURLResolver(r'', 'app_resolver') resolver.url_patterns = extra_patterns app_patterns.append(resolver) APP_RESOLVERS.append(resolver) return app_patterns
false
true
f7fe97ef8ffadbac248437d2b382b73b21f70d7c
1,459
py
Python
libweasyl/libweasyl/alembic/versions/eff79a07a88d_use_timestamp_column_for_latest_.py
greysteil/wzl-test
0f863b9e7c58e5861437618bd590126ca323140c
[ "Apache-2.0" ]
1
2019-02-15T04:21:48.000Z
2019-02-15T04:21:48.000Z
libweasyl/libweasyl/alembic/versions/eff79a07a88d_use_timestamp_column_for_latest_.py
kfkitsune/wzl-test
27297ccb42e24d652a29aa82f5a667c7d9a6d8de
[ "Apache-2.0" ]
254
2017-12-23T19:36:43.000Z
2020-04-14T21:46:13.000Z
libweasyl/libweasyl/alembic/versions/eff79a07a88d_use_timestamp_column_for_latest_.py
greysteil/wzl-test
0f863b9e7c58e5861437618bd590126ca323140c
[ "Apache-2.0" ]
1
2017-12-23T18:42:16.000Z
2017-12-23T18:42:16.000Z
"""Use TIMESTAMP column for latest submission Revision ID: eff79a07a88d Revises: 83e6b2a46191 Create Date: 2017-01-08 22:20:43.814375 """ # revision identifiers, used by Alembic. revision = 'eff79a07a88d' down_revision = '83e6b2a46191' from alembic import op import sqlalchemy as sa import libweasyl from libweasyl.legacy import UNIXTIME_OFFSET def upgrade(): op.alter_column( 'profile', 'latest_submission_time', new_column_name='latest_submission_time_old', ) op.add_column( 'profile', sa.Column('latest_submission_time', libweasyl.models.helpers.ArrowColumn(), nullable=False, server_default='epoch'), ) op.execute( "UPDATE profile SET latest_submission_time = TIMESTAMP WITHOUT TIME ZONE 'epoch' + " "(latest_submission_time_old - %d) * INTERVAL '1 second'" % (UNIXTIME_OFFSET,)) op.drop_column('profile', 'latest_submission_time_old') def downgrade(): op.alter_column( 'profile', 'latest_submission_time', new_column_name='latest_submission_time_new', ) op.add_column( 'profile', sa.Column('latest_submission_time', libweasyl.models.helpers.WeasylTimestampColumn(), nullable=False, server_default='0'), ) op.execute( "UPDATE profile SET latest_submission_time = extract(epoch from latest_submission_time_new) + %d" % (UNIXTIME_OFFSET,)) op.drop_column('profile', 'latest_submission_time_new')
29.77551
130
0.708019
revision = 'eff79a07a88d' down_revision = '83e6b2a46191' from alembic import op import sqlalchemy as sa import libweasyl from libweasyl.legacy import UNIXTIME_OFFSET def upgrade(): op.alter_column( 'profile', 'latest_submission_time', new_column_name='latest_submission_time_old', ) op.add_column( 'profile', sa.Column('latest_submission_time', libweasyl.models.helpers.ArrowColumn(), nullable=False, server_default='epoch'), ) op.execute( "UPDATE profile SET latest_submission_time = TIMESTAMP WITHOUT TIME ZONE 'epoch' + " "(latest_submission_time_old - %d) * INTERVAL '1 second'" % (UNIXTIME_OFFSET,)) op.drop_column('profile', 'latest_submission_time_old') def downgrade(): op.alter_column( 'profile', 'latest_submission_time', new_column_name='latest_submission_time_new', ) op.add_column( 'profile', sa.Column('latest_submission_time', libweasyl.models.helpers.WeasylTimestampColumn(), nullable=False, server_default='0'), ) op.execute( "UPDATE profile SET latest_submission_time = extract(epoch from latest_submission_time_new) + %d" % (UNIXTIME_OFFSET,)) op.drop_column('profile', 'latest_submission_time_new')
true
true
f7fe983d9f3c9724263133f0b77deed272534129
1,764
py
Python
src/main/py/ltprg/game/color/properties/get_stim_embeddings.py
forkunited/ltprg
4e40d3571d229023df0f845c68643024e04bc202
[ "MIT" ]
11
2017-08-03T15:42:19.000Z
2021-02-04T12:43:35.000Z
src/main/py/ltprg/game/color/properties/get_stim_embeddings.py
forkunited/ltprg
4e40d3571d229023df0f845c68643024e04bc202
[ "MIT" ]
null
null
null
src/main/py/ltprg/game/color/properties/get_stim_embeddings.py
forkunited/ltprg
4e40d3571d229023df0f845c68643024e04bc202
[ "MIT" ]
1
2021-02-04T12:43:37.000Z
2021-02-04T12:43:37.000Z
from __future__ import division import numpy as np import sys sys.path.append('../../../../../../../../Packages/mungpy/src/main/py/mung/') import torch import torch.nn as nn from torch.autograd import Variable import time from data import DataSet from alexnet import PartialAlexnet, rgb_to_alexnet_input from colorspace_conversions import hsls_to_rgbs def hsl_from_datum(datum, H_fieldname, S_fieldname, L_fieldname): return [datum.get(H_fieldname), datum.get(S_fieldname), datum.get(L_fieldname)] def load_stim_hsls(data_path): D = DataSet.load(data_path) hsls = [] for i in range(len(D)): # target = [pull_hsls(D[i]."state.sTargetH", D[i]."state.sTargetS", # D[i]."state.sTargetL")] colors_this_trial = [hsl_from_datum(D[i], "state.sH_0", "state.sS_0", "state.sL_0"), hsl_from_datum(D[i], "state.sH_1", "state.sS_1", "state.sL_1"), hsl_from_datum(D[i], "state.sH_2", "state.sS_2", "state.sL_2")] for c in colors_this_trial: if not c == [None, None, None]: c = map(int, c) if c not in hsls: hsls.append(c) print '{} Colors'.format(len(hsls)) return hsls def get_stim_alexnet_embeddings(stim_rgbs, stop_layer): alexnet_to_fc6 = PartialAlexnet(stop_layer) print alexnet_to_fc6.model start_time = time.time() embeddings = alexnet_to_fc6.forward(rgb_to_alexnet_input(stim_rgbs[0])) for i in range(1, stim_rgbs.shape[0]): embeddings = torch.cat([embeddings, alexnet_to_fc6.forward( rgb_to_alexnet_input(stim_rgbs[i]))], 0) print 'Time for dataset = {}'.format(time.time()-start_time) embeddings = embeddings.data.numpy() return embeddings if __name__=='__main__': hsls = load_stim_hsls() rgbs = hsls_to_rgbs(hsls) get_stim_alexnet_embeddings(rgbs, 'fc6')
33.283019
76
0.707483
from __future__ import division import numpy as np import sys sys.path.append('../../../../../../../../Packages/mungpy/src/main/py/mung/') import torch import torch.nn as nn from torch.autograd import Variable import time from data import DataSet from alexnet import PartialAlexnet, rgb_to_alexnet_input from colorspace_conversions import hsls_to_rgbs def hsl_from_datum(datum, H_fieldname, S_fieldname, L_fieldname): return [datum.get(H_fieldname), datum.get(S_fieldname), datum.get(L_fieldname)] def load_stim_hsls(data_path): D = DataSet.load(data_path) hsls = [] for i in range(len(D)): colors_this_trial = [hsl_from_datum(D[i], "state.sH_0", "state.sS_0", "state.sL_0"), hsl_from_datum(D[i], "state.sH_1", "state.sS_1", "state.sL_1"), hsl_from_datum(D[i], "state.sH_2", "state.sS_2", "state.sL_2")] for c in colors_this_trial: if not c == [None, None, None]: c = map(int, c) if c not in hsls: hsls.append(c) print '{} Colors'.format(len(hsls)) return hsls def get_stim_alexnet_embeddings(stim_rgbs, stop_layer): alexnet_to_fc6 = PartialAlexnet(stop_layer) print alexnet_to_fc6.model start_time = time.time() embeddings = alexnet_to_fc6.forward(rgb_to_alexnet_input(stim_rgbs[0])) for i in range(1, stim_rgbs.shape[0]): embeddings = torch.cat([embeddings, alexnet_to_fc6.forward( rgb_to_alexnet_input(stim_rgbs[i]))], 0) print 'Time for dataset = {}'.format(time.time()-start_time) embeddings = embeddings.data.numpy() return embeddings if __name__=='__main__': hsls = load_stim_hsls() rgbs = hsls_to_rgbs(hsls) get_stim_alexnet_embeddings(rgbs, 'fc6')
false
true
f7fe988d73b3edc4eb10a7f5ae08663502f160ce
113
py
Python
lib_secure_monitoring_service/report.py
jfuruness/lib_secure_monitoring_service
80748c0be4944427e99f9f4c9ccd47a7fab93936
[ "BSD-3-Clause" ]
null
null
null
lib_secure_monitoring_service/report.py
jfuruness/lib_secure_monitoring_service
80748c0be4944427e99f9f4c9ccd47a7fab93936
[ "BSD-3-Clause" ]
null
null
null
lib_secure_monitoring_service/report.py
jfuruness/lib_secure_monitoring_service
80748c0be4944427e99f9f4c9ccd47a7fab93936
[ "BSD-3-Clause" ]
null
null
null
from typing import NamedTuple class Report(NamedTuple): reporting_asn: int prefix: str as_path: list
18.833333
29
0.734513
from typing import NamedTuple class Report(NamedTuple): reporting_asn: int prefix: str as_path: list
true
true
f7fe99031f3d741c5489abd7cc781ad091f717b3
4,347
py
Python
quant/app/spread_trading/strategies/statistical_arbitrage_strategy.py
williamquant/quant
a5447a5211ac6dbe3f9515788ecb162b94e61418
[ "MIT" ]
1
2022-01-05T09:03:23.000Z
2022-01-05T09:03:23.000Z
quant/app/spread_trading/strategies/statistical_arbitrage_strategy.py
williamquant/quant
a5447a5211ac6dbe3f9515788ecb162b94e61418
[ "MIT" ]
null
null
null
quant/app/spread_trading/strategies/statistical_arbitrage_strategy.py
williamquant/quant
a5447a5211ac6dbe3f9515788ecb162b94e61418
[ "MIT" ]
2
2021-12-27T22:52:50.000Z
2022-01-05T09:03:15.000Z
from quant.trader.utility import BarGenerator, ArrayManager from quant.app.spread_trading import ( SpreadStrategyTemplate, SpreadAlgoTemplate, SpreadData, OrderData, TradeData, TickData, BarData ) class StatisticalArbitrageStrategy(SpreadStrategyTemplate): """""" author = "用Python的交易员" boll_window = 20 boll_dev = 2 max_pos = 10 payup = 10 interval = 5 spread_pos = 0.0 boll_up = 0.0 boll_down = 0.0 boll_mid = 0.0 parameters = [ "boll_window", "boll_dev", "max_pos", "payup", "interval" ] variables = [ "spread_pos", "boll_up", "boll_down", "boll_mid" ] def __init__( self, strategy_engine, strategy_name: str, spread: SpreadData, setting: dict ): """""" super().__init__( strategy_engine, strategy_name, spread, setting ) self.bg = BarGenerator(self.on_spread_bar) self.am = ArrayManager() def on_init(self): """ Callback when strategy is inited. """ self.write_log("策略初始化") self.load_bar(10) def on_start(self): """ Callback when strategy is started. """ self.write_log("策略启动") def on_stop(self): """ Callback when strategy is stopped. """ self.write_log("策略停止") self.put_event() def on_spread_data(self): """ Callback when spread price is updated. """ tick = self.get_spread_tick() self.on_spread_tick(tick) def on_spread_tick(self, tick: TickData): """ Callback when new spread tick data is generated. """ self.bg.update_tick(tick) def on_spread_bar(self, bar: BarData): """ Callback when spread bar data is generated. """ self.stop_all_algos() self.am.update_bar(bar) if not self.am.inited: return self.boll_mid = self.am.sma(self.boll_window) self.boll_up, self.boll_down = self.am.boll( self.boll_window, self.boll_dev) if not self.spread_pos: if bar.close_price >= self.boll_up: self.start_short_algo( bar.close_price - 10, self.max_pos, payup=self.payup, interval=self.interval ) elif bar.close_price <= self.boll_down: self.start_long_algo( bar.close_price + 10, self.max_pos, payup=self.payup, interval=self.interval ) elif self.spread_pos < 0: if bar.close_price <= self.boll_mid: self.start_long_algo( bar.close_price + 10, abs(self.spread_pos), payup=self.payup, interval=self.interval ) else: if bar.close_price >= self.boll_mid: self.start_short_algo( bar.close_price - 10, abs(self.spread_pos), payup=self.payup, interval=self.interval ) self.put_event() def on_spread_pos(self): """ Callback when spread position is updated. """ self.spread_pos = self.get_spread_pos() self.put_event() def on_spread_algo(self, algo: SpreadAlgoTemplate): """ Callback when algo status is updated. """ pass def on_order(self, order: OrderData): """ Callback when order status is updated. """ pass def on_trade(self, trade: TradeData): """ Callback when new trade data is received. """ pass def stop_open_algos(self): """""" if self.buy_algoid: self.stop_algo(self.buy_algoid) if self.short_algoid: self.stop_algo(self.short_algoid) def stop_close_algos(self): """""" if self.sell_algoid: self.stop_algo(self.sell_algoid) if self.cover_algoid: self.stop_algo(self.cover_algoid)
24.016575
59
0.520589
from quant.trader.utility import BarGenerator, ArrayManager from quant.app.spread_trading import ( SpreadStrategyTemplate, SpreadAlgoTemplate, SpreadData, OrderData, TradeData, TickData, BarData ) class StatisticalArbitrageStrategy(SpreadStrategyTemplate): author = "用Python的交易员" boll_window = 20 boll_dev = 2 max_pos = 10 payup = 10 interval = 5 spread_pos = 0.0 boll_up = 0.0 boll_down = 0.0 boll_mid = 0.0 parameters = [ "boll_window", "boll_dev", "max_pos", "payup", "interval" ] variables = [ "spread_pos", "boll_up", "boll_down", "boll_mid" ] def __init__( self, strategy_engine, strategy_name: str, spread: SpreadData, setting: dict ): super().__init__( strategy_engine, strategy_name, spread, setting ) self.bg = BarGenerator(self.on_spread_bar) self.am = ArrayManager() def on_init(self): self.write_log("策略初始化") self.load_bar(10) def on_start(self): self.write_log("策略启动") def on_stop(self): self.write_log("策略停止") self.put_event() def on_spread_data(self): tick = self.get_spread_tick() self.on_spread_tick(tick) def on_spread_tick(self, tick: TickData): self.bg.update_tick(tick) def on_spread_bar(self, bar: BarData): self.stop_all_algos() self.am.update_bar(bar) if not self.am.inited: return self.boll_mid = self.am.sma(self.boll_window) self.boll_up, self.boll_down = self.am.boll( self.boll_window, self.boll_dev) if not self.spread_pos: if bar.close_price >= self.boll_up: self.start_short_algo( bar.close_price - 10, self.max_pos, payup=self.payup, interval=self.interval ) elif bar.close_price <= self.boll_down: self.start_long_algo( bar.close_price + 10, self.max_pos, payup=self.payup, interval=self.interval ) elif self.spread_pos < 0: if bar.close_price <= self.boll_mid: self.start_long_algo( bar.close_price + 10, abs(self.spread_pos), payup=self.payup, interval=self.interval ) else: if bar.close_price >= self.boll_mid: self.start_short_algo( bar.close_price - 10, abs(self.spread_pos), payup=self.payup, interval=self.interval ) self.put_event() def on_spread_pos(self): self.spread_pos = self.get_spread_pos() self.put_event() def on_spread_algo(self, algo: SpreadAlgoTemplate): pass def on_order(self, order: OrderData): pass def on_trade(self, trade: TradeData): pass def stop_open_algos(self): if self.buy_algoid: self.stop_algo(self.buy_algoid) if self.short_algoid: self.stop_algo(self.short_algoid) def stop_close_algos(self): if self.sell_algoid: self.stop_algo(self.sell_algoid) if self.cover_algoid: self.stop_algo(self.cover_algoid)
true
true
f7fe997b27585a66134a2b95f421cc00774696e7
3,878
py
Python
ge_websocket_to_udp.py
bpennypacker/ge_websocket_to_udp
900dcd78c1f526ed0722590175c2d0f6b2e51cb0
[ "MIT" ]
null
null
null
ge_websocket_to_udp.py
bpennypacker/ge_websocket_to_udp
900dcd78c1f526ed0722590175c2d0f6b2e51cb0
[ "MIT" ]
null
null
null
ge_websocket_to_udp.py
bpennypacker/ge_websocket_to_udp
900dcd78c1f526ed0722590175c2d0f6b2e51cb0
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import aiohttp import asyncio from typing import Any, Dict, Tuple import configparser import socket import time from gekitchen import ( EVENT_ADD_APPLIANCE, EVENT_APPLIANCE_STATE_CHANGE, EVENT_APPLIANCE_INITIAL_UPDATE, EVENT_DISCONNECTED, ErdApplianceType, ErdCode, ErdCodeType, ErdOvenCookMode, GeAppliance, GeWebsocketClient ) machine_status = { 0: 'Idle', 1: 'Standby', 2: 'Run', 3: 'Pause', 4: 'EOC', 5: 'DSMDelayRun', 6: 'DelayRun', 7: 'DelayPause', 8: 'DrainTimeout', 128: 'Clean Speak' } machine_type = { ErdApplianceType.DRYER: "DRYER", ErdApplianceType.WASHER: "WASHER" } class GEWebsocketToUDP: def __init__(self): self.sleeper = None self.client = None self.config = None async def log_state_change(self, data: Tuple[GeAppliance, Dict[ErdCodeType, Any]]): """Send state changes via UDP if desireable""" appliance, state_changes = data if not appliance.appliance_type in machine_type: return machine = machine_type[appliance.appliance_type] if not (machine in self.config and self.config[machine]['enabled']): return # state_changes['0x2000'] is machine status if not '0x2000' in state_changes: return b = int.from_bytes(state_changes['0x2000'], "big") ip = socket.gethostbyname(self.config[machine]['host']) if 'prefix' in self.config[machine]: msg = "{}{}".format(self.config[machine]['prefix'], machine_status[b]) else: msg = machine_status[b] sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto(bytes(msg, 'utf-8'), (ip, int(self.config[machine]['port']))) t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print ("{} : {} {}:{} {}".format(t, machine, self.config[machine]['host'], self.config[machine]['port'], msg)) async def do_event_disconnect(self, appliance: GeAppliance): print ("Received disconnect...") self.client.disconnect() self.sleeper.cancel_all() await self.sleeper(10) async def main(self, loop): self.config = configparser.ConfigParser() self.config.read('ge_websocket_to_udp.ini') self.client = GeWebsocketClient(loop, self.config['auth']['username'], self.config['auth']['password']) self.client.add_event_handler(EVENT_APPLIANCE_STATE_CHANGE, self.log_state_change) self.client.add_event_handler(EVENT_DISCONNECTED, self.do_event_disconnect) session = aiohttp.ClientSession() asyncio.ensure_future(self.client.async_get_credentials_and_run(session), loop=loop) await self.sleeper(86400) def make_sleep(self): async def sleeper(delay, result=None, *, loop=None): coro = asyncio.sleep(delay, result=result, loop=loop) task = asyncio.ensure_future(coro) sleeper.tasks.add(task) try: return await task except asyncio.CancelledError: return result finally: sleeper.tasks.remove(task) sleeper.tasks = set() sleeper.cancel_all = lambda: sum(task.cancel() for task in sleeper.tasks) self.sleeper = sleeper if __name__ == '__main__': loop = asyncio.get_event_loop() while True: try: obj = GEWebsocketToUDP() obj.make_sleep() t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print("{}: starting async loop...".format(t)) loop.run_until_complete(obj.main(loop)) except Exception as e: print("Caught exception: {}".format(e)) pass print("loop aborted. Sleeping 300 seconds...") time.sleep(300)
30.535433
118
0.620165
import aiohttp import asyncio from typing import Any, Dict, Tuple import configparser import socket import time from gekitchen import ( EVENT_ADD_APPLIANCE, EVENT_APPLIANCE_STATE_CHANGE, EVENT_APPLIANCE_INITIAL_UPDATE, EVENT_DISCONNECTED, ErdApplianceType, ErdCode, ErdCodeType, ErdOvenCookMode, GeAppliance, GeWebsocketClient ) machine_status = { 0: 'Idle', 1: 'Standby', 2: 'Run', 3: 'Pause', 4: 'EOC', 5: 'DSMDelayRun', 6: 'DelayRun', 7: 'DelayPause', 8: 'DrainTimeout', 128: 'Clean Speak' } machine_type = { ErdApplianceType.DRYER: "DRYER", ErdApplianceType.WASHER: "WASHER" } class GEWebsocketToUDP: def __init__(self): self.sleeper = None self.client = None self.config = None async def log_state_change(self, data: Tuple[GeAppliance, Dict[ErdCodeType, Any]]): appliance, state_changes = data if not appliance.appliance_type in machine_type: return machine = machine_type[appliance.appliance_type] if not (machine in self.config and self.config[machine]['enabled']): return if not '0x2000' in state_changes: return b = int.from_bytes(state_changes['0x2000'], "big") ip = socket.gethostbyname(self.config[machine]['host']) if 'prefix' in self.config[machine]: msg = "{}{}".format(self.config[machine]['prefix'], machine_status[b]) else: msg = machine_status[b] sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto(bytes(msg, 'utf-8'), (ip, int(self.config[machine]['port']))) t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print ("{} : {} {}:{} {}".format(t, machine, self.config[machine]['host'], self.config[machine]['port'], msg)) async def do_event_disconnect(self, appliance: GeAppliance): print ("Received disconnect...") self.client.disconnect() self.sleeper.cancel_all() await self.sleeper(10) async def main(self, loop): self.config = configparser.ConfigParser() self.config.read('ge_websocket_to_udp.ini') self.client = GeWebsocketClient(loop, self.config['auth']['username'], self.config['auth']['password']) self.client.add_event_handler(EVENT_APPLIANCE_STATE_CHANGE, self.log_state_change) self.client.add_event_handler(EVENT_DISCONNECTED, self.do_event_disconnect) session = aiohttp.ClientSession() asyncio.ensure_future(self.client.async_get_credentials_and_run(session), loop=loop) await self.sleeper(86400) def make_sleep(self): async def sleeper(delay, result=None, *, loop=None): coro = asyncio.sleep(delay, result=result, loop=loop) task = asyncio.ensure_future(coro) sleeper.tasks.add(task) try: return await task except asyncio.CancelledError: return result finally: sleeper.tasks.remove(task) sleeper.tasks = set() sleeper.cancel_all = lambda: sum(task.cancel() for task in sleeper.tasks) self.sleeper = sleeper if __name__ == '__main__': loop = asyncio.get_event_loop() while True: try: obj = GEWebsocketToUDP() obj.make_sleep() t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print("{}: starting async loop...".format(t)) loop.run_until_complete(obj.main(loop)) except Exception as e: print("Caught exception: {}".format(e)) pass print("loop aborted. Sleeping 300 seconds...") time.sleep(300)
true
true
f7fe9aad01a1690a720368845f1e56dcab072722
965
py
Python
qiskit/pulse/channels/pulse_channels.py
Sahar2/qiskit-terra
19fbaeb68f2b279c9748384e919e1d1b006860f2
[ "Apache-2.0" ]
22
2019-08-15T04:39:15.000Z
2022-03-06T05:17:04.000Z
qiskit/pulse/channels/pulse_channels.py
Sahar2/qiskit-terra
19fbaeb68f2b279c9748384e919e1d1b006860f2
[ "Apache-2.0" ]
2
2020-10-26T07:12:12.000Z
2021-12-09T16:22:51.000Z
qiskit/pulse/channels/pulse_channels.py
Sahar2/qiskit-terra
19fbaeb68f2b279c9748384e919e1d1b006860f2
[ "Apache-2.0" ]
9
2019-09-05T05:33:00.000Z
2021-10-09T16:04:53.000Z
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Channels support signal output. """ from abc import ABCMeta from .channels import Channel class PulseChannel(Channel, metaclass=ABCMeta): """Base class of Channel supporting pulse output.""" pass class DriveChannel(PulseChannel): """Drive Channel.""" prefix = 'd' class MeasureChannel(PulseChannel): """Measure Channel.""" prefix = 'm' class ControlChannel(PulseChannel): """Control Channel.""" prefix = 'u'
21.931818
77
0.707772
from abc import ABCMeta from .channels import Channel class PulseChannel(Channel, metaclass=ABCMeta): pass class DriveChannel(PulseChannel): prefix = 'd' class MeasureChannel(PulseChannel): prefix = 'm' class ControlChannel(PulseChannel): prefix = 'u'
true
true
f7fe9b079fcbf300b453522cdb00e7dbf5d3dd39
30,168
py
Python
tests/statisticslearning_tests.py
vishalbelsare/abcpy
72d0d31ae3fa531b69ea3fef39c96af6628ee76f
[ "BSD-3-Clause-Clear" ]
89
2017-02-23T23:34:52.000Z
2022-03-25T20:35:17.000Z
tests/statisticslearning_tests.py
vishalbelsare/abcpy
72d0d31ae3fa531b69ea3fef39c96af6628ee76f
[ "BSD-3-Clause-Clear" ]
35
2017-03-31T13:24:52.000Z
2022-01-09T11:31:38.000Z
tests/statisticslearning_tests.py
vishalbelsare/abcpy
72d0d31ae3fa531b69ea3fef39c96af6628ee76f
[ "BSD-3-Clause-Clear" ]
32
2017-03-22T06:27:43.000Z
2021-09-17T15:50:42.000Z
import unittest import numpy as np from abcpy.backends import BackendDummy as Backend from abcpy.continuousmodels import Normal from abcpy.continuousmodels import Uniform from abcpy.statistics import Identity from abcpy.statisticslearning import Semiautomatic, SemiautomaticNN, TripletDistanceLearning, \ ContrastiveDistanceLearning, ExponentialFamilyScoreMatching try: import torch except ImportError: has_torch = False else: has_torch = True from abcpy.NN_utilities.networks import createDefaultNN class SemiautomaticTests(unittest.TestCase): def setUp(self): # define prior and model sigma = Uniform([[10], [20]]) mu = Normal([0, 1]) Y = Normal([mu, sigma]) # define backend self.backend = Backend() # define statistics self.statistics_cal = Identity(degree=3, cross=False) # Initialize statistics learning self.statisticslearning = Semiautomatic([Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1) def test_transformation(self): # Transform statistics extraction self.new_statistics_calculator = self.statisticslearning.get_statistics() # Simulate observed data Obs = Normal([2, 4]) y_obs = Obs.forward_simulate(Obs.get_input_values(), 1)[0].tolist() extracted_statistics = self.new_statistics_calculator.statistics(y_obs) self.assertEqual(np.shape(extracted_statistics), (1, 2)) # NOTE we cannot test this, since the linear regression used uses a random number generator (which we cannot access and is in C). Therefore, our results differ and testing might fail # self.assertLess(extracted_statistics[0,0] - 0.00215507052338, 10e-2) # self.assertLess(extracted_statistics[0,1] - (-0.0058023274456), 10e-2) class SemiautomaticNNTests(unittest.TestCase): def setUp(self): # define prior and model sigma = Uniform([[10], [20]]) mu = Normal([0, 1]) self.Y = Normal([mu, sigma]) # define backend self.backend = Backend() # define statistics self.statistics_cal = Identity(degree=3, cross=False) if has_torch: # Initialize statistics learning self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=100, n_samples_val=100, n_samples_per_param=1, seed=1, n_epochs=2, scale_samples=False, use_tqdm=False) self.statisticslearning2 = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=10, n_samples_val=10, n_samples_per_param=1, seed=1, n_epochs=5, scale_samples=False, use_tqdm=False) # with sample scaler: self.statisticslearning_with_scaler = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=100, n_samples_per_param=1, seed=1, n_epochs=2, scale_samples=True, use_tqdm=False) def test_initialization(self): if not has_torch: self.assertRaises(ImportError, SemiautomaticNN, [self.Y], self.statistics_cal, self.backend) def test_transformation(self): if has_torch: # Transform statistics extraction self.new_statistics_calculator = self.statisticslearning.get_statistics() self.new_statistics_calculator_with_scaler = self.statisticslearning_with_scaler.get_statistics() # Simulate observed data Obs = Normal([2, 4]) y_obs = Obs.forward_simulate(Obs.get_input_values(), 1)[0].tolist() extracted_statistics = self.new_statistics_calculator.statistics(y_obs) self.assertEqual(np.shape(extracted_statistics), (1, 2)) self.assertRaises(RuntimeError, self.new_statistics_calculator.statistics, [np.array([1, 2])]) extracted_statistics = self.new_statistics_calculator_with_scaler.statistics(y_obs) self.assertEqual(np.shape(extracted_statistics), (1, 2)) self.assertRaises(RuntimeError, self.new_statistics_calculator_with_scaler.statistics, [np.array([1, 2])]) def test_errors(self): if has_torch: with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, parameters=np.ones((100, 1))) with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, embedding_net=createDefaultNN(1, 2)) with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, simulations=np.ones((100, 1))) with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, simulations=np.ones((100, 1, 3))) with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, parameters=np.ones((100, 1, 2))) with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, simulations=np.ones((100, 1)), parameters=np.zeros((99, 1))) with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, parameters_val=np.ones((100, 1))) with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, simulations_val=np.ones((100, 1))) with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, simulations_val=np.ones((100, 1, 3))) with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, parameters_val=np.ones((100, 1, 2))) with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, simulations_val=np.ones((100, 1)), parameters_val=np.zeros((99, 1))) with self.assertRaises(TypeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, parameters=[i for i in range(10)], simulations=[i for i in range(10)]) with self.assertRaises(TypeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, parameters_val=[i for i in range(10)], simulations_val=[i for i in range(10)]) with self.assertRaises(RuntimeError): self.statisticslearning2.test_losses = [4, 2, 1] self.statisticslearning2.plot_losses() with self.assertRaises(NotImplementedError): self.statisticslearning.plot_losses(which_losses="foo") def test_plots(self): if has_torch: self.statisticslearning.plot_losses() self.statisticslearning.plot_losses(which_losses="train") self.statisticslearning.plot_losses(which_losses="test") class ContrastiveDistanceLearningTests(unittest.TestCase): def setUp(self): # define prior and model sigma = Uniform([[10], [20]]) mu = Normal([0, 1]) self.Y = Normal([mu, sigma]) # define backend self.backend = Backend() # define statistics self.statistics_cal = Identity(degree=3, cross=False) if has_torch: # Initialize statistics learning self.statisticslearning = ContrastiveDistanceLearning([self.Y], self.statistics_cal, self.backend, n_samples=100, n_samples_val=100, n_samples_per_param=1, seed=1, n_epochs=2, scale_samples=False, use_tqdm=False) # with sample scaler: self.statisticslearning_with_scaler = ContrastiveDistanceLearning([self.Y], self.statistics_cal, self.backend, n_samples=100, n_samples_per_param=1, seed=1, n_epochs=2, scale_samples=True, use_tqdm=False) def test_initialization(self): if not has_torch: self.assertRaises(ImportError, ContrastiveDistanceLearning, [self.Y], self.statistics_cal, self.backend) def test_transformation(self): if has_torch: # Transform statistics extraction self.new_statistics_calculator = self.statisticslearning.get_statistics() self.new_statistics_calculator_with_scaler = self.statisticslearning_with_scaler.get_statistics() # Simulate observed data Obs = Normal([2, 4]) y_obs = Obs.forward_simulate(Obs.get_input_values(), 1)[0].tolist() extracted_statistics = self.new_statistics_calculator.statistics(y_obs) self.assertEqual(np.shape(extracted_statistics), (1, 2)) self.assertRaises(RuntimeError, self.new_statistics_calculator.statistics, [np.array([1, 2])]) extracted_statistics = self.new_statistics_calculator_with_scaler.statistics(y_obs) self.assertEqual(np.shape(extracted_statistics), (1, 2)) self.assertRaises(RuntimeError, self.new_statistics_calculator_with_scaler.statistics, [np.array([1, 2])]) def test_plots(self): if has_torch: self.statisticslearning.plot_losses() self.statisticslearning.plot_losses(which_losses="train") self.statisticslearning.plot_losses(which_losses="test") class TripletDistanceLearningTests(unittest.TestCase): def setUp(self): # define prior and model sigma = Uniform([[10], [20]]) mu = Normal([0, 1]) self.Y = Normal([mu, sigma]) # define backend self.backend = Backend() # define statistics self.statistics_cal = Identity(degree=3, cross=False) if has_torch: # Initialize statistics learning self.statisticslearning = TripletDistanceLearning([self.Y], self.statistics_cal, self.backend, n_samples=100, n_samples_val=100, n_samples_per_param=1, seed=1, n_epochs=2, scale_samples=False, use_tqdm=False) # with sample scaler: self.statisticslearning_with_scaler = TripletDistanceLearning([self.Y], self.statistics_cal, self.backend, scale_samples=True, use_tqdm=False, n_samples=100, n_samples_per_param=1, seed=1, n_epochs=2) def test_initialization(self): if not has_torch: self.assertRaises(ImportError, TripletDistanceLearning, [self.Y], self.statistics_cal, self.backend) def test_transformation(self): if has_torch: # Transform statistics extraction self.new_statistics_calculator = self.statisticslearning.get_statistics() self.new_statistics_calculator_with_scaler = self.statisticslearning_with_scaler.get_statistics() # Simulate observed data Obs = Normal([2, 4]) y_obs = Obs.forward_simulate(Obs.get_input_values(), 1)[0].tolist() extracted_statistics = self.new_statistics_calculator.statistics(y_obs) self.assertEqual(np.shape(extracted_statistics), (1, 2)) self.assertRaises(RuntimeError, self.new_statistics_calculator.statistics, [np.array([1, 2])]) extracted_statistics = self.new_statistics_calculator_with_scaler.statistics(y_obs) self.assertEqual(np.shape(extracted_statistics), (1, 2)) self.assertRaises(RuntimeError, self.new_statistics_calculator_with_scaler.statistics, [np.array([1, 2])]) def test_plots(self): if has_torch: self.statisticslearning.plot_losses() self.statisticslearning.plot_losses(which_losses="train") self.statisticslearning.plot_losses(which_losses="test") class ExponentialFamilyScoreMatchingTests(unittest.TestCase): def setUp(self): # define prior and model sigma = Uniform([[1], [2]]) mu = Normal([0, 1]) self.Y = Normal([mu, sigma]) # define backend self.backend = Backend() # define statistics self.statistics_cal = Identity(degree=3, cross=False) if has_torch: self.statisticslearning_all_defaults = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, use_tqdm=False) self.statisticslearning_no_sliced = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, sliced=False, use_tqdm=False) self.statisticslearning_sphere_noise = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, use_tqdm=False, noise_type="sphere") self.statisticslearning_gaussian_noise = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, use_tqdm=False, noise_type="gaussian") self.statisticslearning_variance_reduction = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, use_tqdm=False, variance_reduction=True) self.statisticslearning_no_bn = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, batch_norm=False, use_tqdm=False) self.statisticslearning_provide_nets = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, simulations_net=createDefaultNN(3, 3)(), parameters_net=createDefaultNN(2, 2)(), use_tqdm=False) self.statisticslearning_embedding_dim = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, embedding_dimension=4, use_tqdm=False) self.statisticslearning_validation_early_stop = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=20, n_samples_val=20, early_stopping=True, use_tqdm=False) self.statisticslearning_scale = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, scale_samples=False, scale_parameters=True, use_tqdm=False) self.statisticslearning_bounds = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, lower_bound_simulations=np.array([-1000, -1000, -1000]), upper_bound_simulations=np.array([1000, 1000, 1000]), use_tqdm=False, seed=1) self.statisticslearning_no_schedulers = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, scheduler_parameters=False, scheduler_simulations=False, use_tqdm=False) self.statisticslearning_lam = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, use_tqdm=False, sliced=False, lam=0.1) def test_initialization(self): if not has_torch: self.assertRaises(ImportError, ExponentialFamilyScoreMatching, [self.Y], self.statistics_cal, self.backend) def test_transformation(self): if has_torch: self.new_statistics_calculator = self.statisticslearning_all_defaults.get_statistics() # with no scaler on data: self.new_statistics_calculator_no_scaler = self.statisticslearning_scale.get_statistics() # with no rescaling of the statistics: self.new_statistics_calculator_no_rescale = self.statisticslearning_all_defaults.get_statistics( rescale_statistics=False) # Simulate observed data Obs = Normal([2, 4]) y_obs = Obs.forward_simulate(Obs.get_input_values(), 1)[0].tolist() extracted_statistics = self.new_statistics_calculator.statistics(y_obs) self.assertEqual(np.shape(extracted_statistics), (1, 2)) extracted_statistics_no_rescale = self.new_statistics_calculator_no_rescale.statistics(y_obs) self.assertEqual(np.shape(extracted_statistics_no_rescale), (1, 2)) self.assertFalse(np.allclose(extracted_statistics_no_rescale, extracted_statistics)) self.assertRaises(RuntimeError, self.new_statistics_calculator.statistics, [np.array([1, 2])]) self.assertRaises(RuntimeError, self.new_statistics_calculator_no_scaler.statistics, [np.array([1, 2])]) def test_errors(self): if has_torch: with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, parameters=np.ones((100, 1))) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, simulations_net=createDefaultNN(1, 3)) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, parameters_net=createDefaultNN(1, 3)) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, noise_type="ciao", use_tqdm=False) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, noise_type="sphere", variance_reduction=True, use_tqdm=False) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, simulations=np.ones((100, 1))) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, simulations=np.ones((100, 1, 3))) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, parameters=np.ones((100, 1, 2))) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, simulations=np.ones((100, 1)), parameters=np.zeros((99, 1))) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, parameters_val=np.ones((100, 1))) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, simulations_val=np.ones((100, 1))) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, simulations_val=np.ones((100, 1, 3))) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, parameters_val=np.ones((100, 1, 2))) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, simulations_val=np.ones((100, 1)), parameters_val=np.zeros((99, 1))) with self.assertRaises(TypeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, parameters=[i for i in range(10)], simulations=[i for i in range(10)]) with self.assertRaises(TypeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, parameters_val=[i for i in range(10)], simulations_val=[i for i in range(10)]) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, lower_bound_simulations=[1, 2, 3]) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, upper_bound_simulations=[1, 2, 3]) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, lower_bound_simulations=np.array([-1000, -1000]), seed=1, upper_bound_simulations=np.array([1000, 1000, 1000])) with self.assertRaises(RuntimeError): self.statisticslearning_all_defaults.test_losses = [4, 2, 1] self.statisticslearning_all_defaults.plot_losses() with self.assertRaises(NotImplementedError): self.statisticslearning_all_defaults.plot_losses(which_losses="foo") def test_plots(self): if has_torch: self.statisticslearning_all_defaults.plot_losses() self.statisticslearning_all_defaults.plot_losses(which_losses="train") self.statisticslearning_all_defaults.plot_losses(which_losses="test") if __name__ == '__main__': unittest.main()
66.157895
190
0.522905
import unittest import numpy as np from abcpy.backends import BackendDummy as Backend from abcpy.continuousmodels import Normal from abcpy.continuousmodels import Uniform from abcpy.statistics import Identity from abcpy.statisticslearning import Semiautomatic, SemiautomaticNN, TripletDistanceLearning, \ ContrastiveDistanceLearning, ExponentialFamilyScoreMatching try: import torch except ImportError: has_torch = False else: has_torch = True from abcpy.NN_utilities.networks import createDefaultNN class SemiautomaticTests(unittest.TestCase): def setUp(self): sigma = Uniform([[10], [20]]) mu = Normal([0, 1]) Y = Normal([mu, sigma]) self.backend = Backend() self.statistics_cal = Identity(degree=3, cross=False) self.statisticslearning = Semiautomatic([Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1) def test_transformation(self): self.new_statistics_calculator = self.statisticslearning.get_statistics() Obs = Normal([2, 4]) y_obs = Obs.forward_simulate(Obs.get_input_values(), 1)[0].tolist() extracted_statistics = self.new_statistics_calculator.statistics(y_obs) self.assertEqual(np.shape(extracted_statistics), (1, 2)) class SemiautomaticNNTests(unittest.TestCase): def setUp(self): sigma = Uniform([[10], [20]]) mu = Normal([0, 1]) self.Y = Normal([mu, sigma]) self.backend = Backend() self.statistics_cal = Identity(degree=3, cross=False) if has_torch: self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=100, n_samples_val=100, n_samples_per_param=1, seed=1, n_epochs=2, scale_samples=False, use_tqdm=False) self.statisticslearning2 = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=10, n_samples_val=10, n_samples_per_param=1, seed=1, n_epochs=5, scale_samples=False, use_tqdm=False) self.statisticslearning_with_scaler = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=100, n_samples_per_param=1, seed=1, n_epochs=2, scale_samples=True, use_tqdm=False) def test_initialization(self): if not has_torch: self.assertRaises(ImportError, SemiautomaticNN, [self.Y], self.statistics_cal, self.backend) def test_transformation(self): if has_torch: self.new_statistics_calculator = self.statisticslearning.get_statistics() self.new_statistics_calculator_with_scaler = self.statisticslearning_with_scaler.get_statistics() Obs = Normal([2, 4]) y_obs = Obs.forward_simulate(Obs.get_input_values(), 1)[0].tolist() extracted_statistics = self.new_statistics_calculator.statistics(y_obs) self.assertEqual(np.shape(extracted_statistics), (1, 2)) self.assertRaises(RuntimeError, self.new_statistics_calculator.statistics, [np.array([1, 2])]) extracted_statistics = self.new_statistics_calculator_with_scaler.statistics(y_obs) self.assertEqual(np.shape(extracted_statistics), (1, 2)) self.assertRaises(RuntimeError, self.new_statistics_calculator_with_scaler.statistics, [np.array([1, 2])]) def test_errors(self): if has_torch: with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, parameters=np.ones((100, 1))) with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, embedding_net=createDefaultNN(1, 2)) with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, simulations=np.ones((100, 1))) with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, simulations=np.ones((100, 1, 3))) with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, parameters=np.ones((100, 1, 2))) with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, simulations=np.ones((100, 1)), parameters=np.zeros((99, 1))) with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, parameters_val=np.ones((100, 1))) with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, simulations_val=np.ones((100, 1))) with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, simulations_val=np.ones((100, 1, 3))) with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, parameters_val=np.ones((100, 1, 2))) with self.assertRaises(RuntimeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, simulations_val=np.ones((100, 1)), parameters_val=np.zeros((99, 1))) with self.assertRaises(TypeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, parameters=[i for i in range(10)], simulations=[i for i in range(10)]) with self.assertRaises(TypeError): self.statisticslearning = SemiautomaticNN([self.Y], self.statistics_cal, self.backend, n_samples=1000, n_samples_per_param=1, seed=1, parameters_val=[i for i in range(10)], simulations_val=[i for i in range(10)]) with self.assertRaises(RuntimeError): self.statisticslearning2.test_losses = [4, 2, 1] self.statisticslearning2.plot_losses() with self.assertRaises(NotImplementedError): self.statisticslearning.plot_losses(which_losses="foo") def test_plots(self): if has_torch: self.statisticslearning.plot_losses() self.statisticslearning.plot_losses(which_losses="train") self.statisticslearning.plot_losses(which_losses="test") class ContrastiveDistanceLearningTests(unittest.TestCase): def setUp(self): sigma = Uniform([[10], [20]]) mu = Normal([0, 1]) self.Y = Normal([mu, sigma]) self.backend = Backend() self.statistics_cal = Identity(degree=3, cross=False) if has_torch: self.statisticslearning = ContrastiveDistanceLearning([self.Y], self.statistics_cal, self.backend, n_samples=100, n_samples_val=100, n_samples_per_param=1, seed=1, n_epochs=2, scale_samples=False, use_tqdm=False) self.statisticslearning_with_scaler = ContrastiveDistanceLearning([self.Y], self.statistics_cal, self.backend, n_samples=100, n_samples_per_param=1, seed=1, n_epochs=2, scale_samples=True, use_tqdm=False) def test_initialization(self): if not has_torch: self.assertRaises(ImportError, ContrastiveDistanceLearning, [self.Y], self.statistics_cal, self.backend) def test_transformation(self): if has_torch: self.new_statistics_calculator = self.statisticslearning.get_statistics() self.new_statistics_calculator_with_scaler = self.statisticslearning_with_scaler.get_statistics() Obs = Normal([2, 4]) y_obs = Obs.forward_simulate(Obs.get_input_values(), 1)[0].tolist() extracted_statistics = self.new_statistics_calculator.statistics(y_obs) self.assertEqual(np.shape(extracted_statistics), (1, 2)) self.assertRaises(RuntimeError, self.new_statistics_calculator.statistics, [np.array([1, 2])]) extracted_statistics = self.new_statistics_calculator_with_scaler.statistics(y_obs) self.assertEqual(np.shape(extracted_statistics), (1, 2)) self.assertRaises(RuntimeError, self.new_statistics_calculator_with_scaler.statistics, [np.array([1, 2])]) def test_plots(self): if has_torch: self.statisticslearning.plot_losses() self.statisticslearning.plot_losses(which_losses="train") self.statisticslearning.plot_losses(which_losses="test") class TripletDistanceLearningTests(unittest.TestCase): def setUp(self): sigma = Uniform([[10], [20]]) mu = Normal([0, 1]) self.Y = Normal([mu, sigma]) self.backend = Backend() self.statistics_cal = Identity(degree=3, cross=False) if has_torch: self.statisticslearning = TripletDistanceLearning([self.Y], self.statistics_cal, self.backend, n_samples=100, n_samples_val=100, n_samples_per_param=1, seed=1, n_epochs=2, scale_samples=False, use_tqdm=False) self.statisticslearning_with_scaler = TripletDistanceLearning([self.Y], self.statistics_cal, self.backend, scale_samples=True, use_tqdm=False, n_samples=100, n_samples_per_param=1, seed=1, n_epochs=2) def test_initialization(self): if not has_torch: self.assertRaises(ImportError, TripletDistanceLearning, [self.Y], self.statistics_cal, self.backend) def test_transformation(self): if has_torch: self.new_statistics_calculator = self.statisticslearning.get_statistics() self.new_statistics_calculator_with_scaler = self.statisticslearning_with_scaler.get_statistics() Obs = Normal([2, 4]) y_obs = Obs.forward_simulate(Obs.get_input_values(), 1)[0].tolist() extracted_statistics = self.new_statistics_calculator.statistics(y_obs) self.assertEqual(np.shape(extracted_statistics), (1, 2)) self.assertRaises(RuntimeError, self.new_statistics_calculator.statistics, [np.array([1, 2])]) extracted_statistics = self.new_statistics_calculator_with_scaler.statistics(y_obs) self.assertEqual(np.shape(extracted_statistics), (1, 2)) self.assertRaises(RuntimeError, self.new_statistics_calculator_with_scaler.statistics, [np.array([1, 2])]) def test_plots(self): if has_torch: self.statisticslearning.plot_losses() self.statisticslearning.plot_losses(which_losses="train") self.statisticslearning.plot_losses(which_losses="test") class ExponentialFamilyScoreMatchingTests(unittest.TestCase): def setUp(self): sigma = Uniform([[1], [2]]) mu = Normal([0, 1]) self.Y = Normal([mu, sigma]) self.backend = Backend() self.statistics_cal = Identity(degree=3, cross=False) if has_torch: self.statisticslearning_all_defaults = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, use_tqdm=False) self.statisticslearning_no_sliced = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, sliced=False, use_tqdm=False) self.statisticslearning_sphere_noise = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, use_tqdm=False, noise_type="sphere") self.statisticslearning_gaussian_noise = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, use_tqdm=False, noise_type="gaussian") self.statisticslearning_variance_reduction = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, use_tqdm=False, variance_reduction=True) self.statisticslearning_no_bn = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, batch_norm=False, use_tqdm=False) self.statisticslearning_provide_nets = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, simulations_net=createDefaultNN(3, 3)(), parameters_net=createDefaultNN(2, 2)(), use_tqdm=False) self.statisticslearning_embedding_dim = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, embedding_dimension=4, use_tqdm=False) self.statisticslearning_validation_early_stop = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=20, n_samples_val=20, early_stopping=True, use_tqdm=False) self.statisticslearning_scale = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, scale_samples=False, scale_parameters=True, use_tqdm=False) self.statisticslearning_bounds = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, lower_bound_simulations=np.array([-1000, -1000, -1000]), upper_bound_simulations=np.array([1000, 1000, 1000]), use_tqdm=False, seed=1) self.statisticslearning_no_schedulers = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, scheduler_parameters=False, scheduler_simulations=False, use_tqdm=False) self.statisticslearning_lam = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=4, n_epochs=2, use_tqdm=False, sliced=False, lam=0.1) def test_initialization(self): if not has_torch: self.assertRaises(ImportError, ExponentialFamilyScoreMatching, [self.Y], self.statistics_cal, self.backend) def test_transformation(self): if has_torch: self.new_statistics_calculator = self.statisticslearning_all_defaults.get_statistics() self.new_statistics_calculator_no_scaler = self.statisticslearning_scale.get_statistics() self.new_statistics_calculator_no_rescale = self.statisticslearning_all_defaults.get_statistics( rescale_statistics=False) Obs = Normal([2, 4]) y_obs = Obs.forward_simulate(Obs.get_input_values(), 1)[0].tolist() extracted_statistics = self.new_statistics_calculator.statistics(y_obs) self.assertEqual(np.shape(extracted_statistics), (1, 2)) extracted_statistics_no_rescale = self.new_statistics_calculator_no_rescale.statistics(y_obs) self.assertEqual(np.shape(extracted_statistics_no_rescale), (1, 2)) self.assertFalse(np.allclose(extracted_statistics_no_rescale, extracted_statistics)) self.assertRaises(RuntimeError, self.new_statistics_calculator.statistics, [np.array([1, 2])]) self.assertRaises(RuntimeError, self.new_statistics_calculator_no_scaler.statistics, [np.array([1, 2])]) def test_errors(self): if has_torch: with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, parameters=np.ones((100, 1))) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, simulations_net=createDefaultNN(1, 3)) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, parameters_net=createDefaultNN(1, 3)) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, noise_type="ciao", use_tqdm=False) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, noise_type="sphere", variance_reduction=True, use_tqdm=False) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, simulations=np.ones((100, 1))) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, simulations=np.ones((100, 1, 3))) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, parameters=np.ones((100, 1, 2))) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, simulations=np.ones((100, 1)), parameters=np.zeros((99, 1))) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, parameters_val=np.ones((100, 1))) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, simulations_val=np.ones((100, 1))) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, simulations_val=np.ones((100, 1, 3))) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, parameters_val=np.ones((100, 1, 2))) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, simulations_val=np.ones((100, 1)), parameters_val=np.zeros((99, 1))) with self.assertRaises(TypeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, parameters=[i for i in range(10)], simulations=[i for i in range(10)]) with self.assertRaises(TypeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, parameters_val=[i for i in range(10)], simulations_val=[i for i in range(10)]) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, lower_bound_simulations=[1, 2, 3]) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, seed=1, upper_bound_simulations=[1, 2, 3]) with self.assertRaises(RuntimeError): self.statisticslearning = ExponentialFamilyScoreMatching([self.Y], self.statistics_cal, self.backend, n_samples=1000, lower_bound_simulations=np.array([-1000, -1000]), seed=1, upper_bound_simulations=np.array([1000, 1000, 1000])) with self.assertRaises(RuntimeError): self.statisticslearning_all_defaults.test_losses = [4, 2, 1] self.statisticslearning_all_defaults.plot_losses() with self.assertRaises(NotImplementedError): self.statisticslearning_all_defaults.plot_losses(which_losses="foo") def test_plots(self): if has_torch: self.statisticslearning_all_defaults.plot_losses() self.statisticslearning_all_defaults.plot_losses(which_losses="train") self.statisticslearning_all_defaults.plot_losses(which_losses="test") if __name__ == '__main__': unittest.main()
true
true
f7fe9be20480f1b08ea8c20cbfbc51b9436b5905
2,173
py
Python
tacker/vnfm/infra_drivers/noop.py
sungbogo28/tacker
a3f0b6d4e9e490ffeb6b3084705f38d962134fff
[ "Apache-2.0" ]
null
null
null
tacker/vnfm/infra_drivers/noop.py
sungbogo28/tacker
a3f0b6d4e9e490ffeb6b3084705f38d962134fff
[ "Apache-2.0" ]
null
null
null
tacker/vnfm/infra_drivers/noop.py
sungbogo28/tacker
a3f0b6d4e9e490ffeb6b3084705f38d962134fff
[ "Apache-2.0" ]
1
2019-01-21T10:57:10.000Z
2019-01-21T10:57:10.000Z
# Copyright 2013, 2014 Intel Corporation. # All Rights Reserved. # # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # TODO(yamahata): once unittests are impletemted, move this there from oslo_log import log as logging from oslo_utils import uuidutils from tacker.common import log from tacker.vnfm.infra_drivers import abstract_driver LOG = logging.getLogger(__name__) class VnfNoop(abstract_driver.VnfAbstractDriver): """Noop driver of hosting vnf for tests.""" def __init__(self): super(VnfNoop, self).__init__() self._instances = set() def get_type(self): return 'noop' def get_name(self): return 'noop' def get_description(self): return 'Tacker infra noop driver' @log.log def create(self, **kwargs): instance_id = uuidutils.generate_uuid() self._instances.add(instance_id) return instance_id @log.log def create_wait(self, plugin, context, vnf_dict, vnf_id): pass @log.log def update(self, plugin, context, vnf_id, vnf_dict, vnf): if vnf_id not in self._instances: LOG.debug('not found') raise ValueError('No instance %s' % vnf_id) @log.log def update_wait(self, plugin, context, vnf_id): pass @log.log def delete(self, plugin, context, vnf_id): self._instances.remove(vnf_id) @log.log def delete_wait(self, plugin, context, vnf_id): pass def get_resource_info(self, plugin, context, vnf_info, auth_attr, region_name=None): return {'noop': {'id': uuidutils.generate_uuid(), 'type': 'noop'}}
28.592105
78
0.670502
from oslo_log import log as logging from oslo_utils import uuidutils from tacker.common import log from tacker.vnfm.infra_drivers import abstract_driver LOG = logging.getLogger(__name__) class VnfNoop(abstract_driver.VnfAbstractDriver): def __init__(self): super(VnfNoop, self).__init__() self._instances = set() def get_type(self): return 'noop' def get_name(self): return 'noop' def get_description(self): return 'Tacker infra noop driver' @log.log def create(self, **kwargs): instance_id = uuidutils.generate_uuid() self._instances.add(instance_id) return instance_id @log.log def create_wait(self, plugin, context, vnf_dict, vnf_id): pass @log.log def update(self, plugin, context, vnf_id, vnf_dict, vnf): if vnf_id not in self._instances: LOG.debug('not found') raise ValueError('No instance %s' % vnf_id) @log.log def update_wait(self, plugin, context, vnf_id): pass @log.log def delete(self, plugin, context, vnf_id): self._instances.remove(vnf_id) @log.log def delete_wait(self, plugin, context, vnf_id): pass def get_resource_info(self, plugin, context, vnf_info, auth_attr, region_name=None): return {'noop': {'id': uuidutils.generate_uuid(), 'type': 'noop'}}
true
true
f7fe9c52b15e986902a3ba00feebcc2a53eeaf4a
9,075
py
Python
test/test_pluginmanager.py
noralsydmp/icetea
b486cdc8e0d2211e118f1f8211aa4d284ca02422
[ "Apache-2.0" ]
6
2018-08-10T17:11:10.000Z
2020-04-29T07:05:36.000Z
test/test_pluginmanager.py
noralsydmp/icetea
b486cdc8e0d2211e118f1f8211aa4d284ca02422
[ "Apache-2.0" ]
58
2018-08-13T08:36:08.000Z
2021-07-07T08:32:52.000Z
test/test_pluginmanager.py
noralsydmp/icetea
b486cdc8e0d2211e118f1f8211aa4d284ca02422
[ "Apache-2.0" ]
7
2018-08-10T12:53:18.000Z
2021-11-08T05:15:42.000Z
# pylint: disable=missing-docstring,protected-access """ Copyright 2017 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest import os import sys import mock from icetea_lib.Plugin.PluginManager import PluginManager, PluginException from icetea_lib.Plugin.plugins.default_plugins import default_plugins class PMTestcase(unittest.TestCase): def test_load_defaults(self): bench = mock.MagicMock(spec=[]) bench.logger = mock.MagicMock(return_value=mock.MagicMock()) resp_parser = mock.MagicMock() resp_parser.append = mock.MagicMock() resp_parser.has_parser = mock.MagicMock(return_value=False) pluginmanager = PluginManager(bench=bench, responseparser=resp_parser) pluginmanager.load_default_tc_plugins() pluginmanager.load_default_run_plugins() length = len(default_plugins) self.assertEqual(len(pluginmanager.registered_plugins), length) def test_register_all_tc_types(self): # Set up mocks plugin_class = mock.MagicMock() plugin_class.init = mock.MagicMock() plugin_class.get_bench_api = mock.MagicMock() plugin_class.get_parsers = mock.MagicMock() plugin_class.get_external_services = mock.MagicMock() mock_bench = mock.MagicMock(spec=[]) mock_bench.logger = mock.MagicMock(return_value=mock.MagicMock()) mock_bench_function = mock.MagicMock() mock_parser = mock.MagicMock() plugin_class.get_bench_api.return_value = {"mock_func": mock_bench_function} plugin_class.get_external_services.return_value = {"mock_class": mock.MagicMock} plugin_class.get_parsers.return_value = {"mock_parser": mock_parser} mock_parsermanager = mock.MagicMock() mock_parsermanager.add_parser = mock.MagicMock() mock_parsermanager.has_parser = mock.MagicMock(return_value=False) pluginmanager = PluginManager(bench=mock_bench, responseparser=mock_parsermanager) pluginmanager.register_tc_plugins("test_plugin", plugin_class) # Asserts self.assertEqual(len(pluginmanager.registered_plugins), 1) self.assertEqual(pluginmanager.registered_plugins[0], "test_plugin") self.assertEqual(len(pluginmanager._external_services), 1) mock_parsermanager.has_parser.assert_called_once_with("mock_parser") mock_parsermanager.add_parser.assert_called_once_with("mock_parser", mock_parser) def test_register_and_start_service(self): # Set up mocks plugin_class = mock.MagicMock() plugin_class.init = mock.MagicMock() plugin_class.get_bench_api = mock.MagicMock() plugin_class.get_parsers = mock.MagicMock() plugin_class.get_external_services = mock.MagicMock() mock_bench = mock.MagicMock(spec=[]) mock_bench.logger = mock.MagicMock(return_value=mock.MagicMock()) plugin_class.get_bench_api.return_value = None mock_class = mock.MagicMock() plugin_class.get_external_services.return_value = {"mock_class": mock_class} plugin_class.get_parsers.return_value = None mock_parsermanager = mock.MagicMock() pluginmanager = PluginManager(bench=mock_bench, responseparser=mock_parsermanager) pluginmanager.register_tc_plugins("test_plugin", plugin_class) pluginmanager.start_external_service("mock_class") self.assertEqual(len(pluginmanager._started_services), 1) pluginmanager.stop_external_services() self.assertEqual(len(pluginmanager._started_services), 0) self.assertEqual(len(pluginmanager._external_services), 1) mock_class.assert_called_once() def test_start_service_raises_exception(self): # pylint: disable=invalid-name # Set up mocks plugin_class = mock.MagicMock() plugin_class.init = mock.MagicMock() plugin_class.get_bench_api = mock.MagicMock() plugin_class.get_parsers = mock.MagicMock() plugin_class.get_external_services = mock.MagicMock() mock_bench = mock.MagicMock(spec=[]) mock_bench.logger = mock.MagicMock(return_value=mock.MagicMock()) plugin_class.get_bench_api.return_value = None mocked_service = mock.MagicMock() mock_class = mock.MagicMock(return_value=mocked_service) mocked_service.start = mock.MagicMock() mocked_service.start.side_effect = [PluginException] plugin_class.get_external_services.return_value = {"mock_class": mock_class} plugin_class.get_parsers.return_value = None mock_parsermanager = mock.MagicMock() pluginmanager = PluginManager(bench=mock_bench, responseparser=mock_parsermanager) pluginmanager.register_tc_plugins("test_plugin", plugin_class) with self.assertRaises(PluginException): pluginmanager.start_external_service("mock_class") mocked_service.start.assert_called_once() def test_register_start_stop_service(self): # pylint: disable=invalid-name plugin_class = mock.MagicMock() plugin_class.init = mock.MagicMock() plugin_class.get_bench_api = mock.MagicMock() plugin_class.get_parsers = mock.MagicMock() plugin_class.get_external_services = mock.MagicMock() mock_bench = mock.MagicMock(spec=[]) mock_bench.logger = mock.MagicMock(return_value=mock.MagicMock()) plugin_class.get_bench_api.return_value = None mocked_service = mock.MagicMock() mocked_service.start = mock.MagicMock() mocked_service.stop = mock.MagicMock(side_effect=[PluginException]) mock_class = mock.MagicMock(return_value=mocked_service) plugin_class.get_external_services.return_value = {"mock_class": mock_class} plugin_class.get_parsers.return_value = None mock_parsermanager = mock.MagicMock() pluginmanager = PluginManager(bench=mock_bench, responseparser=mock_parsermanager) pluginmanager.register_tc_plugins("test_plugin", plugin_class) pluginmanager.start_external_service("mock_class") self.assertEqual(len(pluginmanager._started_services), 1) pluginmanager.stop_external_services() self.assertEqual(len(pluginmanager._started_services), 0) self.assertEqual(len(pluginmanager._external_services), 1) mock_class.assert_called_once() def test_register_raises_pluginexception(self): # pylint: disable=invalid-name plugin_class = mock.MagicMock() plugin_class.init = mock.MagicMock() plugin_class.get_bench_api = mock.MagicMock() mock_bench = mock.MagicMock(spec=[]) mock_bench.logger = mock.MagicMock(return_value=mock.MagicMock()) mock_bench_function = mock.MagicMock() plugin_class.get_bench_api.return_value = {"mock_func": mock_bench_function} mock_parsermanager = mock.MagicMock() mock_parsermanager.add_parser = mock.MagicMock() mock_parsermanager.has_parser = mock.MagicMock(return_value=False) pluginmanager = PluginManager(bench=mock_bench, responseparser=mock_parsermanager) pluginmanager.registered_plugins = ["test_plugin"] with self.assertRaises(PluginException): pluginmanager.register_tc_plugins("test_plugin", plugin_class) def test_load_custom_plugins(self): # pylint: disable=no-self-use modules = sys.modules mock_bench = mock.MagicMock(spec=[]) mock_parsermanager = mock.MagicMock() pluginmanager = PluginManager(bench=mock_bench, responseparser=mock_parsermanager) pluginmanager.register_tc_plugins = mock.MagicMock() pluginmanager.load_custom_tc_plugins(os.path.join(os.path.dirname(os.path.abspath( __file__)), "test_plugin/load_test_plugins.py")) sys.modules = modules pluginmanager.register_tc_plugins.assert_called_once() @mock.patch("icetea_lib.Plugin.PluginManager.importlib") def test_load_custom_plugin_exception(self, mock_importer): # pylint: disable=invalid-name mock_bench = mock.MagicMock(spec=[]) mock_parsermanager = mock.MagicMock() mock_importer.import_module = mock.MagicMock(side_effect=[ImportError]) pluginmanager = PluginManager(bench=mock_bench, responseparser=mock_parsermanager) with self.assertRaises(PluginException): pluginmanager.load_custom_tc_plugins(os.path.join(os.path.dirname(os.path.abspath( __file__)), "test_plugin/load_test_plugins.py")) if __name__ == '__main__': unittest.main()
46.06599
95
0.729366
import unittest import os import sys import mock from icetea_lib.Plugin.PluginManager import PluginManager, PluginException from icetea_lib.Plugin.plugins.default_plugins import default_plugins class PMTestcase(unittest.TestCase): def test_load_defaults(self): bench = mock.MagicMock(spec=[]) bench.logger = mock.MagicMock(return_value=mock.MagicMock()) resp_parser = mock.MagicMock() resp_parser.append = mock.MagicMock() resp_parser.has_parser = mock.MagicMock(return_value=False) pluginmanager = PluginManager(bench=bench, responseparser=resp_parser) pluginmanager.load_default_tc_plugins() pluginmanager.load_default_run_plugins() length = len(default_plugins) self.assertEqual(len(pluginmanager.registered_plugins), length) def test_register_all_tc_types(self): plugin_class = mock.MagicMock() plugin_class.init = mock.MagicMock() plugin_class.get_bench_api = mock.MagicMock() plugin_class.get_parsers = mock.MagicMock() plugin_class.get_external_services = mock.MagicMock() mock_bench = mock.MagicMock(spec=[]) mock_bench.logger = mock.MagicMock(return_value=mock.MagicMock()) mock_bench_function = mock.MagicMock() mock_parser = mock.MagicMock() plugin_class.get_bench_api.return_value = {"mock_func": mock_bench_function} plugin_class.get_external_services.return_value = {"mock_class": mock.MagicMock} plugin_class.get_parsers.return_value = {"mock_parser": mock_parser} mock_parsermanager = mock.MagicMock() mock_parsermanager.add_parser = mock.MagicMock() mock_parsermanager.has_parser = mock.MagicMock(return_value=False) pluginmanager = PluginManager(bench=mock_bench, responseparser=mock_parsermanager) pluginmanager.register_tc_plugins("test_plugin", plugin_class) self.assertEqual(len(pluginmanager.registered_plugins), 1) self.assertEqual(pluginmanager.registered_plugins[0], "test_plugin") self.assertEqual(len(pluginmanager._external_services), 1) mock_parsermanager.has_parser.assert_called_once_with("mock_parser") mock_parsermanager.add_parser.assert_called_once_with("mock_parser", mock_parser) def test_register_and_start_service(self): plugin_class = mock.MagicMock() plugin_class.init = mock.MagicMock() plugin_class.get_bench_api = mock.MagicMock() plugin_class.get_parsers = mock.MagicMock() plugin_class.get_external_services = mock.MagicMock() mock_bench = mock.MagicMock(spec=[]) mock_bench.logger = mock.MagicMock(return_value=mock.MagicMock()) plugin_class.get_bench_api.return_value = None mock_class = mock.MagicMock() plugin_class.get_external_services.return_value = {"mock_class": mock_class} plugin_class.get_parsers.return_value = None mock_parsermanager = mock.MagicMock() pluginmanager = PluginManager(bench=mock_bench, responseparser=mock_parsermanager) pluginmanager.register_tc_plugins("test_plugin", plugin_class) pluginmanager.start_external_service("mock_class") self.assertEqual(len(pluginmanager._started_services), 1) pluginmanager.stop_external_services() self.assertEqual(len(pluginmanager._started_services), 0) self.assertEqual(len(pluginmanager._external_services), 1) mock_class.assert_called_once() def test_start_service_raises_exception(self): plugin_class = mock.MagicMock() plugin_class.init = mock.MagicMock() plugin_class.get_bench_api = mock.MagicMock() plugin_class.get_parsers = mock.MagicMock() plugin_class.get_external_services = mock.MagicMock() mock_bench = mock.MagicMock(spec=[]) mock_bench.logger = mock.MagicMock(return_value=mock.MagicMock()) plugin_class.get_bench_api.return_value = None mocked_service = mock.MagicMock() mock_class = mock.MagicMock(return_value=mocked_service) mocked_service.start = mock.MagicMock() mocked_service.start.side_effect = [PluginException] plugin_class.get_external_services.return_value = {"mock_class": mock_class} plugin_class.get_parsers.return_value = None mock_parsermanager = mock.MagicMock() pluginmanager = PluginManager(bench=mock_bench, responseparser=mock_parsermanager) pluginmanager.register_tc_plugins("test_plugin", plugin_class) with self.assertRaises(PluginException): pluginmanager.start_external_service("mock_class") mocked_service.start.assert_called_once() def test_register_start_stop_service(self): plugin_class = mock.MagicMock() plugin_class.init = mock.MagicMock() plugin_class.get_bench_api = mock.MagicMock() plugin_class.get_parsers = mock.MagicMock() plugin_class.get_external_services = mock.MagicMock() mock_bench = mock.MagicMock(spec=[]) mock_bench.logger = mock.MagicMock(return_value=mock.MagicMock()) plugin_class.get_bench_api.return_value = None mocked_service = mock.MagicMock() mocked_service.start = mock.MagicMock() mocked_service.stop = mock.MagicMock(side_effect=[PluginException]) mock_class = mock.MagicMock(return_value=mocked_service) plugin_class.get_external_services.return_value = {"mock_class": mock_class} plugin_class.get_parsers.return_value = None mock_parsermanager = mock.MagicMock() pluginmanager = PluginManager(bench=mock_bench, responseparser=mock_parsermanager) pluginmanager.register_tc_plugins("test_plugin", plugin_class) pluginmanager.start_external_service("mock_class") self.assertEqual(len(pluginmanager._started_services), 1) pluginmanager.stop_external_services() self.assertEqual(len(pluginmanager._started_services), 0) self.assertEqual(len(pluginmanager._external_services), 1) mock_class.assert_called_once() def test_register_raises_pluginexception(self): plugin_class = mock.MagicMock() plugin_class.init = mock.MagicMock() plugin_class.get_bench_api = mock.MagicMock() mock_bench = mock.MagicMock(spec=[]) mock_bench.logger = mock.MagicMock(return_value=mock.MagicMock()) mock_bench_function = mock.MagicMock() plugin_class.get_bench_api.return_value = {"mock_func": mock_bench_function} mock_parsermanager = mock.MagicMock() mock_parsermanager.add_parser = mock.MagicMock() mock_parsermanager.has_parser = mock.MagicMock(return_value=False) pluginmanager = PluginManager(bench=mock_bench, responseparser=mock_parsermanager) pluginmanager.registered_plugins = ["test_plugin"] with self.assertRaises(PluginException): pluginmanager.register_tc_plugins("test_plugin", plugin_class) def test_load_custom_plugins(self): modules = sys.modules mock_bench = mock.MagicMock(spec=[]) mock_parsermanager = mock.MagicMock() pluginmanager = PluginManager(bench=mock_bench, responseparser=mock_parsermanager) pluginmanager.register_tc_plugins = mock.MagicMock() pluginmanager.load_custom_tc_plugins(os.path.join(os.path.dirname(os.path.abspath( __file__)), "test_plugin/load_test_plugins.py")) sys.modules = modules pluginmanager.register_tc_plugins.assert_called_once() @mock.patch("icetea_lib.Plugin.PluginManager.importlib") def test_load_custom_plugin_exception(self, mock_importer): mock_bench = mock.MagicMock(spec=[]) mock_parsermanager = mock.MagicMock() mock_importer.import_module = mock.MagicMock(side_effect=[ImportError]) pluginmanager = PluginManager(bench=mock_bench, responseparser=mock_parsermanager) with self.assertRaises(PluginException): pluginmanager.load_custom_tc_plugins(os.path.join(os.path.dirname(os.path.abspath( __file__)), "test_plugin/load_test_plugins.py")) if __name__ == '__main__': unittest.main()
true
true
f7fe9c842b6fde00535088f166a52c9c7725826f
286
py
Python
2021/day_11/test_solution.py
krother/advent_of_code
fd7d5199666b2f3a60c41c6cf24b747322ad88e5
[ "MIT" ]
3
2021-12-01T09:27:34.000Z
2022-02-24T23:35:56.000Z
2021/day_11/test_solution.py
krother/advent_of_code
fd7d5199666b2f3a60c41c6cf24b747322ad88e5
[ "MIT" ]
null
null
null
2021/day_11/test_solution.py
krother/advent_of_code
fd7d5199666b2f3a60c41c6cf24b747322ad88e5
[ "MIT" ]
null
null
null
import pytest from .solution import solve INPUT = """5483143223 2745854711 5264556173 6141336146 6357385478 4167524645 2176841721 6882881134 4846848554 5283751526 """ def test_solve(): assert solve(INPUT) == 1656 def test_solve2(): assert solve(INPUT, 999999999999) == 195
12.434783
44
0.762238
import pytest from .solution import solve INPUT = """5483143223 2745854711 5264556173 6141336146 6357385478 4167524645 2176841721 6882881134 4846848554 5283751526 """ def test_solve(): assert solve(INPUT) == 1656 def test_solve2(): assert solve(INPUT, 999999999999) == 195
true
true
f7fe9cb437273e5169b1c20580e73b1720f0ff50
668
py
Python
components/Actuators/LowLevel/winch.py
Raptacon/Robot-2022
f59c6a6ebd5779a2fd91181b65cbcd677507ca5d
[ "MIT" ]
4
2022-01-31T14:05:31.000Z
2022-03-26T14:12:45.000Z
components/Actuators/LowLevel/winch.py
Raptacon/Robot-2022
f59c6a6ebd5779a2fd91181b65cbcd677507ca5d
[ "MIT" ]
57
2022-01-13T02:41:31.000Z
2022-03-26T14:50:42.000Z
components/Actuators/LowLevel/winch.py
Raptacon/Robot-2022
f59c6a6ebd5779a2fd91181b65cbcd677507ca5d
[ "MIT" ]
null
null
null
class Winch: compatString = ["teapot"] motors_winch: dict def on_enable(self): """ Sets up the winch """ self.upSpeed = 0 self.winchMotor = self.motors_winch["winchMotor"] self.logger.info("Lifter Component Created") def setRaise(self): """ Sets the motor speed to .5 in order to reel in the winch """ self.upSpeed = .5 def setLower(self): self.upSpeed = -1 def stop(self): """ Sets the motor speed to 0 in order to stop the winch """ self.upSpeed = 0 def execute(self): self.winchMotor.set(self.upSpeed)
20.875
64
0.546407
class Winch: compatString = ["teapot"] motors_winch: dict def on_enable(self): self.upSpeed = 0 self.winchMotor = self.motors_winch["winchMotor"] self.logger.info("Lifter Component Created") def setRaise(self): self.upSpeed = .5 def setLower(self): self.upSpeed = -1 def stop(self): self.upSpeed = 0 def execute(self): self.winchMotor.set(self.upSpeed)
true
true
f7fe9d66d4c64174c063245c6d2cb2a4b7a1596d
486
py
Python
tests/conftest.py
Yasti4/python-aioddd
a0731e05a0133bf5636437ceb7625f7deaa100ab
[ "MIT" ]
4
2020-07-28T12:34:02.000Z
2021-02-11T09:57:20.000Z
tests/conftest.py
Yasti4/python-aioddd
a0731e05a0133bf5636437ceb7625f7deaa100ab
[ "MIT" ]
2
2020-11-19T20:45:53.000Z
2020-12-25T13:48:08.000Z
tests/conftest.py
ticdenis/python-aiodi
4ad35145674f5ec0ed6324bec7dd186ab0a8bc33
[ "MIT" ]
1
2020-11-19T20:39:09.000Z
2020-11-19T20:39:09.000Z
import sys from asyncio import AbstractEventLoop, get_event_loop_policy from unittest.mock import MagicMock if sys.version_info >= (3, 8): from unittest.mock import AsyncMock else: class AsyncMock(MagicMock): async def __call__(self, *args, **kwargs): return super(AsyncMock, self).__call__(*args, **kwargs) from pytest import fixture @fixture(scope='session') def event_loop() -> AbstractEventLoop: return get_event_loop_policy().new_event_loop()
24.3
67
0.734568
import sys from asyncio import AbstractEventLoop, get_event_loop_policy from unittest.mock import MagicMock if sys.version_info >= (3, 8): from unittest.mock import AsyncMock else: class AsyncMock(MagicMock): async def __call__(self, *args, **kwargs): return super(AsyncMock, self).__call__(*args, **kwargs) from pytest import fixture @fixture(scope='session') def event_loop() -> AbstractEventLoop: return get_event_loop_policy().new_event_loop()
true
true
f7fe9e40ca2bd2c5da645db6823f7967d370514f
12,777
py
Python
kd_splicing/kd_splicing/helpers.py
konovalovdmitry/catsnap
d5f1d7c37dcee1ad3fee2cdc12a3b44b56f4c63f
[ "MIT" ]
null
null
null
kd_splicing/kd_splicing/helpers.py
konovalovdmitry/catsnap
d5f1d7c37dcee1ad3fee2cdc12a3b44b56f4c63f
[ "MIT" ]
null
null
null
kd_splicing/kd_splicing/helpers.py
konovalovdmitry/catsnap
d5f1d7c37dcee1ad3fee2cdc12a3b44b56f4c63f
[ "MIT" ]
1
2021-09-30T08:06:20.000Z
2021-09-30T08:06:20.000Z
import os import uuid from collections import defaultdict from itertools import chain from typing import Dict, List, Mapping, Optional, Tuple import pandas as pd from kd_common import excel, logutil, pathutil from kd_splicing import as_type, blast, database, features, ml, performance, pipeline from kd_splicing.dataset.models import Dataset from kd_splicing.dump import dump from kd_splicing.models import FormattedResults, IsoformTuple, Match, SimpleMatch, Queries from kd_splicing.models import SearchStatus import itertools from tqdm import tqdm import json _logger = logutil.get_logger(__name__) def find_in_queries( protein_ids_str: str, isoforms_to_duplicates: Mapping[uuid.UUID, List[uuid.UUID]], db: database.models.DB, matches_dict: Mapping[IsoformTuple, List[SimpleMatch]] ) -> Optional[IsoformTuple]: tup = str_to_isoform_tuple(db, protein_ids_str) for a in isoforms_to_duplicates[tup.a]: for b in isoforms_to_duplicates[tup.b]: dup = IsoformTuple(a,b) if dup in matches_dict: return dup return None ############# # Common ############# def str_to_isoform_tuple(db: database.models.DB, protein_ids_str: str) -> IsoformTuple: protein_ids = [protein_id.strip() for protein_id in protein_ids_str.split(",")] assert len(protein_ids) == 2 return IsoformTuple( db.protein_id_to_isoform[protein_ids[0]], db.protein_id_to_isoform[protein_ids[1]]) def isoform_tuple_to_protein_ids(db: database.models.DB, iso_tuple: IsoformTuple) -> str: return f"{db.isoforms[iso_tuple.a].protein_id},{db.isoforms[iso_tuple.b].protein_id}" def tuples_to_queries(tuples: List[IsoformTuple], num_groups: int = 20) -> Queries: isoforms = sorted(list(set(chain.from_iterable( (query_isoforms.a, query_isoforms.b) for query_isoforms in tuples )))) group_count = itertools.cycle(range(0, num_groups)) isoform_to_group = {} isoform_to_idx = {} group_size: Dict[int, int] = defaultdict(int) for iso in isoforms: group = next(group_count) isoform_to_group[iso] = group isoform_to_idx[iso] = group_size[group] group_size[group] += 1 return Queries( tuples=tuples, isoforms=isoforms, isoform_to_idx=isoform_to_idx, isoform_to_group=isoform_to_group, ) def best_match_per_organism(matches: List[Match]) -> List[Match]: query_organism_to_match: Dict[Tuple[IsoformTuple, str], Match] = {} for m in matches: key = (m.query_isoforms, m.hit_organism) best_match = query_organism_to_match.get(key) if not best_match or best_match.predicted_positive_probability < m.predicted_positive_probability: query_organism_to_match[key] = m return list(query_organism_to_match.values()) ############# # Stats ############# def count_isoforms_per_organism(db: database.models.DB) -> None: organism_to_isoform_count: Dict[str, int] = defaultdict(int) for isoform in db.isoforms.values(): gene = db.genes[isoform.gene_uuid] record = db.records[gene.record_uuid] organism_to_isoform_count[record.organism] += 1 for key, value in sorted(organism_to_isoform_count.items(), key=lambda p: p[1]): print(key, ",", value) def calc_performance(matches: List[Match]) -> None: predicted = [m.predicted_positive for m in matches] correct = [m.positive for m in matches] _logger.info( f"Performance:\n{pd.Series(performance.binary_y_performance(correct, predicted))}") def db_organisms_stats(db: database.models.DB, db_folder: str) -> None: df = database.utils.to_df(db) d1 = df["organism"].value_counts().reset_index() excel.write(d1, os.path.join(pathutil.create_folder( db_folder, "stats"), os.path.basename(db_folder) + "_db_organisms.xlsx")) d2 = df[df["db_name"] == "refseq"]["organism"].value_counts().reset_index() excel.write(d2, os.path.join(pathutil.create_folder( db_folder, "stats"), os.path.basename(db_folder) + "_db_organisms_refseq.xlsx")) d3 = df[df["db_name"] == "genbank"]["organism"].value_counts().reset_index() excel.write(d3, os.path.join(pathutil.create_folder( db_folder, "stats"), os.path.basename(db_folder) + "_db_organisms_genbank.xlsx")) d4 = df[df["db_name_src"] == "refseq"]["organism"].value_counts().reset_index() excel.write(d4, os.path.join(pathutil.create_folder( db_folder, "stats"), os.path.basename(db_folder) + "_db_organisms_refseq_src.xlsx")) d5 = df[df["db_name_src"] == "genbank"]["organism"].value_counts().reset_index() excel.write(d5, os.path.join(pathutil.create_folder( db_folder, "stats"), os.path.basename(db_folder) + "_db_organisms_genbank_src.xlsx")) def db_missed_files(p: pipeline.Pipeline) -> None: def prepare(s: str) -> str: s = os.path.basename(s) s = ".".join(s.split(".")[:-1]) return s files = pathutil.file_list(p.folder_archive, p.archive_extension) extracted = pathutil.file_list(p.folder_extracted) files.sort() extracted = [prepare(f) for f in extracted] files = [prepare(f) for f in files] print(sorted(list(set(files) - set(extracted)))) ############# # Dumps ############# def single_cross_validation_and_dump(db: database.models.DB, launch_folder: str, ds: List[Match], test_protein_ids: str) -> None: protein_ids = test_protein_ids.split(",") assert len(protein_ids) == 2 protein_id_to_isoform = { i.protein_id: i.uuid for i in db.isoforms.values()} test_query_isoforms = IsoformTuple( protein_id_to_isoform[protein_ids[0]], protein_id_to_isoform[protein_ids[1]]) train_ds = [m for m in ds if m.query_isoforms != test_query_isoforms] test_ds = [m for m in ds if m.query_isoforms == test_query_isoforms] d = ml.Detector() d.fit(train_ds) d.transform(test_ds) calc_performance(test_ds) folder = pathutil.create_folder(launch_folder, "cross_validation") dump(db, folder, test_ds) def dump_single_query_simple_matches( db: database.models.DB, launch_folder: str, matches_dict: Mapping[IsoformTuple, List[SimpleMatch]], protein_ids_str: str, isoforms_to_duplicates: Mapping[uuid.UUID, List[uuid.UUID]], ) -> None: query_isoforms = find_in_queries(protein_ids_str, isoforms_to_duplicates, db, matches_dict) if not query_isoforms: print("No such query in precalculated queries") return simple_matches = matches_dict[query_isoforms] matches = features.convert_matches({query_isoforms: simple_matches}) dump(db, pathutil.create_folder(launch_folder, "matches_simple_single", protein_ids_str), matches) def calc_features_and_dump_single( db: database.models.DB, launch_folder: str, queries: Queries, detector: ml.Detector, protein_ids_str: str, isoforms_to_duplicates: Mapping[uuid.UUID, List[uuid.UUID]], matches_dict: Mapping[IsoformTuple, List[SimpleMatch]], ) -> List[Match]: query_isoforms = find_in_queries(protein_ids_str, isoforms_to_duplicates, db, matches_dict) if not query_isoforms: print("No such query in precalculated queries") return matches = features.calc(db, launch_folder, queries, [query_isoforms]) detector.transform(matches) dump(db, pathutil.create_folder(launch_folder, "matches_single", protein_ids_str), matches) return matches ############# # Search ############# def search( db: database.models.DB, p: pipeline.Pipeline, detector: ml.Detector, query_protein_ids_str: List[str], blast_db_path: str, status: SearchStatus = SearchStatus.construct(progress = 0, description = ""), isoforms_to_duplicates: Optional[Mapping[uuid.UUID, List[uuid.UUID]]] = None, ) -> str: status.set(0, "Preparing queries") tuples = [str_to_isoform_tuple(db, query_proteins) for query_proteins in query_protein_ids_str] queries = tuples_to_queries(tuples, num_groups=1) name = ";".join(query_protein_ids_str) return search_queries(db, p, detector, queries, name, blast_db_path, status, isoforms_to_duplicates) def search_queries( db: database.models.DB, p: pipeline.Pipeline, detector: ml.Detector, queries: Queries, name: str, blast_db_path: str, status: SearchStatus, isoforms_to_duplicates: Optional[Mapping[uuid.UUID, List[uuid.UUID]]] = None, ) -> str: status.set(10, "BLAST running") blast.create_queires(db, queries, p.launch_folder) blast.run(p.launch_folder, blast_db_path, parallel = False) status.set(20, "Reading BLAST results") queries.isoform_to_file = get_isoforms_to_file(p.launch_folder) status.set(30, "Calculating features") matches = features.calc(db, p.launch_folder, queries) status.set(40, "Running ml model") detector.transform(matches) result_folder = pathutil.create_folder(p.launch_folder, "search_single", name) status.set(50, "Preparing results") dump(db, result_folder, matches, isoforms_to_duplicates) return result_folder def matches_to_df( db: database.models.DB, isoforms_to_duplicates: Mapping[uuid.UUID, List[uuid.UUID]], matches: List[Match], ) -> pd.DataFrame: data = [] for m in tqdm(matches): q_iso_a = db.isoforms[m.query_isoforms.a] q_iso_b = db.isoforms[m.query_isoforms.b] q_gene = db.genes[q_iso_a.gene_uuid] q_record = db.records[q_gene.record_uuid] q_file = db.files[q_record.file_uuid] h_iso_a = db.isoforms[m.hit_isoforms.a] h_iso_b = db.isoforms[m.hit_isoforms.b] h_gene = db.genes[h_iso_a.gene_uuid] h_record = db.records[h_gene.record_uuid] h_file = db.files[h_record.file_uuid] hit_as_types = as_type.get_isoforms_as_types(db, isoforms_to_duplicates, h_iso_a.uuid, h_iso_b.uuid) query_as_types = as_type.get_isoforms_as_types(db, isoforms_to_duplicates, q_iso_a.uuid, q_iso_b.uuid) intersection_as_types = hit_as_types & query_as_types row = { "query_isoforms": m.query_isoforms, "hit_isoforms": m.hit_isoforms, "hit_organism": m.hit_organism, "hit_db_name": m.hit_db_name, "hit_gene_uuid": h_iso_a.gene_uuid, "hit_protein_ids": f"{h_iso_a.protein_id}, {h_iso_b.protein_id}", "hit_locus_tag": h_gene.locus_tag, "hit_gene_id": h_gene.gene_id, "hit_db_xref": h_gene.db_xref, "hit_as_types": hit_as_types, "hit_as_types_max": max([len(as_type) for as_type in hit_as_types], default=0), "positive": m.positive, "predicted_positive": m.predicted_positive, "predicted_positive_probability": m.predicted_positive_probability, "isoform_blast_score": m.isoform_blast_score, "splicing_difference": m.splicing_difference, "splicing_similarity": m.splicing_similarity, "splicing_dissimilarity": m.splicing_dissimilarity, "query_gene_uuid": q_iso_a.gene_uuid, "query_protein_ids": f"{q_iso_a.protein_id}, {q_iso_b.protein_id}", "query_locus_tag": q_gene.locus_tag, "query_gene_id": q_gene.gene_id, "query_db_xref": q_gene.db_xref, "query_as_types": query_as_types, "query_as_types_max": max([len(as_type) for as_type in query_as_types], default=0), "intersection_as_types": intersection_as_types, "intersection_as_types_len": len(intersection_as_types), "conservative": int(m.predicted_positive), "conservative_probability": m.predicted_positive_probability, "db_name": q_file.db_name, } data.append(row) df = pd.DataFrame(data) return df def get_isoforms_to_file(launch_folder: str) -> Mapping[uuid.UUID, str]: results_folder = pathutil.create_folder(launch_folder, "blast_results") isoforms_to_file: Dict[uuid.UUID, str] = {} for group_folder in tqdm(pathutil.get_sub_directories(results_folder)): for result_file in pathutil.file_list(group_folder, ".json"): with open(result_file, "r") as f: try: data = json.load(f) except Exception as e: _logger.exception("exception in file result file") continue query_iso_str = data["BlastOutput2"]["report"]["results"]["search"]["query_title"] isoforms_to_file[uuid.UUID(query_iso_str)] = result_file return isoforms_to_file
39.435185
129
0.681146
import os import uuid from collections import defaultdict from itertools import chain from typing import Dict, List, Mapping, Optional, Tuple import pandas as pd from kd_common import excel, logutil, pathutil from kd_splicing import as_type, blast, database, features, ml, performance, pipeline from kd_splicing.dataset.models import Dataset from kd_splicing.dump import dump from kd_splicing.models import FormattedResults, IsoformTuple, Match, SimpleMatch, Queries from kd_splicing.models import SearchStatus import itertools from tqdm import tqdm import json _logger = logutil.get_logger(__name__) def find_in_queries( protein_ids_str: str, isoforms_to_duplicates: Mapping[uuid.UUID, List[uuid.UUID]], db: database.models.DB, matches_dict: Mapping[IsoformTuple, List[SimpleMatch]] ) -> Optional[IsoformTuple]: tup = str_to_isoform_tuple(db, protein_ids_str) for a in isoforms_to_duplicates[tup.a]: for b in isoforms_to_duplicates[tup.b]: dup = IsoformTuple(a,b) if dup in matches_dict: return dup return None tein_id in protein_ids_str.split(",")] assert len(protein_ids) == 2 return IsoformTuple( db.protein_id_to_isoform[protein_ids[0]], db.protein_id_to_isoform[protein_ids[1]]) def isoform_tuple_to_protein_ids(db: database.models.DB, iso_tuple: IsoformTuple) -> str: return f"{db.isoforms[iso_tuple.a].protein_id},{db.isoforms[iso_tuple.b].protein_id}" def tuples_to_queries(tuples: List[IsoformTuple], num_groups: int = 20) -> Queries: isoforms = sorted(list(set(chain.from_iterable( (query_isoforms.a, query_isoforms.b) for query_isoforms in tuples )))) group_count = itertools.cycle(range(0, num_groups)) isoform_to_group = {} isoform_to_idx = {} group_size: Dict[int, int] = defaultdict(int) for iso in isoforms: group = next(group_count) isoform_to_group[iso] = group isoform_to_idx[iso] = group_size[group] group_size[group] += 1 return Queries( tuples=tuples, isoforms=isoforms, isoform_to_idx=isoform_to_idx, isoform_to_group=isoform_to_group, ) def best_match_per_organism(matches: List[Match]) -> List[Match]: query_organism_to_match: Dict[Tuple[IsoformTuple, str], Match] = {} for m in matches: key = (m.query_isoforms, m.hit_organism) best_match = query_organism_to_match.get(key) if not best_match or best_match.predicted_positive_probability < m.predicted_positive_probability: query_organism_to_match[key] = m return list(query_organism_to_match.values()) isoforms.values(): gene = db.genes[isoform.gene_uuid] record = db.records[gene.record_uuid] organism_to_isoform_count[record.organism] += 1 for key, value in sorted(organism_to_isoform_count.items(), key=lambda p: p[1]): print(key, ",", value) def calc_performance(matches: List[Match]) -> None: predicted = [m.predicted_positive for m in matches] correct = [m.positive for m in matches] _logger.info( f"Performance:\n{pd.Series(performance.binary_y_performance(correct, predicted))}") def db_organisms_stats(db: database.models.DB, db_folder: str) -> None: df = database.utils.to_df(db) d1 = df["organism"].value_counts().reset_index() excel.write(d1, os.path.join(pathutil.create_folder( db_folder, "stats"), os.path.basename(db_folder) + "_db_organisms.xlsx")) d2 = df[df["db_name"] == "refseq"]["organism"].value_counts().reset_index() excel.write(d2, os.path.join(pathutil.create_folder( db_folder, "stats"), os.path.basename(db_folder) + "_db_organisms_refseq.xlsx")) d3 = df[df["db_name"] == "genbank"]["organism"].value_counts().reset_index() excel.write(d3, os.path.join(pathutil.create_folder( db_folder, "stats"), os.path.basename(db_folder) + "_db_organisms_genbank.xlsx")) d4 = df[df["db_name_src"] == "refseq"]["organism"].value_counts().reset_index() excel.write(d4, os.path.join(pathutil.create_folder( db_folder, "stats"), os.path.basename(db_folder) + "_db_organisms_refseq_src.xlsx")) d5 = df[df["db_name_src"] == "genbank"]["organism"].value_counts().reset_index() excel.write(d5, os.path.join(pathutil.create_folder( db_folder, "stats"), os.path.basename(db_folder) + "_db_organisms_genbank_src.xlsx")) def db_missed_files(p: pipeline.Pipeline) -> None: def prepare(s: str) -> str: s = os.path.basename(s) s = ".".join(s.split(".")[:-1]) return s files = pathutil.file_list(p.folder_archive, p.archive_extension) extracted = pathutil.file_list(p.folder_extracted) files.sort() extracted = [prepare(f) for f in extracted] files = [prepare(f) for f in files] print(sorted(list(set(files) - set(extracted)))) t_protein_ids.split(",") assert len(protein_ids) == 2 protein_id_to_isoform = { i.protein_id: i.uuid for i in db.isoforms.values()} test_query_isoforms = IsoformTuple( protein_id_to_isoform[protein_ids[0]], protein_id_to_isoform[protein_ids[1]]) train_ds = [m for m in ds if m.query_isoforms != test_query_isoforms] test_ds = [m for m in ds if m.query_isoforms == test_query_isoforms] d = ml.Detector() d.fit(train_ds) d.transform(test_ds) calc_performance(test_ds) folder = pathutil.create_folder(launch_folder, "cross_validation") dump(db, folder, test_ds) def dump_single_query_simple_matches( db: database.models.DB, launch_folder: str, matches_dict: Mapping[IsoformTuple, List[SimpleMatch]], protein_ids_str: str, isoforms_to_duplicates: Mapping[uuid.UUID, List[uuid.UUID]], ) -> None: query_isoforms = find_in_queries(protein_ids_str, isoforms_to_duplicates, db, matches_dict) if not query_isoforms: print("No such query in precalculated queries") return simple_matches = matches_dict[query_isoforms] matches = features.convert_matches({query_isoforms: simple_matches}) dump(db, pathutil.create_folder(launch_folder, "matches_simple_single", protein_ids_str), matches) def calc_features_and_dump_single( db: database.models.DB, launch_folder: str, queries: Queries, detector: ml.Detector, protein_ids_str: str, isoforms_to_duplicates: Mapping[uuid.UUID, List[uuid.UUID]], matches_dict: Mapping[IsoformTuple, List[SimpleMatch]], ) -> List[Match]: query_isoforms = find_in_queries(protein_ids_str, isoforms_to_duplicates, db, matches_dict) if not query_isoforms: print("No such query in precalculated queries") return matches = features.calc(db, launch_folder, queries, [query_isoforms]) detector.transform(matches) dump(db, pathutil.create_folder(launch_folder, "matches_single", protein_ids_str), matches) return matches r, status: SearchStatus = SearchStatus.construct(progress = 0, description = ""), isoforms_to_duplicates: Optional[Mapping[uuid.UUID, List[uuid.UUID]]] = None, ) -> str: status.set(0, "Preparing queries") tuples = [str_to_isoform_tuple(db, query_proteins) for query_proteins in query_protein_ids_str] queries = tuples_to_queries(tuples, num_groups=1) name = ";".join(query_protein_ids_str) return search_queries(db, p, detector, queries, name, blast_db_path, status, isoforms_to_duplicates) def search_queries( db: database.models.DB, p: pipeline.Pipeline, detector: ml.Detector, queries: Queries, name: str, blast_db_path: str, status: SearchStatus, isoforms_to_duplicates: Optional[Mapping[uuid.UUID, List[uuid.UUID]]] = None, ) -> str: status.set(10, "BLAST running") blast.create_queires(db, queries, p.launch_folder) blast.run(p.launch_folder, blast_db_path, parallel = False) status.set(20, "Reading BLAST results") queries.isoform_to_file = get_isoforms_to_file(p.launch_folder) status.set(30, "Calculating features") matches = features.calc(db, p.launch_folder, queries) status.set(40, "Running ml model") detector.transform(matches) result_folder = pathutil.create_folder(p.launch_folder, "search_single", name) status.set(50, "Preparing results") dump(db, result_folder, matches, isoforms_to_duplicates) return result_folder def matches_to_df( db: database.models.DB, isoforms_to_duplicates: Mapping[uuid.UUID, List[uuid.UUID]], matches: List[Match], ) -> pd.DataFrame: data = [] for m in tqdm(matches): q_iso_a = db.isoforms[m.query_isoforms.a] q_iso_b = db.isoforms[m.query_isoforms.b] q_gene = db.genes[q_iso_a.gene_uuid] q_record = db.records[q_gene.record_uuid] q_file = db.files[q_record.file_uuid] h_iso_a = db.isoforms[m.hit_isoforms.a] h_iso_b = db.isoforms[m.hit_isoforms.b] h_gene = db.genes[h_iso_a.gene_uuid] h_record = db.records[h_gene.record_uuid] h_file = db.files[h_record.file_uuid] hit_as_types = as_type.get_isoforms_as_types(db, isoforms_to_duplicates, h_iso_a.uuid, h_iso_b.uuid) query_as_types = as_type.get_isoforms_as_types(db, isoforms_to_duplicates, q_iso_a.uuid, q_iso_b.uuid) intersection_as_types = hit_as_types & query_as_types row = { "query_isoforms": m.query_isoforms, "hit_isoforms": m.hit_isoforms, "hit_organism": m.hit_organism, "hit_db_name": m.hit_db_name, "hit_gene_uuid": h_iso_a.gene_uuid, "hit_protein_ids": f"{h_iso_a.protein_id}, {h_iso_b.protein_id}", "hit_locus_tag": h_gene.locus_tag, "hit_gene_id": h_gene.gene_id, "hit_db_xref": h_gene.db_xref, "hit_as_types": hit_as_types, "hit_as_types_max": max([len(as_type) for as_type in hit_as_types], default=0), "positive": m.positive, "predicted_positive": m.predicted_positive, "predicted_positive_probability": m.predicted_positive_probability, "isoform_blast_score": m.isoform_blast_score, "splicing_difference": m.splicing_difference, "splicing_similarity": m.splicing_similarity, "splicing_dissimilarity": m.splicing_dissimilarity, "query_gene_uuid": q_iso_a.gene_uuid, "query_protein_ids": f"{q_iso_a.protein_id}, {q_iso_b.protein_id}", "query_locus_tag": q_gene.locus_tag, "query_gene_id": q_gene.gene_id, "query_db_xref": q_gene.db_xref, "query_as_types": query_as_types, "query_as_types_max": max([len(as_type) for as_type in query_as_types], default=0), "intersection_as_types": intersection_as_types, "intersection_as_types_len": len(intersection_as_types), "conservative": int(m.predicted_positive), "conservative_probability": m.predicted_positive_probability, "db_name": q_file.db_name, } data.append(row) df = pd.DataFrame(data) return df def get_isoforms_to_file(launch_folder: str) -> Mapping[uuid.UUID, str]: results_folder = pathutil.create_folder(launch_folder, "blast_results") isoforms_to_file: Dict[uuid.UUID, str] = {} for group_folder in tqdm(pathutil.get_sub_directories(results_folder)): for result_file in pathutil.file_list(group_folder, ".json"): with open(result_file, "r") as f: try: data = json.load(f) except Exception as e: _logger.exception("exception in file result file") continue query_iso_str = data["BlastOutput2"]["report"]["results"]["search"]["query_title"] isoforms_to_file[uuid.UUID(query_iso_str)] = result_file return isoforms_to_file
true
true
f7fe9edce30814d34454bfea14b8ac92cf00915e
22,646
py
Python
efficientdet/anchors.py
HyunjiEllenPak/automl
fedf04adf12c5fd11045ea06e2f5c11a5a5490c4
[ "Apache-2.0" ]
null
null
null
efficientdet/anchors.py
HyunjiEllenPak/automl
fedf04adf12c5fd11045ea06e2f5c11a5a5490c4
[ "Apache-2.0" ]
null
null
null
efficientdet/anchors.py
HyunjiEllenPak/automl
fedf04adf12c5fd11045ea06e2f5c11a5a5490c4
[ "Apache-2.0" ]
null
null
null
# Lint as: python3 # Copyright 2020 Google Research. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Anchor definition. This module is borrowed from TPU RetinaNet implementation: https://github.com/tensorflow/tpu/blob/master/models/official/retinanet/anchors.py """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from absl import logging import numpy as np import tensorflow.compat.v1 as tf import utils from object_detection import argmax_matcher from object_detection import box_list from object_detection import faster_rcnn_box_coder from object_detection import region_similarity_calculator from object_detection import target_assigner # The minimum score to consider a logit for identifying detections. MIN_CLASS_SCORE = -5.0 # The score for a dummy detection _DUMMY_DETECTION_SCORE = -1e5 # The maximum number of (anchor,class) pairs to keep for non-max suppression. MAX_DETECTION_POINTS = 5000 # The maximum number of detections per image. MAX_DETECTIONS_PER_IMAGE = 100 # The minimal score threshold. MIN_SCORE_THRESH = 0.4 def sigmoid(x): """Sigmoid function for use with Numpy for CPU evaluation.""" return 1 / (1 + np.exp(-x)) def decode_box_outputs(rel_codes, anchors): """Transforms relative regression coordinates to absolute positions. Network predictions are normalized and relative to a given anchor; this reverses the transformation and outputs absolute coordinates for the input image. Args: rel_codes: box regression targets. anchors: anchors on all feature levels. Returns: outputs: bounding boxes. """ ycenter_a = (anchors[0] + anchors[2]) / 2 xcenter_a = (anchors[1] + anchors[3]) / 2 ha = anchors[2] - anchors[0] wa = anchors[3] - anchors[1] ty, tx, th, tw = rel_codes w = np.exp(tw) * wa h = np.exp(th) * ha ycenter = ty * ha + ycenter_a xcenter = tx * wa + xcenter_a ymin = ycenter - h / 2. xmin = xcenter - w / 2. ymax = ycenter + h / 2. xmax = xcenter + w / 2. return np.column_stack([ymin, xmin, ymax, xmax]) def decode_box_outputs_tf(rel_codes, anchors): """Transforms relative regression coordinates to absolute positions. Network predictions are normalized and relative to a given anchor; this reverses the transformation and outputs absolute coordinates for the input image. Args: rel_codes: box regression targets. anchors: anchors on all feature levels. Returns: outputs: bounding boxes. """ ycenter_a = (anchors[0] + anchors[2]) / 2 xcenter_a = (anchors[1] + anchors[3]) / 2 ha = anchors[2] - anchors[0] wa = anchors[3] - anchors[1] ty, tx, th, tw = tf.unstack(rel_codes, num=4) w = tf.math.exp(tw) * wa h = tf.math.exp(th) * ha ycenter = ty * ha + ycenter_a xcenter = tx * wa + xcenter_a ymin = ycenter - h / 2. xmin = xcenter - w / 2. ymax = ycenter + h / 2. xmax = xcenter + w / 2. return tf.stack([ymin, xmin, ymax, xmax], axis=1) @tf.autograph.to_graph def nms_tf(dets, thresh): """Non-maximum suppression with tf graph mode.""" x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 4] areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = tf.argsort(scores, direction='DESCENDING') keep = tf.TensorArray(tf.int32, size=0, dynamic_size=True) index = 0 while tf.size(order) > 0: i = order[0] keep = keep.write(index, i) xx1 = tf.maximum(x1[i], tf.gather(x1, order[1:])) yy1 = tf.maximum(y1[i], tf.gather(y1, order[1:])) xx2 = tf.minimum(x2[i], tf.gather(x2, order[1:])) yy2 = tf.minimum(y2[i], tf.gather(y2, order[1:])) w = tf.maximum(0.0, xx2 - xx1 + 1) h = tf.maximum(0.0, yy2 - yy1 + 1) intersection = w * h overlap = intersection / ( areas[i] + tf.gather(areas, order[1:]) - intersection) inds = tf.where_v2(overlap <= thresh) order = tf.concat(tf.gather(order, inds + 1), axis=1) order = tf.squeeze(order, axis=-1) index += 1 return keep.stack() def nms(dets, thresh): """Non-maximum suppression.""" x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 4] areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = scores.argsort()[::-1] keep = [] while order.size > 0: i = order[0] keep.append(i) xx1 = np.maximum(x1[i], x1[order[1:]]) yy1 = np.maximum(y1[i], y1[order[1:]]) xx2 = np.minimum(x2[i], x2[order[1:]]) yy2 = np.minimum(y2[i], y2[order[1:]]) w = np.maximum(0.0, xx2 - xx1 + 1) h = np.maximum(0.0, yy2 - yy1 + 1) intersection = w * h overlap = intersection / (areas[i] + areas[order[1:]] - intersection) inds = np.where(overlap <= thresh)[0] order = order[inds + 1] return keep def _generate_anchor_configs(feat_sizes, min_level, max_level, num_scales, aspect_ratios): """Generates mapping from output level to a list of anchor configurations. A configuration is a tuple of (num_anchors, scale, aspect_ratio). Args: feat_sizes: list of dict of integer numbers of feature map sizes. min_level: integer number of minimum level of the output feature pyramid. max_level: integer number of maximum level of the output feature pyramid. num_scales: integer number representing intermediate scales added on each level. For instances, num_scales=2 adds two additional anchor scales [2^0, 2^0.5] on each level. aspect_ratios: list of tuples representing the aspect ratio anchors added on each level. For instances, aspect_ratios = [(1, 1), (1.4, 0.7), (0.7, 1.4)] adds three anchors on each level. Returns: anchor_configs: a dictionary with keys as the levels of anchors and values as a list of anchor configuration. """ anchor_configs = {} for level in range(min_level, max_level + 1): anchor_configs[level] = [] for scale_octave in range(num_scales): for aspect in aspect_ratios: anchor_configs[level].append( ((feat_sizes[0]['height'] / float(feat_sizes[level]['height']), feat_sizes[0]['width'] / float(feat_sizes[level]['width'])), scale_octave / float(num_scales), aspect)) return anchor_configs def _generate_anchor_boxes(image_size, anchor_scale, anchor_configs): """Generates multiscale anchor boxes. Args: image_size: tuple of integer numbers of input image size. anchor_scale: float number representing the scale of size of the base anchor to the feature stride 2^level. anchor_configs: a dictionary with keys as the levels of anchors and values as a list of anchor configuration. Returns: anchor_boxes: a numpy array with shape [N, 4], which stacks anchors on all feature levels. Raises: ValueError: input size must be the multiple of largest feature stride. """ boxes_all = [] for _, configs in anchor_configs.items(): boxes_level = [] for config in configs: stride, octave_scale, aspect = config base_anchor_size_x = anchor_scale * stride[1] * 2**octave_scale base_anchor_size_y = anchor_scale * stride[0] * 2**octave_scale anchor_size_x_2 = base_anchor_size_x * aspect[0] / 2.0 anchor_size_y_2 = base_anchor_size_y * aspect[1] / 2.0 x = np.arange(stride[1] / 2, image_size[1], stride[1]) y = np.arange(stride[0] / 2, image_size[0], stride[0]) xv, yv = np.meshgrid(x, y) xv = xv.reshape(-1) yv = yv.reshape(-1) boxes = np.vstack((yv - anchor_size_y_2, xv - anchor_size_x_2, yv + anchor_size_y_2, xv + anchor_size_x_2)) boxes = np.swapaxes(boxes, 0, 1) boxes_level.append(np.expand_dims(boxes, axis=1)) # concat anchors on the same level to the reshape NxAx4 boxes_level = np.concatenate(boxes_level, axis=1) boxes_all.append(boxes_level.reshape([-1, 4])) anchor_boxes = np.vstack(boxes_all) return anchor_boxes def _generate_detections_tf(cls_outputs, box_outputs, anchor_boxes, indices, classes, image_id, image_scale, min_score_thresh=MIN_SCORE_THRESH, max_boxes_to_draw=MAX_DETECTIONS_PER_IMAGE, soft_nms_sigma=0.0, iou_threshold=0.5, use_native_nms=True): """Generates detections with model outputs and anchors. Args: cls_outputs: a numpy array with shape [N, 1], which has the highest class scores on all feature levels. The N is the number of selected top-K total anchors on all levels. (k being MAX_DETECTION_POINTS) box_outputs: a numpy array with shape [N, 4], which stacks box regression outputs on all feature levels. The N is the number of selected top-k total anchors on all levels. (k being MAX_DETECTION_POINTS) anchor_boxes: a numpy array with shape [N, 4], which stacks anchors on all feature levels. The N is the number of selected top-k total anchors on all levels. indices: a numpy array with shape [N], which is the indices from top-k selection. classes: a numpy array with shape [N], which represents the class prediction on all selected anchors from top-k selection. image_id: an integer number to specify the image id. image_scale: a float tensor representing the scale between original image and input image for the detector. It is used to rescale detections for evaluating with the original groundtruth annotations. min_score_thresh: A float representing the threshold for deciding when to remove boxes based on score. max_boxes_to_draw: Max number of boxes to draw. soft_nms_sigma: A scalar float representing the Soft NMS sigma parameter; See Bodla et al, https://arxiv.org/abs/1704.04503). When `soft_nms_sigma=0.0` (which is default), we fall back to standard (hard) NMS. iou_threshold: A float representing the threshold for deciding whether boxes overlap too much with respect to IOU. use_native_nms: a bool that indicates whether to use native nms. Returns: detections: detection results in a tensor with each row representing [image_id, y, x, height, width, score, class] """ logging.info('Using tf version of post-processing.') anchor_boxes = tf.gather(anchor_boxes, indices) scores = tf.math.sigmoid(cls_outputs) # apply bounding box regression to anchors boxes = decode_box_outputs_tf( tf.transpose(box_outputs, [1, 0]), tf.transpose(anchor_boxes, [1, 0])) if use_native_nms: logging.info('Using native nms.') top_detection_idx, scores = tf.image.non_max_suppression_with_scores( boxes, scores, max_boxes_to_draw, iou_threshold=iou_threshold, score_threshold=min_score_thresh, soft_nms_sigma=soft_nms_sigma) boxes = tf.gather(boxes, top_detection_idx) else: logging.info('Using customized nms.') scores = tf.expand_dims(scores, axis=1) all_detections = tf.concat([boxes, scores], axis=1) top_detection_idx = nms_tf(all_detections, iou_threshold) detections = tf.gather(all_detections, top_detection_idx) scores = detections[:, 4] boxes = detections[:, :4] height = boxes[:, 2] - boxes[:, 0] width = boxes[:, 3] - boxes[:, 1] detections = tf.stack([ tf.cast(tf.repeat(image_id, tf.size(top_detection_idx)), tf.float32), boxes[:, 0] * image_scale, boxes[:, 1] * image_scale, height * image_scale, width * image_scale, scores, tf.cast(tf.gather(classes, top_detection_idx) + 1, tf.float32) ], axis=1) return detections def _generate_detections(cls_outputs, box_outputs, anchor_boxes, indices, classes, image_id, image_scale, num_classes, max_boxes_to_draw): """Generates detections with model outputs and anchors. Args: cls_outputs: a numpy array with shape [N, 1], which has the highest class scores on all feature levels. The N is the number of selected top-K total anchors on all levels. (k being MAX_DETECTION_POINTS) box_outputs: a numpy array with shape [N, 4], which stacks box regression outputs on all feature levels. The N is the number of selected top-k total anchors on all levels. (k being MAX_DETECTION_POINTS) anchor_boxes: a numpy array with shape [N, 4], which stacks anchors on all feature levels. The N is the number of selected top-k total anchors on all levels. indices: a numpy array with shape [N], which is the indices from top-k selection. classes: a numpy array with shape [N], which represents the class prediction on all selected anchors from top-k selection. image_id: an integer number to specify the image id. image_scale: a float tensor representing the scale between original image and input image for the detector. It is used to rescale detections for evaluating with the original groundtruth annotations. num_classes: a integer that indicates the number of classes. max_boxes_to_draw: max number of boxes to draw per image. Returns: detections: detection results in a tensor with each row representing [image_id, x, y, width, height, score, class] """ logging.info('Using numpy version of post-processing.') anchor_boxes = anchor_boxes[indices, :] scores = sigmoid(cls_outputs) # apply bounding box regression to anchors boxes = decode_box_outputs( box_outputs.swapaxes(0, 1), anchor_boxes.swapaxes(0, 1)) boxes = boxes[:, [1, 0, 3, 2]] # run class-wise nms detections = [] for c in range(num_classes): indices = np.where(classes == c)[0] if indices.shape[0] == 0: continue boxes_cls = boxes[indices, :] scores_cls = scores[indices] # Select top-scoring boxes in each class and apply non-maximum suppression # (nms) for boxes in the same class. The selected boxes from each class are # then concatenated for the final detection outputs. all_detections_cls = np.column_stack((boxes_cls, scores_cls)) top_detection_idx = nms(all_detections_cls, 0.5) top_detections_cls = all_detections_cls[top_detection_idx] top_detections_cls[:, 2] -= top_detections_cls[:, 0] top_detections_cls[:, 3] -= top_detections_cls[:, 1] top_detections_cls = np.column_stack( (np.repeat(image_id, len(top_detection_idx)), top_detections_cls, np.repeat(c + 1, len(top_detection_idx))) ) detections.append(top_detections_cls) def _generate_dummy_detections(number): detections_dummy = np.zeros((number, 7), dtype=np.float32) detections_dummy[:, 0] = image_id[0] detections_dummy[:, 5] = _DUMMY_DETECTION_SCORE return detections_dummy if detections: detections = np.vstack(detections) # take final 100 detections indices = np.argsort(-detections[:, -2]) detections = np.array( detections[indices[0:max_boxes_to_draw]], dtype=np.float32) # Add dummy detections to fill up to 100 detections n = max(max_boxes_to_draw - len(detections), 0) detections_dummy = _generate_dummy_detections(n) detections = np.vstack([detections, detections_dummy]) else: detections = _generate_dummy_detections(max_boxes_to_draw) detections[:, 1:5] *= image_scale return detections class Anchors(object): """RetinaNet Anchors class.""" def __init__(self, min_level, max_level, num_scales, aspect_ratios, anchor_scale, image_size): """Constructs multiscale RetinaNet anchors. Args: min_level: integer number of minimum level of the output feature pyramid. max_level: integer number of maximum level of the output feature pyramid. num_scales: integer number representing intermediate scales added on each level. For instances, num_scales=2 adds two additional anchor scales [2^0, 2^0.5] on each level. aspect_ratios: list of tuples representing the aspect ratio anchors added on each level. For instances, aspect_ratios = [(1, 1), (1.4, 0.7), (0.7, 1.4)] adds three anchors on each level. anchor_scale: float number representing the scale of size of the base anchor to the feature stride 2^level. image_size: integer number or tuple of integer number of input image size. """ self.min_level = min_level self.max_level = max_level self.num_scales = num_scales self.aspect_ratios = aspect_ratios self.anchor_scale = anchor_scale if isinstance(image_size, int): self.image_size = (image_size, image_size) else: self.image_size = image_size self.feat_sizes = utils.get_feat_sizes(image_size, max_level) self.config = self._generate_configs() self.boxes = self._generate_boxes() def _generate_configs(self): """Generate configurations of anchor boxes.""" return _generate_anchor_configs(self.feat_sizes, self.min_level, self.max_level, self.num_scales, self.aspect_ratios) def _generate_boxes(self): """Generates multiscale anchor boxes.""" boxes = _generate_anchor_boxes(self.image_size, self.anchor_scale, self.config) boxes = tf.convert_to_tensor(boxes, dtype=tf.float32) return boxes def get_anchors_per_location(self): return self.num_scales * len(self.aspect_ratios) class AnchorLabeler(object): """Labeler for multiscale anchor boxes.""" def __init__(self, anchors, num_classes, match_threshold=0.5): """Constructs anchor labeler to assign labels to anchors. Args: anchors: an instance of class Anchors. num_classes: integer number representing number of classes in the dataset. match_threshold: float number between 0 and 1 representing the threshold to assign positive labels for anchors. """ similarity_calc = region_similarity_calculator.IouSimilarity() matcher = argmax_matcher.ArgMaxMatcher( match_threshold, unmatched_threshold=match_threshold, negatives_lower_than_unmatched=True, force_match_for_each_row=True) box_coder = faster_rcnn_box_coder.FasterRcnnBoxCoder() self._target_assigner = target_assigner.TargetAssigner( similarity_calc, matcher, box_coder) self._anchors = anchors self._match_threshold = match_threshold self._num_classes = num_classes def _unpack_labels(self, labels): """Unpacks an array of labels into multiscales labels.""" labels_unpacked = collections.OrderedDict() anchors = self._anchors count = 0 for level in range(anchors.min_level, anchors.max_level + 1): feat_size = anchors.feat_sizes[level] steps = feat_size['height'] * feat_size[ 'width'] * anchors.get_anchors_per_location() indices = tf.range(count, count + steps) count += steps labels_unpacked[level] = tf.reshape( tf.gather(labels, indices), [feat_size['height'], feat_size['width'], -1]) return labels_unpacked def label_anchors(self, gt_boxes, gt_labels): """Labels anchors with ground truth inputs. Args: gt_boxes: A float tensor with shape [N, 4] representing groundtruth boxes. For each row, it stores [y0, x0, y1, x1] for four corners of a box. gt_labels: A integer tensor with shape [N, 1] representing groundtruth classes. Returns: cls_targets_dict: ordered dictionary with keys [min_level, min_level+1, ..., max_level]. The values are tensor with shape [height_l, width_l, num_anchors]. The height_l and width_l represent the dimension of class logits at l-th level. box_targets_dict: ordered dictionary with keys [min_level, min_level+1, ..., max_level]. The values are tensor with shape [height_l, width_l, num_anchors * 4]. The height_l and width_l represent the dimension of bounding box regression output at l-th level. num_positives: scalar tensor storing number of positives in an image. """ gt_box_list = box_list.BoxList(gt_boxes) anchor_box_list = box_list.BoxList(self._anchors.boxes) # cls_weights, box_weights are not used cls_targets, _, box_targets, _, matches = self._target_assigner.assign( anchor_box_list, gt_box_list, gt_labels) # class labels start from 1 and the background class = -1 cls_targets -= 1 cls_targets = tf.cast(cls_targets, tf.int32) # Unpack labels. cls_targets_dict = self._unpack_labels(cls_targets) box_targets_dict = self._unpack_labels(box_targets) num_positives = tf.reduce_sum( tf.cast(tf.not_equal(matches.match_results, -1), tf.float32)) return cls_targets_dict, box_targets_dict, num_positives def generate_detections(self, cls_outputs, box_outputs, indices, classes, image_id, image_scale, min_score_thresh=MIN_SCORE_THRESH, max_boxes_to_draw=MAX_DETECTIONS_PER_IMAGE, disable_pyfun=None): """Generate detections based on class and box predictions.""" if disable_pyfun: return _generate_detections_tf( cls_outputs, box_outputs, self._anchors.boxes, indices, classes, image_id, image_scale, min_score_thresh=min_score_thresh, max_boxes_to_draw=max_boxes_to_draw) else: return tf.py_func(_generate_detections, [ cls_outputs, box_outputs, self._anchors.boxes, indices, classes, image_id, image_scale, self._num_classes, max_boxes_to_draw, ], tf.float32)
38.318105
82
0.675307
from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from absl import logging import numpy as np import tensorflow.compat.v1 as tf import utils from object_detection import argmax_matcher from object_detection import box_list from object_detection import faster_rcnn_box_coder from object_detection import region_similarity_calculator from object_detection import target_assigner MIN_CLASS_SCORE = -5.0 _DUMMY_DETECTION_SCORE = -1e5 MAX_DETECTION_POINTS = 5000 MAX_DETECTIONS_PER_IMAGE = 100 MIN_SCORE_THRESH = 0.4 def sigmoid(x): return 1 / (1 + np.exp(-x)) def decode_box_outputs(rel_codes, anchors): ycenter_a = (anchors[0] + anchors[2]) / 2 xcenter_a = (anchors[1] + anchors[3]) / 2 ha = anchors[2] - anchors[0] wa = anchors[3] - anchors[1] ty, tx, th, tw = rel_codes w = np.exp(tw) * wa h = np.exp(th) * ha ycenter = ty * ha + ycenter_a xcenter = tx * wa + xcenter_a ymin = ycenter - h / 2. xmin = xcenter - w / 2. ymax = ycenter + h / 2. xmax = xcenter + w / 2. return np.column_stack([ymin, xmin, ymax, xmax]) def decode_box_outputs_tf(rel_codes, anchors): ycenter_a = (anchors[0] + anchors[2]) / 2 xcenter_a = (anchors[1] + anchors[3]) / 2 ha = anchors[2] - anchors[0] wa = anchors[3] - anchors[1] ty, tx, th, tw = tf.unstack(rel_codes, num=4) w = tf.math.exp(tw) * wa h = tf.math.exp(th) * ha ycenter = ty * ha + ycenter_a xcenter = tx * wa + xcenter_a ymin = ycenter - h / 2. xmin = xcenter - w / 2. ymax = ycenter + h / 2. xmax = xcenter + w / 2. return tf.stack([ymin, xmin, ymax, xmax], axis=1) @tf.autograph.to_graph def nms_tf(dets, thresh): x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 4] areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = tf.argsort(scores, direction='DESCENDING') keep = tf.TensorArray(tf.int32, size=0, dynamic_size=True) index = 0 while tf.size(order) > 0: i = order[0] keep = keep.write(index, i) xx1 = tf.maximum(x1[i], tf.gather(x1, order[1:])) yy1 = tf.maximum(y1[i], tf.gather(y1, order[1:])) xx2 = tf.minimum(x2[i], tf.gather(x2, order[1:])) yy2 = tf.minimum(y2[i], tf.gather(y2, order[1:])) w = tf.maximum(0.0, xx2 - xx1 + 1) h = tf.maximum(0.0, yy2 - yy1 + 1) intersection = w * h overlap = intersection / ( areas[i] + tf.gather(areas, order[1:]) - intersection) inds = tf.where_v2(overlap <= thresh) order = tf.concat(tf.gather(order, inds + 1), axis=1) order = tf.squeeze(order, axis=-1) index += 1 return keep.stack() def nms(dets, thresh): x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 4] areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = scores.argsort()[::-1] keep = [] while order.size > 0: i = order[0] keep.append(i) xx1 = np.maximum(x1[i], x1[order[1:]]) yy1 = np.maximum(y1[i], y1[order[1:]]) xx2 = np.minimum(x2[i], x2[order[1:]]) yy2 = np.minimum(y2[i], y2[order[1:]]) w = np.maximum(0.0, xx2 - xx1 + 1) h = np.maximum(0.0, yy2 - yy1 + 1) intersection = w * h overlap = intersection / (areas[i] + areas[order[1:]] - intersection) inds = np.where(overlap <= thresh)[0] order = order[inds + 1] return keep def _generate_anchor_configs(feat_sizes, min_level, max_level, num_scales, aspect_ratios): anchor_configs = {} for level in range(min_level, max_level + 1): anchor_configs[level] = [] for scale_octave in range(num_scales): for aspect in aspect_ratios: anchor_configs[level].append( ((feat_sizes[0]['height'] / float(feat_sizes[level]['height']), feat_sizes[0]['width'] / float(feat_sizes[level]['width'])), scale_octave / float(num_scales), aspect)) return anchor_configs def _generate_anchor_boxes(image_size, anchor_scale, anchor_configs): boxes_all = [] for _, configs in anchor_configs.items(): boxes_level = [] for config in configs: stride, octave_scale, aspect = config base_anchor_size_x = anchor_scale * stride[1] * 2**octave_scale base_anchor_size_y = anchor_scale * stride[0] * 2**octave_scale anchor_size_x_2 = base_anchor_size_x * aspect[0] / 2.0 anchor_size_y_2 = base_anchor_size_y * aspect[1] / 2.0 x = np.arange(stride[1] / 2, image_size[1], stride[1]) y = np.arange(stride[0] / 2, image_size[0], stride[0]) xv, yv = np.meshgrid(x, y) xv = xv.reshape(-1) yv = yv.reshape(-1) boxes = np.vstack((yv - anchor_size_y_2, xv - anchor_size_x_2, yv + anchor_size_y_2, xv + anchor_size_x_2)) boxes = np.swapaxes(boxes, 0, 1) boxes_level.append(np.expand_dims(boxes, axis=1)) boxes_level = np.concatenate(boxes_level, axis=1) boxes_all.append(boxes_level.reshape([-1, 4])) anchor_boxes = np.vstack(boxes_all) return anchor_boxes def _generate_detections_tf(cls_outputs, box_outputs, anchor_boxes, indices, classes, image_id, image_scale, min_score_thresh=MIN_SCORE_THRESH, max_boxes_to_draw=MAX_DETECTIONS_PER_IMAGE, soft_nms_sigma=0.0, iou_threshold=0.5, use_native_nms=True): logging.info('Using tf version of post-processing.') anchor_boxes = tf.gather(anchor_boxes, indices) scores = tf.math.sigmoid(cls_outputs) boxes = decode_box_outputs_tf( tf.transpose(box_outputs, [1, 0]), tf.transpose(anchor_boxes, [1, 0])) if use_native_nms: logging.info('Using native nms.') top_detection_idx, scores = tf.image.non_max_suppression_with_scores( boxes, scores, max_boxes_to_draw, iou_threshold=iou_threshold, score_threshold=min_score_thresh, soft_nms_sigma=soft_nms_sigma) boxes = tf.gather(boxes, top_detection_idx) else: logging.info('Using customized nms.') scores = tf.expand_dims(scores, axis=1) all_detections = tf.concat([boxes, scores], axis=1) top_detection_idx = nms_tf(all_detections, iou_threshold) detections = tf.gather(all_detections, top_detection_idx) scores = detections[:, 4] boxes = detections[:, :4] height = boxes[:, 2] - boxes[:, 0] width = boxes[:, 3] - boxes[:, 1] detections = tf.stack([ tf.cast(tf.repeat(image_id, tf.size(top_detection_idx)), tf.float32), boxes[:, 0] * image_scale, boxes[:, 1] * image_scale, height * image_scale, width * image_scale, scores, tf.cast(tf.gather(classes, top_detection_idx) + 1, tf.float32) ], axis=1) return detections def _generate_detections(cls_outputs, box_outputs, anchor_boxes, indices, classes, image_id, image_scale, num_classes, max_boxes_to_draw): logging.info('Using numpy version of post-processing.') anchor_boxes = anchor_boxes[indices, :] scores = sigmoid(cls_outputs) boxes = decode_box_outputs( box_outputs.swapaxes(0, 1), anchor_boxes.swapaxes(0, 1)) boxes = boxes[:, [1, 0, 3, 2]] detections = [] for c in range(num_classes): indices = np.where(classes == c)[0] if indices.shape[0] == 0: continue boxes_cls = boxes[indices, :] scores_cls = scores[indices] all_detections_cls = np.column_stack((boxes_cls, scores_cls)) top_detection_idx = nms(all_detections_cls, 0.5) top_detections_cls = all_detections_cls[top_detection_idx] top_detections_cls[:, 2] -= top_detections_cls[:, 0] top_detections_cls[:, 3] -= top_detections_cls[:, 1] top_detections_cls = np.column_stack( (np.repeat(image_id, len(top_detection_idx)), top_detections_cls, np.repeat(c + 1, len(top_detection_idx))) ) detections.append(top_detections_cls) def _generate_dummy_detections(number): detections_dummy = np.zeros((number, 7), dtype=np.float32) detections_dummy[:, 0] = image_id[0] detections_dummy[:, 5] = _DUMMY_DETECTION_SCORE return detections_dummy if detections: detections = np.vstack(detections) indices = np.argsort(-detections[:, -2]) detections = np.array( detections[indices[0:max_boxes_to_draw]], dtype=np.float32) n = max(max_boxes_to_draw - len(detections), 0) detections_dummy = _generate_dummy_detections(n) detections = np.vstack([detections, detections_dummy]) else: detections = _generate_dummy_detections(max_boxes_to_draw) detections[:, 1:5] *= image_scale return detections class Anchors(object): def __init__(self, min_level, max_level, num_scales, aspect_ratios, anchor_scale, image_size): self.min_level = min_level self.max_level = max_level self.num_scales = num_scales self.aspect_ratios = aspect_ratios self.anchor_scale = anchor_scale if isinstance(image_size, int): self.image_size = (image_size, image_size) else: self.image_size = image_size self.feat_sizes = utils.get_feat_sizes(image_size, max_level) self.config = self._generate_configs() self.boxes = self._generate_boxes() def _generate_configs(self): return _generate_anchor_configs(self.feat_sizes, self.min_level, self.max_level, self.num_scales, self.aspect_ratios) def _generate_boxes(self): boxes = _generate_anchor_boxes(self.image_size, self.anchor_scale, self.config) boxes = tf.convert_to_tensor(boxes, dtype=tf.float32) return boxes def get_anchors_per_location(self): return self.num_scales * len(self.aspect_ratios) class AnchorLabeler(object): def __init__(self, anchors, num_classes, match_threshold=0.5): similarity_calc = region_similarity_calculator.IouSimilarity() matcher = argmax_matcher.ArgMaxMatcher( match_threshold, unmatched_threshold=match_threshold, negatives_lower_than_unmatched=True, force_match_for_each_row=True) box_coder = faster_rcnn_box_coder.FasterRcnnBoxCoder() self._target_assigner = target_assigner.TargetAssigner( similarity_calc, matcher, box_coder) self._anchors = anchors self._match_threshold = match_threshold self._num_classes = num_classes def _unpack_labels(self, labels): labels_unpacked = collections.OrderedDict() anchors = self._anchors count = 0 for level in range(anchors.min_level, anchors.max_level + 1): feat_size = anchors.feat_sizes[level] steps = feat_size['height'] * feat_size[ 'width'] * anchors.get_anchors_per_location() indices = tf.range(count, count + steps) count += steps labels_unpacked[level] = tf.reshape( tf.gather(labels, indices), [feat_size['height'], feat_size['width'], -1]) return labels_unpacked def label_anchors(self, gt_boxes, gt_labels): gt_box_list = box_list.BoxList(gt_boxes) anchor_box_list = box_list.BoxList(self._anchors.boxes) cls_targets, _, box_targets, _, matches = self._target_assigner.assign( anchor_box_list, gt_box_list, gt_labels) cls_targets -= 1 cls_targets = tf.cast(cls_targets, tf.int32) cls_targets_dict = self._unpack_labels(cls_targets) box_targets_dict = self._unpack_labels(box_targets) num_positives = tf.reduce_sum( tf.cast(tf.not_equal(matches.match_results, -1), tf.float32)) return cls_targets_dict, box_targets_dict, num_positives def generate_detections(self, cls_outputs, box_outputs, indices, classes, image_id, image_scale, min_score_thresh=MIN_SCORE_THRESH, max_boxes_to_draw=MAX_DETECTIONS_PER_IMAGE, disable_pyfun=None): if disable_pyfun: return _generate_detections_tf( cls_outputs, box_outputs, self._anchors.boxes, indices, classes, image_id, image_scale, min_score_thresh=min_score_thresh, max_boxes_to_draw=max_boxes_to_draw) else: return tf.py_func(_generate_detections, [ cls_outputs, box_outputs, self._anchors.boxes, indices, classes, image_id, image_scale, self._num_classes, max_boxes_to_draw, ], tf.float32)
true
true
f7fe9f026c543b5570b877a9844e11b56cd87aa7
3,898
py
Python
openGaussBase/testcase/GUC/WAL/Opengauss_Function_Guc_WAL_Case0052.py
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
openGaussBase/testcase/GUC/WAL/Opengauss_Function_Guc_WAL_Case0052.py
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
openGaussBase/testcase/GUC/WAL/Opengauss_Function_Guc_WAL_Case0052.py
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. """ """ Case Type : GUC Case Name : 修改enable_double_write为off,观察预期结果; Description : 1、查询enable_double_write默认值; show enable_double_write; 2、修改enable_double_write为off,重启使其生效,并校验其预期结果; gs_guc set -D {cluster/dn1} -c "enable_double_write=off" gs_om -t stop && gs_om -t start show enable_double_write; 3、重启后做简单DML 4、恢复默认值; Expect : 1、显示默认值; 2、参数修改成功,校验修改后系统参数值为off; 3、DML无报错 4、恢复默认值成功; History : """ import unittest from testcase.utils.CommonSH import CommonSH from testcase.utils.Constant import Constant from testcase.utils.Logger import Logger logger = Logger() COMMONSH = CommonSH('PrimaryDbUser') class Guctestcase(unittest.TestCase): def setUp(self): logger.info("==Opengauss_Function_Guc_WAL_Case0052开始执行==") self.constant = Constant() is_started = COMMONSH.get_db_cluster_status() self.assertTrue("Degraded" in is_started or "Normal" in is_started) def test_guc_wal(self): logger.info("查询enable_double_write 期望:默认值on") sql_cmd = COMMONSH.execut_db_sql("show enable_double_write;") logger.info(sql_cmd) self.assertIn(self.constant.OPEN_STATUS_MSG[0], sql_cmd) logger.info("方式一修改enable_double_write为off," "重启使其生效,期望:设置成功") result = COMMONSH.execute_gsguc("set", self.constant.GSGUC_SUCCESS_MSG, 'enable_double_write=off') self.assertTrue(result) logger.info("期望:重启后查询结果为off") COMMONSH.restart_db_cluster() status = COMMONSH.get_db_cluster_status() self.assertTrue("Degraded" in status or "Normal" in status) sql_cmd = COMMONSH.execut_db_sql("show enable_double_write;") logger.info(sql_cmd) self.assertIn(self.constant.CLOSE_STATUS_MSG[0], sql_cmd) logger.info("创建表,期望:创建成功") sql_cmd = COMMONSH.execut_db_sql("drop table if exists test;" "create table test(x int);") logger.info(sql_cmd) self.assertNotIn(self.constant.SQL_WRONG_MSG[1], sql_cmd) self.assertIn(self.constant.CREATE_TABLE_SUCCESS, sql_cmd) logger.info("恢复默认值") logger.info("删除表") sql_cmd = COMMONSH.execut_db_sql("drop table test cascade;") logger.info(sql_cmd) self.assertIn(self.constant.DROP_TABLE_SUCCESS, sql_cmd) result = COMMONSH.execute_gsguc("set", self.constant.GSGUC_SUCCESS_MSG, 'enable_double_write=on') self.assertTrue(result) COMMONSH.restart_db_cluster() result = COMMONSH.get_db_cluster_status() self.assertTrue("Degraded" in result or "Normal" in result) def tearDown(self): logger.info("恢复默认值") sql_cmd = COMMONSH.execut_db_sql("show enable_double_write;") if "on" != sql_cmd.split("\n")[-2].strip(): COMMONSH.execute_gsguc("set", self.constant.GSGUC_SUCCESS_MSG, 'enable_double_write=on') COMMONSH.restart_db_cluster() is_started = COMMONSH.get_db_cluster_status() self.assertTrue("Degraded" in is_started or "Normal" in is_started) logger.info("==Opengauss_Function_Guc_WAL_Case0052执行结束==")
37.480769
84
0.651873
import unittest from testcase.utils.CommonSH import CommonSH from testcase.utils.Constant import Constant from testcase.utils.Logger import Logger logger = Logger() COMMONSH = CommonSH('PrimaryDbUser') class Guctestcase(unittest.TestCase): def setUp(self): logger.info("==Opengauss_Function_Guc_WAL_Case0052开始执行==") self.constant = Constant() is_started = COMMONSH.get_db_cluster_status() self.assertTrue("Degraded" in is_started or "Normal" in is_started) def test_guc_wal(self): logger.info("查询enable_double_write 期望:默认值on") sql_cmd = COMMONSH.execut_db_sql("show enable_double_write;") logger.info(sql_cmd) self.assertIn(self.constant.OPEN_STATUS_MSG[0], sql_cmd) logger.info("方式一修改enable_double_write为off," "重启使其生效,期望:设置成功") result = COMMONSH.execute_gsguc("set", self.constant.GSGUC_SUCCESS_MSG, 'enable_double_write=off') self.assertTrue(result) logger.info("期望:重启后查询结果为off") COMMONSH.restart_db_cluster() status = COMMONSH.get_db_cluster_status() self.assertTrue("Degraded" in status or "Normal" in status) sql_cmd = COMMONSH.execut_db_sql("show enable_double_write;") logger.info(sql_cmd) self.assertIn(self.constant.CLOSE_STATUS_MSG[0], sql_cmd) logger.info("创建表,期望:创建成功") sql_cmd = COMMONSH.execut_db_sql("drop table if exists test;" "create table test(x int);") logger.info(sql_cmd) self.assertNotIn(self.constant.SQL_WRONG_MSG[1], sql_cmd) self.assertIn(self.constant.CREATE_TABLE_SUCCESS, sql_cmd) logger.info("恢复默认值") logger.info("删除表") sql_cmd = COMMONSH.execut_db_sql("drop table test cascade;") logger.info(sql_cmd) self.assertIn(self.constant.DROP_TABLE_SUCCESS, sql_cmd) result = COMMONSH.execute_gsguc("set", self.constant.GSGUC_SUCCESS_MSG, 'enable_double_write=on') self.assertTrue(result) COMMONSH.restart_db_cluster() result = COMMONSH.get_db_cluster_status() self.assertTrue("Degraded" in result or "Normal" in result) def tearDown(self): logger.info("恢复默认值") sql_cmd = COMMONSH.execut_db_sql("show enable_double_write;") if "on" != sql_cmd.split("\n")[-2].strip(): COMMONSH.execute_gsguc("set", self.constant.GSGUC_SUCCESS_MSG, 'enable_double_write=on') COMMONSH.restart_db_cluster() is_started = COMMONSH.get_db_cluster_status() self.assertTrue("Degraded" in is_started or "Normal" in is_started) logger.info("==Opengauss_Function_Guc_WAL_Case0052执行结束==")
true
true
f7fe9f1fecdc08f89d9fc996cf962b5f9a2c49b5
8,623
py
Python
sympy/physics/quantum/tests/test_cg.py
ovolve/sympy
0a15782f20505673466b940454b33b8014a25c13
[ "BSD-3-Clause" ]
8
2019-05-29T09:38:30.000Z
2021-01-20T03:36:59.000Z
sympy/physics/quantum/tests/test_cg.py
ovolve/sympy
0a15782f20505673466b940454b33b8014a25c13
[ "BSD-3-Clause" ]
12
2021-03-09T03:01:16.000Z
2022-03-11T23:59:36.000Z
sympy/physics/quantum/tests/test_cg.py
ovolve/sympy
0a15782f20505673466b940454b33b8014a25c13
[ "BSD-3-Clause" ]
1
2018-10-22T09:17:11.000Z
2018-10-22T09:17:11.000Z
from __future__ import division from sympy import S, sqrt, Sum, symbols from sympy.physics.quantum.cg import Wigner3j, Wigner6j, Wigner9j, CG, cg_simp from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.utilities.pytest import slow @slow def test_cg_simp_add(): j, m1, m1p, m2, m2p = symbols('j m1 m1p m2 m2p') # Test Varshalovich 8.7.1 Eq 1 a = CG(S(1)/2, S(1)/2, 0, 0, S(1)/2, S(1)/2) b = CG(S(1)/2, -S(1)/2, 0, 0, S(1)/2, -S(1)/2) c = CG(1, 1, 0, 0, 1, 1) d = CG(1, 0, 0, 0, 1, 0) e = CG(1, -1, 0, 0, 1, -1) assert cg_simp(a + b) == 2 assert cg_simp(c + d + e) == 3 assert cg_simp(a + b + c + d + e) == 5 assert cg_simp(a + b + c) == 2 + c assert cg_simp(2*a + b) == 2 + a assert cg_simp(2*c + d + e) == 3 + c assert cg_simp(5*a + 5*b) == 10 assert cg_simp(5*c + 5*d + 5*e) == 15 assert cg_simp(-a - b) == -2 assert cg_simp(-c - d - e) == -3 assert cg_simp(-6*a - 6*b) == -12 assert cg_simp(-4*c - 4*d - 4*e) == -12 a = CG(S(1)/2, S(1)/2, j, 0, S(1)/2, S(1)/2) b = CG(S(1)/2, -S(1)/2, j, 0, S(1)/2, -S(1)/2) c = CG(1, 1, j, 0, 1, 1) d = CG(1, 0, j, 0, 1, 0) e = CG(1, -1, j, 0, 1, -1) assert cg_simp(a + b) == 2*KroneckerDelta(j, 0) assert cg_simp(c + d + e) == 3*KroneckerDelta(j, 0) assert cg_simp(a + b + c + d + e) == 5*KroneckerDelta(j, 0) assert cg_simp(a + b + c) == 2*KroneckerDelta(j, 0) + c assert cg_simp(2*a + b) == 2*KroneckerDelta(j, 0) + a assert cg_simp(2*c + d + e) == 3*KroneckerDelta(j, 0) + c assert cg_simp(5*a + 5*b) == 10*KroneckerDelta(j, 0) assert cg_simp(5*c + 5*d + 5*e) == 15*KroneckerDelta(j, 0) assert cg_simp(-a - b) == -2*KroneckerDelta(j, 0) assert cg_simp(-c - d - e) == -3*KroneckerDelta(j, 0) assert cg_simp(-6*a - 6*b) == -12*KroneckerDelta(j, 0) assert cg_simp(-4*c - 4*d - 4*e) == -12*KroneckerDelta(j, 0) # Test Varshalovich 8.7.1 Eq 2 a = CG(S(1)/2, S(1)/2, S(1)/2, -S(1)/2, 0, 0) b = CG(S(1)/2, -S(1)/2, S(1)/2, S(1)/2, 0, 0) c = CG(1, 1, 1, -1, 0, 0) d = CG(1, 0, 1, 0, 0, 0) e = CG(1, -1, 1, 1, 0, 0) assert cg_simp(a - b) == sqrt(2) assert cg_simp(c - d + e) == sqrt(3) assert cg_simp(a - b + c - d + e) == sqrt(2) + sqrt(3) assert cg_simp(a - b + c) == sqrt(2) + c assert cg_simp(2*a - b) == sqrt(2) + a assert cg_simp(2*c - d + e) == sqrt(3) + c assert cg_simp(5*a - 5*b) == 5*sqrt(2) assert cg_simp(5*c - 5*d + 5*e) == 5*sqrt(3) assert cg_simp(-a + b) == -sqrt(2) assert cg_simp(-c + d - e) == -sqrt(3) assert cg_simp(-6*a + 6*b) == -6*sqrt(2) assert cg_simp(-4*c + 4*d - 4*e) == -4*sqrt(3) a = CG(S(1)/2, S(1)/2, S(1)/2, -S(1)/2, j, 0) b = CG(S(1)/2, -S(1)/2, S(1)/2, S(1)/2, j, 0) c = CG(1, 1, 1, -1, j, 0) d = CG(1, 0, 1, 0, j, 0) e = CG(1, -1, 1, 1, j, 0) assert cg_simp(a - b) == sqrt(2)*KroneckerDelta(j, 0) assert cg_simp(c - d + e) == sqrt(3)*KroneckerDelta(j, 0) assert cg_simp(a - b + c - d + e) == sqrt( 2)*KroneckerDelta(j, 0) + sqrt(3)*KroneckerDelta(j, 0) assert cg_simp(a - b + c) == sqrt(2)*KroneckerDelta(j, 0) + c assert cg_simp(2*a - b) == sqrt(2)*KroneckerDelta(j, 0) + a assert cg_simp(2*c - d + e) == sqrt(3)*KroneckerDelta(j, 0) + c assert cg_simp(5*a - 5*b) == 5*sqrt(2)*KroneckerDelta(j, 0) assert cg_simp(5*c - 5*d + 5*e) == 5*sqrt(3)*KroneckerDelta(j, 0) assert cg_simp(-a + b) == -sqrt(2)*KroneckerDelta(j, 0) assert cg_simp(-c + d - e) == -sqrt(3)*KroneckerDelta(j, 0) assert cg_simp(-6*a + 6*b) == -6*sqrt(2)*KroneckerDelta(j, 0) assert cg_simp(-4*c + 4*d - 4*e) == -4*sqrt(3)*KroneckerDelta(j, 0) # Test Varshalovich 8.7.2 Eq 9 # alpha=alphap,beta=betap case # numerical a = CG(S(1)/2, S(1)/2, S(1)/2, -S(1)/2, 1, 0)**2 b = CG(S(1)/2, S(1)/2, S(1)/2, -S(1)/2, 0, 0)**2 c = CG(1, 0, 1, 1, 1, 1)**2 d = CG(1, 0, 1, 1, 2, 1)**2 assert cg_simp(a + b) == 1 assert cg_simp(c + d) == 1 assert cg_simp(a + b + c + d) == 2 assert cg_simp(4*a + 4*b) == 4 assert cg_simp(4*c + 4*d) == 4 assert cg_simp(5*a + 3*b) == 3 + 2*a assert cg_simp(5*c + 3*d) == 3 + 2*c assert cg_simp(-a - b) == -1 assert cg_simp(-c - d) == -1 # symbolic a = CG(S(1)/2, m1, S(1)/2, m2, 1, 1)**2 b = CG(S(1)/2, m1, S(1)/2, m2, 1, 0)**2 c = CG(S(1)/2, m1, S(1)/2, m2, 1, -1)**2 d = CG(S(1)/2, m1, S(1)/2, m2, 0, 0)**2 assert cg_simp(a + b + c + d) == 1 assert cg_simp(4*a + 4*b + 4*c + 4*d) == 4 assert cg_simp(3*a + 5*b + 3*c + 4*d) == 3 + 2*b + d assert cg_simp(-a - b - c - d) == -1 a = CG(1, m1, 1, m2, 2, 2)**2 b = CG(1, m1, 1, m2, 2, 1)**2 c = CG(1, m1, 1, m2, 2, 0)**2 d = CG(1, m1, 1, m2, 2, -1)**2 e = CG(1, m1, 1, m2, 2, -2)**2 f = CG(1, m1, 1, m2, 1, 1)**2 g = CG(1, m1, 1, m2, 1, 0)**2 h = CG(1, m1, 1, m2, 1, -1)**2 i = CG(1, m1, 1, m2, 0, 0)**2 assert cg_simp(a + b + c + d + e + f + g + h + i) == 1 assert cg_simp(4*(a + b + c + d + e + f + g + h + i)) == 4 assert cg_simp(a + b + 2*c + d + 4*e + f + g + h + i) == 1 + c + 3*e assert cg_simp(-a - b - c - d - e - f - g - h - i) == -1 # alpha!=alphap or beta!=betap case # numerical a = CG(S(1)/2, S( 1)/2, S(1)/2, -S(1)/2, 1, 0)*CG(S(1)/2, -S(1)/2, S(1)/2, S(1)/2, 1, 0) b = CG(S(1)/2, S( 1)/2, S(1)/2, -S(1)/2, 0, 0)*CG(S(1)/2, -S(1)/2, S(1)/2, S(1)/2, 0, 0) c = CG(1, 1, 1, 0, 2, 1)*CG(1, 0, 1, 1, 2, 1) d = CG(1, 1, 1, 0, 1, 1)*CG(1, 0, 1, 1, 1, 1) assert cg_simp(a + b) == 0 assert cg_simp(c + d) == 0 # symbolic a = CG(S(1)/2, m1, S(1)/2, m2, 1, 1)*CG(S(1)/2, m1p, S(1)/2, m2p, 1, 1) b = CG(S(1)/2, m1, S(1)/2, m2, 1, 0)*CG(S(1)/2, m1p, S(1)/2, m2p, 1, 0) c = CG(S(1)/2, m1, S(1)/2, m2, 1, -1)*CG(S(1)/2, m1p, S(1)/2, m2p, 1, -1) d = CG(S(1)/2, m1, S(1)/2, m2, 0, 0)*CG(S(1)/2, m1p, S(1)/2, m2p, 0, 0) assert cg_simp(a + b + c + d) == KroneckerDelta(m1, m1p)*KroneckerDelta(m2, m2p) a = CG(1, m1, 1, m2, 2, 2)*CG(1, m1p, 1, m2p, 2, 2) b = CG(1, m1, 1, m2, 2, 1)*CG(1, m1p, 1, m2p, 2, 1) c = CG(1, m1, 1, m2, 2, 0)*CG(1, m1p, 1, m2p, 2, 0) d = CG(1, m1, 1, m2, 2, -1)*CG(1, m1p, 1, m2p, 2, -1) e = CG(1, m1, 1, m2, 2, -2)*CG(1, m1p, 1, m2p, 2, -2) f = CG(1, m1, 1, m2, 1, 1)*CG(1, m1p, 1, m2p, 1, 1) g = CG(1, m1, 1, m2, 1, 0)*CG(1, m1p, 1, m2p, 1, 0) h = CG(1, m1, 1, m2, 1, -1)*CG(1, m1p, 1, m2p, 1, -1) i = CG(1, m1, 1, m2, 0, 0)*CG(1, m1p, 1, m2p, 0, 0) assert cg_simp( a + b + c + d + e + f + g + h + i) == KroneckerDelta(m1, m1p)*KroneckerDelta(m2, m2p) def test_cg_simp_sum(): x, a, b, c, cp, alpha, beta, gamma, gammap = symbols( 'x a b c cp alpha beta gamma gammap') # Varshalovich 8.7.1 Eq 1 assert cg_simp(x * Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a) )) == x*(2*a + 1)*KroneckerDelta(b, 0) assert cg_simp(x * Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a)) + CG(1, 0, 1, 0, 1, 0)) == x*(2*a + 1)*KroneckerDelta(b, 0) + CG(1, 0, 1, 0, 1, 0) assert cg_simp(2 * Sum(CG(1, alpha, 0, 0, 1, alpha), (alpha, -1, 1))) == 6 # Varshalovich 8.7.1 Eq 2 assert cg_simp(x*Sum((-1)**(a - alpha) * CG(a, alpha, a, -alpha, c, 0), (alpha, -a, a))) == x*sqrt(2*a + 1)*KroneckerDelta(c, 0) assert cg_simp(3*Sum((-1)**(2 - alpha) * CG( 2, alpha, 2, -alpha, 0, 0), (alpha, -2, 2))) == 3*sqrt(5) # Varshalovich 8.7.2 Eq 4 assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, cp, gammap), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(c, cp)*KroneckerDelta(gamma, gammap) assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, c, gammap), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(gamma, gammap) assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, cp, gamma), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(c, cp) assert cg_simp(Sum(CG( a, alpha, b, beta, c, gamma)**2, (alpha, -a, a), (beta, -b, b))) == 1 assert cg_simp(Sum(CG(2, alpha, 1, beta, 2, gamma)*CG(2, alpha, 1, beta, 2, gammap), (alpha, -2, 2), (beta, -1, 1))) == KroneckerDelta(gamma, gammap) def test_doit(): assert Wigner3j(1/2, -1/2, 1/2, 1/2, 0, 0).doit() == -sqrt(2)/2 assert Wigner6j(1, 2, 3, 2, 1, 2).doit() == sqrt(21)/105 assert Wigner6j(3, 1, 2, 2, 2, 1).doit() == sqrt(21) / 105 assert Wigner9j( 2, 1, 1, S(3)/2, S(1)/2, 1, S(1)/2, S(1)/2, 0).doit() == sqrt(2)/12 assert CG(1/2, 1/2, 1/2, -1/2, 1, 0).doit() == sqrt(2)/2
48.44382
176
0.491824
from __future__ import division from sympy import S, sqrt, Sum, symbols from sympy.physics.quantum.cg import Wigner3j, Wigner6j, Wigner9j, CG, cg_simp from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.utilities.pytest import slow @slow def test_cg_simp_add(): j, m1, m1p, m2, m2p = symbols('j m1 m1p m2 m2p') a = CG(S(1)/2, S(1)/2, 0, 0, S(1)/2, S(1)/2) b = CG(S(1)/2, -S(1)/2, 0, 0, S(1)/2, -S(1)/2) c = CG(1, 1, 0, 0, 1, 1) d = CG(1, 0, 0, 0, 1, 0) e = CG(1, -1, 0, 0, 1, -1) assert cg_simp(a + b) == 2 assert cg_simp(c + d + e) == 3 assert cg_simp(a + b + c + d + e) == 5 assert cg_simp(a + b + c) == 2 + c assert cg_simp(2*a + b) == 2 + a assert cg_simp(2*c + d + e) == 3 + c assert cg_simp(5*a + 5*b) == 10 assert cg_simp(5*c + 5*d + 5*e) == 15 assert cg_simp(-a - b) == -2 assert cg_simp(-c - d - e) == -3 assert cg_simp(-6*a - 6*b) == -12 assert cg_simp(-4*c - 4*d - 4*e) == -12 a = CG(S(1)/2, S(1)/2, j, 0, S(1)/2, S(1)/2) b = CG(S(1)/2, -S(1)/2, j, 0, S(1)/2, -S(1)/2) c = CG(1, 1, j, 0, 1, 1) d = CG(1, 0, j, 0, 1, 0) e = CG(1, -1, j, 0, 1, -1) assert cg_simp(a + b) == 2*KroneckerDelta(j, 0) assert cg_simp(c + d + e) == 3*KroneckerDelta(j, 0) assert cg_simp(a + b + c + d + e) == 5*KroneckerDelta(j, 0) assert cg_simp(a + b + c) == 2*KroneckerDelta(j, 0) + c assert cg_simp(2*a + b) == 2*KroneckerDelta(j, 0) + a assert cg_simp(2*c + d + e) == 3*KroneckerDelta(j, 0) + c assert cg_simp(5*a + 5*b) == 10*KroneckerDelta(j, 0) assert cg_simp(5*c + 5*d + 5*e) == 15*KroneckerDelta(j, 0) assert cg_simp(-a - b) == -2*KroneckerDelta(j, 0) assert cg_simp(-c - d - e) == -3*KroneckerDelta(j, 0) assert cg_simp(-6*a - 6*b) == -12*KroneckerDelta(j, 0) assert cg_simp(-4*c - 4*d - 4*e) == -12*KroneckerDelta(j, 0) a = CG(S(1)/2, S(1)/2, S(1)/2, -S(1)/2, 0, 0) b = CG(S(1)/2, -S(1)/2, S(1)/2, S(1)/2, 0, 0) c = CG(1, 1, 1, -1, 0, 0) d = CG(1, 0, 1, 0, 0, 0) e = CG(1, -1, 1, 1, 0, 0) assert cg_simp(a - b) == sqrt(2) assert cg_simp(c - d + e) == sqrt(3) assert cg_simp(a - b + c - d + e) == sqrt(2) + sqrt(3) assert cg_simp(a - b + c) == sqrt(2) + c assert cg_simp(2*a - b) == sqrt(2) + a assert cg_simp(2*c - d + e) == sqrt(3) + c assert cg_simp(5*a - 5*b) == 5*sqrt(2) assert cg_simp(5*c - 5*d + 5*e) == 5*sqrt(3) assert cg_simp(-a + b) == -sqrt(2) assert cg_simp(-c + d - e) == -sqrt(3) assert cg_simp(-6*a + 6*b) == -6*sqrt(2) assert cg_simp(-4*c + 4*d - 4*e) == -4*sqrt(3) a = CG(S(1)/2, S(1)/2, S(1)/2, -S(1)/2, j, 0) b = CG(S(1)/2, -S(1)/2, S(1)/2, S(1)/2, j, 0) c = CG(1, 1, 1, -1, j, 0) d = CG(1, 0, 1, 0, j, 0) e = CG(1, -1, 1, 1, j, 0) assert cg_simp(a - b) == sqrt(2)*KroneckerDelta(j, 0) assert cg_simp(c - d + e) == sqrt(3)*KroneckerDelta(j, 0) assert cg_simp(a - b + c - d + e) == sqrt( 2)*KroneckerDelta(j, 0) + sqrt(3)*KroneckerDelta(j, 0) assert cg_simp(a - b + c) == sqrt(2)*KroneckerDelta(j, 0) + c assert cg_simp(2*a - b) == sqrt(2)*KroneckerDelta(j, 0) + a assert cg_simp(2*c - d + e) == sqrt(3)*KroneckerDelta(j, 0) + c assert cg_simp(5*a - 5*b) == 5*sqrt(2)*KroneckerDelta(j, 0) assert cg_simp(5*c - 5*d + 5*e) == 5*sqrt(3)*KroneckerDelta(j, 0) assert cg_simp(-a + b) == -sqrt(2)*KroneckerDelta(j, 0) assert cg_simp(-c + d - e) == -sqrt(3)*KroneckerDelta(j, 0) assert cg_simp(-6*a + 6*b) == -6*sqrt(2)*KroneckerDelta(j, 0) assert cg_simp(-4*c + 4*d - 4*e) == -4*sqrt(3)*KroneckerDelta(j, 0) a = CG(S(1)/2, S(1)/2, S(1)/2, -S(1)/2, 1, 0)**2 b = CG(S(1)/2, S(1)/2, S(1)/2, -S(1)/2, 0, 0)**2 c = CG(1, 0, 1, 1, 1, 1)**2 d = CG(1, 0, 1, 1, 2, 1)**2 assert cg_simp(a + b) == 1 assert cg_simp(c + d) == 1 assert cg_simp(a + b + c + d) == 2 assert cg_simp(4*a + 4*b) == 4 assert cg_simp(4*c + 4*d) == 4 assert cg_simp(5*a + 3*b) == 3 + 2*a assert cg_simp(5*c + 3*d) == 3 + 2*c assert cg_simp(-a - b) == -1 assert cg_simp(-c - d) == -1 a = CG(S(1)/2, m1, S(1)/2, m2, 1, 1)**2 b = CG(S(1)/2, m1, S(1)/2, m2, 1, 0)**2 c = CG(S(1)/2, m1, S(1)/2, m2, 1, -1)**2 d = CG(S(1)/2, m1, S(1)/2, m2, 0, 0)**2 assert cg_simp(a + b + c + d) == 1 assert cg_simp(4*a + 4*b + 4*c + 4*d) == 4 assert cg_simp(3*a + 5*b + 3*c + 4*d) == 3 + 2*b + d assert cg_simp(-a - b - c - d) == -1 a = CG(1, m1, 1, m2, 2, 2)**2 b = CG(1, m1, 1, m2, 2, 1)**2 c = CG(1, m1, 1, m2, 2, 0)**2 d = CG(1, m1, 1, m2, 2, -1)**2 e = CG(1, m1, 1, m2, 2, -2)**2 f = CG(1, m1, 1, m2, 1, 1)**2 g = CG(1, m1, 1, m2, 1, 0)**2 h = CG(1, m1, 1, m2, 1, -1)**2 i = CG(1, m1, 1, m2, 0, 0)**2 assert cg_simp(a + b + c + d + e + f + g + h + i) == 1 assert cg_simp(4*(a + b + c + d + e + f + g + h + i)) == 4 assert cg_simp(a + b + 2*c + d + 4*e + f + g + h + i) == 1 + c + 3*e assert cg_simp(-a - b - c - d - e - f - g - h - i) == -1 a = CG(S(1)/2, S( 1)/2, S(1)/2, -S(1)/2, 1, 0)*CG(S(1)/2, -S(1)/2, S(1)/2, S(1)/2, 1, 0) b = CG(S(1)/2, S( 1)/2, S(1)/2, -S(1)/2, 0, 0)*CG(S(1)/2, -S(1)/2, S(1)/2, S(1)/2, 0, 0) c = CG(1, 1, 1, 0, 2, 1)*CG(1, 0, 1, 1, 2, 1) d = CG(1, 1, 1, 0, 1, 1)*CG(1, 0, 1, 1, 1, 1) assert cg_simp(a + b) == 0 assert cg_simp(c + d) == 0 a = CG(S(1)/2, m1, S(1)/2, m2, 1, 1)*CG(S(1)/2, m1p, S(1)/2, m2p, 1, 1) b = CG(S(1)/2, m1, S(1)/2, m2, 1, 0)*CG(S(1)/2, m1p, S(1)/2, m2p, 1, 0) c = CG(S(1)/2, m1, S(1)/2, m2, 1, -1)*CG(S(1)/2, m1p, S(1)/2, m2p, 1, -1) d = CG(S(1)/2, m1, S(1)/2, m2, 0, 0)*CG(S(1)/2, m1p, S(1)/2, m2p, 0, 0) assert cg_simp(a + b + c + d) == KroneckerDelta(m1, m1p)*KroneckerDelta(m2, m2p) a = CG(1, m1, 1, m2, 2, 2)*CG(1, m1p, 1, m2p, 2, 2) b = CG(1, m1, 1, m2, 2, 1)*CG(1, m1p, 1, m2p, 2, 1) c = CG(1, m1, 1, m2, 2, 0)*CG(1, m1p, 1, m2p, 2, 0) d = CG(1, m1, 1, m2, 2, -1)*CG(1, m1p, 1, m2p, 2, -1) e = CG(1, m1, 1, m2, 2, -2)*CG(1, m1p, 1, m2p, 2, -2) f = CG(1, m1, 1, m2, 1, 1)*CG(1, m1p, 1, m2p, 1, 1) g = CG(1, m1, 1, m2, 1, 0)*CG(1, m1p, 1, m2p, 1, 0) h = CG(1, m1, 1, m2, 1, -1)*CG(1, m1p, 1, m2p, 1, -1) i = CG(1, m1, 1, m2, 0, 0)*CG(1, m1p, 1, m2p, 0, 0) assert cg_simp( a + b + c + d + e + f + g + h + i) == KroneckerDelta(m1, m1p)*KroneckerDelta(m2, m2p) def test_cg_simp_sum(): x, a, b, c, cp, alpha, beta, gamma, gammap = symbols( 'x a b c cp alpha beta gamma gammap') assert cg_simp(x * Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a) )) == x*(2*a + 1)*KroneckerDelta(b, 0) assert cg_simp(x * Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a)) + CG(1, 0, 1, 0, 1, 0)) == x*(2*a + 1)*KroneckerDelta(b, 0) + CG(1, 0, 1, 0, 1, 0) assert cg_simp(2 * Sum(CG(1, alpha, 0, 0, 1, alpha), (alpha, -1, 1))) == 6 assert cg_simp(x*Sum((-1)**(a - alpha) * CG(a, alpha, a, -alpha, c, 0), (alpha, -a, a))) == x*sqrt(2*a + 1)*KroneckerDelta(c, 0) assert cg_simp(3*Sum((-1)**(2 - alpha) * CG( 2, alpha, 2, -alpha, 0, 0), (alpha, -2, 2))) == 3*sqrt(5) assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, cp, gammap), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(c, cp)*KroneckerDelta(gamma, gammap) assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, c, gammap), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(gamma, gammap) assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, cp, gamma), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(c, cp) assert cg_simp(Sum(CG( a, alpha, b, beta, c, gamma)**2, (alpha, -a, a), (beta, -b, b))) == 1 assert cg_simp(Sum(CG(2, alpha, 1, beta, 2, gamma)*CG(2, alpha, 1, beta, 2, gammap), (alpha, -2, 2), (beta, -1, 1))) == KroneckerDelta(gamma, gammap) def test_doit(): assert Wigner3j(1/2, -1/2, 1/2, 1/2, 0, 0).doit() == -sqrt(2)/2 assert Wigner6j(1, 2, 3, 2, 1, 2).doit() == sqrt(21)/105 assert Wigner6j(3, 1, 2, 2, 2, 1).doit() == sqrt(21) / 105 assert Wigner9j( 2, 1, 1, S(3)/2, S(1)/2, 1, S(1)/2, S(1)/2, 0).doit() == sqrt(2)/12 assert CG(1/2, 1/2, 1/2, -1/2, 1, 0).doit() == sqrt(2)/2
true
true
f7fea1418f16facb361a8885f258c589f1582d5e
710
py
Python
tardis/default_settings/localisation.py
keithschulze/mytardis
8ed3562574ce990d42bfe96133185a82c31c27d4
[ "Apache-2.0" ]
null
null
null
tardis/default_settings/localisation.py
keithschulze/mytardis
8ed3562574ce990d42bfe96133185a82c31c27d4
[ "Apache-2.0" ]
null
null
null
tardis/default_settings/localisation.py
keithschulze/mytardis
8ed3562574ce990d42bfe96133185a82c31c27d4
[ "Apache-2.0" ]
null
null
null
USE_TZ = True # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'Australia/Melbourne' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' # Date format to use by default. ("jS F Y" => "8th March 2012") # https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#std:templatefilter-date # noqa DATE_FORMAT = "jS F Y" DATETIME_FORMAT = "jS F Y H:i"
33.809524
95
0.750704
USE_TZ = True TIME_ZONE = 'Australia/Melbourne' LANGUAGE_CODE = 'en-us' AT = "jS F Y H:i"
true
true