Convert MagicMock object to something I can use in my test - python

I'm not familiar with Python testing, particularly with using mocks so this may be completely wrong.
I have this code in my test:
import os
import mock
from mock import Mock
from tests import unittest
from datetime import datetime
from ibm_botocore.session import Session
import logging
class TestS3Parameters(unittest.TestCase):
def setUp(self):
super(TestS3Parameters, self).setUp()
# Set the config file to something that doesn't exist so
# that we don't accidentally load a config.
os.environ['AWS_CONFIG_FILE'] = '~/.aws/config-missing'
def create_session(self, *args, **kwargs):
"""
Create a new session with the given arguments. Additionally,
this method will set the credentials file to the test credentials
used by the following test cases.
"""
kwargs['session_vars'] = {
'credentials_file': (
None, None,
os.path.join(os.path.dirname(__file__), 'test-credentials'),
None)
}
return Session(*args, **kwargs)
#mock.patch('ibm_botocore.credentials.Credentials')
def test_extended_endpoint(self, my_mock):
now = datetime.utcnow().strftime("%Y%m%d")
extended_listing_mock_response_basic = {
"IsTruncated": False,
"Buckets": [
{
"Name": "bucketnamefoo",
"CreationDate": str(now),
"LocationConstraint": "bar-standard"
}
],
"Owner": {
"DisplayName": "ownerfoo",
"ID": "idfoo"
}
}
s = self.create_session()
client = s.create_client('s3', region_name='us-east-1', aws_access_key_id='foo',
aws_secret_access_key='bar')
# Create a mock response.
self.mock_response = Mock()
self.mock_response = extended_listing_mock_response_basic
request = my_mock.list_bucket()
self.assertEquals(request['httpRequest']['method'], 'GET')
self.assertEquals(request['httpRequest']['path'], '/?extended')
if __name__ == "__main__":
unittest.main()
When I run it I get this error:
Traceback (most recent call last):
File "/core/.tox/py33/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched
return func(*args, **keywargs)
File "/core/tests/unit/test_s3_param.py", line 56, in test_extended_endpoint
request = client.list_bucket()
File "/core/ibm_botocore/client.py", line 357, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/core/ibm_botocore/client.py", line 648, in _make_api_call
operation_model, request_dict, request_context)
File "/core/ibm_botocore/client.py", line 667, in _make_request
return self._endpoint.make_request(operation_model, request_dict)
File "/core/ibm_botocore/endpoint.py", line 102, in make_request
return self._send_request(request_dict, operation_model)
File "/core/ibm_botocore/endpoint.py", line 132, in _send_request
request = self.create_request(request_dict, operation_model)
File "/core/ibm_botocore/endpoint.py", line 116, in create_request
operation_name=operation_model.name)
File "/core/ibm_botocore/hooks.py", line 356, in emit
return self._emitter.emit(aliased_event_name, **kwargs)
File "/core/ibm_botocore/hooks.py", line 228, in emit
return self._emit(event_name, kwargs)
File "/core/ibm_botocore/hooks.py", line 211, in _emit
response = handler(**kwargs)
File "/core/ibm_botocore/signers.py", line 90, in handler
return self.sign(operation_name, request)
File "/core/ibm_botocore/signers.py", line 157, in sign
auth.add_auth(request)
File "/core/ibm_botocore/auth.py", line 425, in add_auth
super(S3SigV4Auth, self).add_auth(request)
File "/core/ibm_botocore/auth.py", line 368, in add_auth
signature = self.signature(string_to_sign, request)
File "/core/ibm_botocore/auth.py", line 349, in signature
request.context['timestamp'][0:8])
File "/core/ibm_botocore/auth.py", line 169, in _sign
sig = hmac.new(key, msg.encode('utf-8'), sha256).digest()
File "/Users/me/.pyenv/versions/2.7.8/lib/python2.7/hmac.py", line 136, in new
return HMAC(key, msg, digestmod)
File "/Users/me/.pyenv/versions/2.7.8/lib/python2.7/hmac.py", line 75, in __init__
self.outer.update(key.translate(trans_5C))
TypeError: must be convertible to a buffer, not MagicMock
How do I convert this to a type I can use?
I tried using request = my_mock.list_bucket() but it give me this error:
AssertionError: <MagicMock name='Credentials.list_buckets_extended().__getitem__().__getitem__()' id='4459954832'> != 'GET'
What I'm trying to do is create a mock client which I can use for my list_bucket call. I then hope to check it to ensure the request is a GET and the /?extended endpoint is used.

Related

How to fix: azure.core.exceptions.ServiceRequestError: EOF occurred in violation of protocol (_ssl.c:1129)

I am trying to interact with the TextAnalyticsClient of Azure to run a pretrained custom Entity Recognition program. However, when I call the attribute .begin_recognize_custom_entities(...) in the code shown below. It appears that the administration of the key credentials passes succesfully (in text_analytics_client = TextAnalyticsClient(...)), but then it fails afterwards.
"""
FILE: sample_recognize_custom_entities.py
DESCRIPTION:
This sample demonstrates how to recognize custom entities in documents.
Recognizing custom entities is available as an action type through the begin_analyze_actions API.
For information on regional support of custom features and how to train a model to
recognize custom entities, see https://aka.ms/azsdk/textanalytics/customentityrecognition
USAGE:
python sample_recognize_custom_entities.py
Set the environment variables with your own values before running the sample:
1) AZURE_LANGUAGE_ENDPOINT - the endpoint to your Language resource.
2) AZURE_LANGUAGE_KEY - your Language subscription key
3) CUSTOM_ENTITIES_PROJECT_NAME - your Language Studio project name
4) CUSTOM_ENTITIES_DEPLOYMENT_NAME - your Language Studio deployment name
"""
import os
print('#############################################################')
def sample_recognize_custom_entities():
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient
deployment_name = #####
endpoint = #####
key = #####
project_name = #####
path_to_sample_document = r'C:\Users\#####\Documents\#####\Source\Document cracking\output_documents\txt_for_ML_566docs_270922\text.txt'
text_analytics_client = TextAnalyticsClient(
endpoint=endpoint,
credential=AzureKeyCredential(key),
)
with open(path_to_sample_document) as fd:
document = [fd.read()]
poller = text_analytics_client.begin_recognize_custom_entities(
document,
project_name=project_name,
deployment_name=deployment_name
)
document_results = poller.result()
for result in document_results:
custom_entities_result = result[0] # first document, first result
if not custom_entities_result.is_error:
for entity in custom_entities_result.entities:
print(
"Entity '{}' has category '{}' with confidence score of '{}'".format(
entity.text, entity.category, entity.confidence_score
)
)
else:
print(
"...Is an error with code '{}' and message '{}'".format(
custom_entities_result.code, custom_entities_result.message
)
)
sample_recognize_custom_entities()
if __name__ == "__main__":
sample_recognize_custom_entities()
it gives the following error:
File "C:\Users\#####\Documents\#####\Source\Document cracking\crack-document\test_ML_connection.py", line 71, in <module>
sample_recognize_custom_entities()
File "C:\Users\#####\Documents\#####\Source\Document cracking\crack-document\test_ML_connection.py", line 48, in sample_recognize_custom_entities
poller = text_analytics_client.begin_recognize_custom_entities(
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\tracing\decorator.py", line 78, in wrapper_use_tracer
return func(*args, **kwargs)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\ai\textanalytics\_validate.py", line 74, in wrapper
return func(*args, **kwargs)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\ai\textanalytics\_text_analytics_client.py", line 1388, in begin_recognize_custom_entities
self.begin_analyze_actions(
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\tracing\decorator.py", line 78, in wrapper_use_tracer
return func(*args, **kwargs)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\ai\textanalytics\_validate.py", line 74, in wrapper
return func(*args, **kwargs)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\ai\textanalytics\_text_analytics_client.py", line 1213, in begin_analyze_actions
self._client.begin_analyze_text_submit_job(
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\ai\textanalytics\_generated\_operations_mixin.py", line 277, in begin_analyze_text_submit_job
return mixin_instance.begin_analyze_text_submit_job(body, **kwargs)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\tracing\decorator.py", line 78, in wrapper_use_tracer
return func(*args, **kwargs)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\ai\textanalytics\_generated\v2022_05_01\operations\_patch.py", line 67, in begin_analyze_text_submit_job
raw_result = self._analyze_text_submit_job_initial( # type: ignore
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\ai\textanalytics\_generated\v2022_05_01\operations\_text_analytics_client_operations.py", line 353, in _analyze_text_submit_job_initial
pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\_base.py", line 211, in run
return first_node.send(pipeline_request) # type: ignore
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\_base.py", line 71, in send
response = self.next.send(request)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\_base.py", line 71, in send
response = self.next.send(request)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\_base.py", line 71, in send
response = self.next.send(request)
[Previous line repeated 2 more times]
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\policies\_redirect.py", line 158, in send
response = self.next.send(request)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\policies\_retry.py", line 468, in send
raise err
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\policies\_retry.py", line 446, in send
response = self.next.send(request)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\_base.py", line 71, in send
response = self.next.send(request)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\_base.py", line 71, in send
response = self.next.send(request)
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\_base.py", line 71, in send
response = self.next.send(request)
[Previous line repeated 3 more times]
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\_base.py", line 103, in send
self._sender.send(request.http_request, **request.context.options),
File "C:\Users\#####\Anaconda3\envs\doc_crac\lib\site-packages\azure\core\pipeline\transport\_requests_basic.py", line 361, in send
raise error
azure.core.exceptions.ServiceRequestError: EOF occurred in violation of protocol (_ssl.c:1129)
Anyone knows what this means, and how to solve it?
Thanks in advance,
Koeiswit

Transaction fails when calling contract function with return value

I'm hitting some unintuitive behavior in solidity when one of my contracts calls another. I'm testing the contracts with web3py. Here's is the most minimal example I could come up with. Note that it may not actually be a minimal example because failures reasons aren't propagated from ethereum to web3py.
Foo.sol:
pragma solidity ^0.4.0;
import "./Bar.sol";
contract Foo {
Bar public bar;
function Foo(){
bar = new Bar();
}
function test() returns (uint) { return 1; }
function test2() {}
function execute() {
bar.run();
}
}
Bar.sol
pragma solidity ^0.4.0;
import "./Foo.sol";
contract Bar {
address bar_address;
function Bar(){
bar_address = msg.sender;
}
function run() {
Foo foo = Foo(bar_address);
// foo.test(); # fails
foo.test2(); # succeeds
}
}
test.py
from web3 import Web3, EthereumTesterProvider
import unittest
import os
from eth_tester.exceptions import TransactionFailed
import tests.utils.utils as utils
from web3.utils.filters import Filter
class TestMycroToken(unittest.TestCase):
PROJECT_ROOT = os.path.dirname(os.path.dirname(__file__))
CONTRACT_ROOT = os.path.join(PROJECT_ROOT, "contracts")
TEST_CONTRACT_ROOT = os.path.join(CONTRACT_ROOT, "test_contracts")
def test_foo(self):
w3 = Web3(EthereumTesterProvider())
proposal_contract, proposal_contract_address, proposal_contract_instance = utils.create_contract(
self.CONTRACT_ROOT, os.path.join(self.TEST_CONTRACT_ROOT, "Foo.sol"), "Foo", w3 )
proposal_contract_instance.execute(transact={'from': self.w3.eth.accounts[1]})
When Bar.run calls Foo.test2() the test passes, but when Foo.test() is called, the test fails.
utils.create_contract more or less does what's shown in the quickstart for web3py with some modifications to handle compiling multiple files.
I'm getting the following stack trace for the error:
/Users/paymahn/mycro/venv/bin/python /Applications/PyCharm.app/Contents/helpers/pycharm/_jb_unittest_runner.py --target test_mycro_token.TestMycroToken.test_foo
Launching unittests with arguments python -m unittest test_mycro_token.TestMycroToken.test_foo in /Users/paymahn/mycro/tests
Ran 1 test in 0.692s
FAILED (errors=1)
Error
Traceback (most recent call last):
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/eth_tester/utils/formatting.py", line 85, in wrapper
return to_wrap(*args, **kwargs)
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/eth_tester/backends/pyethereum/v16/main.py", line 439, in estimate_gas
transaction=transaction,
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/eth_tester/backends/pyethereum/v16/main.py", line 157, in _estimate_evm_transaction
return _send_evm_transaction(tester_module, evm, transaction_for_estimate)
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/eth_tester/backends/pyethereum/v16/main.py", line 145, in _send_evm_transaction
evmdata=transaction.get('data', b''),
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/ethereum/tester.py", line 338, in send
return self._send(*args, **kwargs)["output"]
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/ethereum/tester.py", line 296, in _send
raise TransactionFailed()
ethereum.tester.TransactionFailed
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/case.py", line 59, in testPartExecutor
yield
File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/case.py", line 605, in run
testMethod()
File "/Users/paymahn/mycro/tests/test_mycro_token.py", line 125, in test_foo
proposal_contract_instance.execute(transact={'from': self.w3.eth.accounts[1]})
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/contract.py", line 777, in __call__
return self.__prepared_function(*args, **kwargs)
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/contract.py", line 790, in __prepared_function
return getattr(self._function(*args), modifier)(modifier_dict)
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/contract.py", line 1028, in transact
**self.kwargs)
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/contract.py", line 1305, in transact_with_contract_function
txn_hash = web3.eth.sendTransaction(transact_transaction)
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/eth.py", line 247, in sendTransaction
get_buffered_gas_estimate(self.web3, transaction),
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/utils/transactions.py", line 72, in get_buffered_gas_estimate
gas_estimate = web3.eth.estimateGas(gas_estimate_transaction)
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/eth.py", line 288, in estimateGas
[transaction],
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/manager.py", line 103, in request_blocking
response = self._make_request(method, params)
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/manager.py", line 86, in _make_request
return request_func(method, params)
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/middleware/gas_price_strategy.py", line 18, in middleware
return make_request(method, params)
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/middleware/formatting.py", line 21, in middleware
response = make_request(method, formatted_params)
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/middleware/attrdict.py", line 18, in middleware
response = make_request(method, params)
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/middleware/formatting.py", line 21, in middleware
response = make_request(method, formatted_params)
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/middleware/normalize_errors.py", line 9, in middleware
result = make_request(method, params)
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/middleware/validation.py", line 44, in middleware
return make_request(method, post_validated_params)
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/middleware/formatting.py", line 21, in middleware
response = make_request(method, formatted_params)
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/providers/eth_tester/middleware.py", line 315, in middleware
return make_request(method, [filled_transaction] + params[1:])
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/middleware/fixture.py", line 12, in middleware
return make_request(method, params)
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/middleware/formatting.py", line 21, in middleware
response = make_request(method, formatted_params)
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/providers/eth_tester/main.py", line 46, in make_request
response = delegator(self.ethereum_tester, params)
File "cytoolz/functoolz.pyx", line 232, in cytoolz.functoolz.curry.__call__
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/web3/providers/eth_tester/defaults.py", line 36, in call_eth_tester
return getattr(eth_tester, fn_name)(*fn_args, **fn_kwargs)
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/eth_tester/main.py", line 466, in estimate_gas
raw_gas_estimate = self.backend.estimate_gas(raw_transaction)
File "/Users/paymahn/mycro/venv/lib/python3.6/site-packages/eth_tester/utils/formatting.py", line 88, in wrapper
raise old_to_new_exceptions[type(e)] from e
eth_tester.exceptions.TransactionFailed

Python client for AWS Redis Cluster

Can anyone suggest a Python client for AWS Redis Cluster enabled?
I'm using redis-py-cluster, but it fails:
Sample code:
from rediscluster import StrictRedisCluster
startup_nodes = [{"host": "xxxx.clustercfg.apn2.cache.amazonaws.com", "port": "6379"}]
r = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True, skip_full_coverage_check=False)
r.set('foo', 'bar')
value = r.get('foo')
======
Exception:
Traceback (most recent call last):
File "testRedisCluster.py", line 11, in
r = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True, skip_full_coverage_check=False)
File "/Library/Python/2.7/site-packages/rediscluster/client.py", line 181, in init
**kwargs
File "/Library/Python/2.7/site-packages/rediscluster/connection.py", line 141, in init
self.nodes.initialize()
File "/Library/Python/2.7/site-packages/rediscluster/nodemanager.py", line 228, in initialize
need_full_slots_coverage = self.cluster_require_full_coverage(nodes_cache)
File "/Library/Python/2.7/site-packages/rediscluster/nodemanager.py", line 270, in cluster_require_full_coverage
return any(node_require_full_coverage(node) for node in nodes.values())
File "/Library/Python/2.7/site-packages/rediscluster/nodemanager.py", line 270, in
return any(node_require_full_coverage(node) for node in nodes.values())
File "/Library/Python/2.7/site-packages/rediscluster/nodemanager.py", line 267, in node_require_full_coverage
return "yes" in r_node.config_get("cluster-require-full-coverage").values()
File "/Library/Python/2.7/site-packages/redis/client.py", line 715, in config_get
return self.execute_command('CONFIG GET', pattern)
File "/Library/Python/2.7/site-packages/redis/client.py", line 668, in execute_command
return self.parse_response(connection, command_name, **options)
File "/Library/Python/2.7/site-packages/redis/client.py", line 680, in parse_response
response = connection.read_response()
File "/Library/Python/2.7/site-packages/redis/connection.py", line 629, in read_response
raise response
redis.exceptions.ResponseError: unknown command 'CONFIG'
I'm using redis-py-cluster 1.3.4.
Any idea?
Change the parameter skip_full_coverage_check=False to skip_full_coverage_check=True

Exception raised during haystack unit test

I'm using python 3.5.2, Django 1.9 and django-haystack 2.5.1.
I have some models:
class Annotation(TimeStampedModel):
... other attributes ...
entity = models.ForeignKey('another_app.Entity', blank=True, null=True)
class Entity(models.Model):
... other attributes ...
I'm using this configuration in order to override the HAYSTACK_CONNECTIONS settings variable with another one (TEST_INDEX) which redirects all tests to a different search index.
#override_settings(HAYSTACK_CONNECTIONS=TEST_INDEX, HAYSTACK_SIGNAL_PROCESSOR='haystack.signals.BaseSignalProcessor')
class SearchEnpointsTests(OurAPITestCase):
fixtures = ['test_data.json']
#classmethod
def setUpClass(cls):
super(SearchEnpointsTests, cls).setUpClass()
haystack.connections.reload('default')
call_command('update_index', interactive=False, verbosity=0)
#classmethod
def tearDownClass(cls):
return super(SearchEnpointsTests, cls).tearDownClass()
# call_command('clear_index', interactive=False, verbosity=0)
test_search(self):
...
And, as settings variables:
# haystack:
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': ELASTICSEARCH_HOST,
'INDEX_NAME': 'haystack'
}
}
TEST_INDEX = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': ELASTICSEARCH_HOST,
'INDEX_NAME': 'test_index',
},
}
Before configuring haystack real-time, it worked, now that I changed the configuration with this one:
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
It raises an exception during testing:
File "/project_folder/.venv/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 160, in __get__
rel_obj = getattr(instance, self.cache_name)
AttributeError: 'Annotation' object has no attribute '_entity_cache'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/project_folder/.venv/lib/python3.5/site-packages/django/test/testcases.py", line 1036, in setUpClass
'database': db_name,
File "/project_folder/.venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 119, in call_command
return command.execute(*args, **defaults)
File "/project_folder/.venv/lib/python3.5/site-packages/django/core/management/base.py", line 399, in execute
output = self.handle(*args, **options)
File "/project_folder/.venv/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 60, in handle
self.loaddata(fixture_labels)
File "/project_folder/.venv/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 100, in loaddata
self.load_label(fixture_label)
File "/project_folder/.venv/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 158, in load_label
obj.save(using=self.using)
File "/project_folder/.venv/lib/python3.5/site-packages/django/core/serializers/base.py", line 201, in save
models.Model.save_base(self.object, using=using, raw=True, **kwargs)
File "/project_folder/.venv/lib/python3.5/site-packages/django/db/models/base.py", line 745, in save_base
update_fields=update_fields, raw=raw, using=using)
File "/project_folder/.venv/lib/python3.5/site-packages/django/dispatch/dispatcher.py", line 192, in send
response = receiver(signal=self, sender=sender, **named)
File "/project_folder/.venv/lib/python3.5/site-packages/haystack/signals.py", line 52, in handle_save
index.update_object(instance, using=using)
File "/project_folder/.venv/lib/python3.5/site-packages/haystack/indexes.py", line 278, in update_object
backend.update(self, [instance])
File "/project_folder/.venv/lib/python3.5/site-packages/haystack/backends/elasticsearch_backend.py", line 168, in update
prepped_data = index.full_prepare(obj)
File "/project_folder/.venv/lib/python3.5/site-packages/haystack/indexes.py", line 208, in full_prepare
self.prepared_data = self.prepare(obj)
File "/project_folder/.venv/lib/python3.5/site-packages/haystack/indexes.py", line 199, in prepare
self.prepared_data[field.index_fieldname] = field.prepare(obj)
File "/project_folder/.venv/lib/python3.5/site-packages/haystack/fields.py", line 205, in prepare
return self.convert(super(CharField, self).prepare(obj))
File "/project_folder/.venv/lib/python3.5/site-packages/haystack/fields.py", line 88, in prepare
values = self.resolve_attributes_lookup(current_objects, attrs)
File "/project_folder/.venv/lib/python3.5/site-packages/haystack/fields.py", line 108, in resolve_attributes_lookup
if not hasattr(current_object, attributes[0]):
File "/project_folder/.venv/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 169, in __get__
rel_obj = qs.get()
File "/project_folder/.venv/lib/python3.5/site-packages/django/db/models/query.py", line 387, in get
self.model._meta.object_name
apps.another_app.models.DoesNotExist: Problem installing fixture '/project_folder/fixtures/test_data.json': Entity matching query does not exist.

POST request raises AssertionError

I'm doing a POST request to an API, the code looks like this:
#gen.coroutine
def call():
...
response = yield AsyncHTTPClient().fetch(
HTTPRequest(
url='https://api.mywebsite.com/v1/users',
headers=headers,
method='POST',
body=json.dumps(body),
validate_cert=False
)
)
print response, response.body
if __name__ == "__main__":
tornado.ioloop.IOLoop.current().run_sync(call)
The server responds first time with 201 Created and the second time with 200 OK.
But for that code I get this error for the first time. The second time works
Traceback (most recent call last):
File "t.py", line 49, in <module>
tornado.ioloop.IOLoop.current().run_sync(call)
File "/usr/lib/python2.7/dist-packages/tornado/ioloop.py", line 389, in run_sync
return future_cell[0].result()
File "/usr/lib/python2.7/dist-packages/tornado/concurrent.py", line 129, in result
raise_exc_info(self.__exc_info)
File "/usr/lib/python2.7/dist-packages/tornado/stack_context.py", line 302, in wrapped
ret = fn(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/tornado/gen.py", line 574, in inner
self.set_result(key, result)
File "/usr/lib/python2.7/dist-packages/tornado/gen.py", line 500, in set_result
self.run()
File "/usr/lib/python2.7/dist-packages/tornado/gen.py", line 529, in run
yielded = self.gen.throw(*exc_info)
File "t.py", line 43, in call
validate_cert=False
File "/usr/lib/python2.7/dist-packages/tornado/gen.py", line 520, in run
next = self.yield_point.get_result()
File "/usr/lib/python2.7/dist-packages/tornado/gen.py", line 409, in get_result
return self.runner.pop_result(self.key).result()
File "/usr/lib/python2.7/dist-packages/tornado/concurrent.py", line 131, in result
return super(TracebackFuture, self).result(timeout=timeout)
File "/usr/lib/python2.7/dist-packages/concurrent/futures/_base.py", line 401, in result
return self.__get_result()
File "/usr/lib/python2.7/dist-packages/concurrent/futures/_base.py", line 360, in __get_result
raise self._exception
AssertionError
Looks like you are using sync function HTTPRequest in future
from tornado.httpclient import AsyncHTTPClient
from tornado.httpclient import HTTPResponse
def call():
response = None
http_client = AsyncHTTPClient()
try:
body = json.dumps(body)
response: HTTPResponse = yield http_client.fetch('https://api.mywebsite.com/v1/users', method='POST', body=str(body), headers=headers, request_timeout=5)
except Exception as e:
print('get_request error:{0}'.format(e))

Categories