How to test store_items function mocking Object
def store_items(self):
items_json = json.dumps(self.items, default=self.serialize_date).encode("utf-8")
self.algorithm.ObjectStore.SaveBytes(self.trade_planning_key, items_json)
self.algorithm.Debug(f"Stored {len(self.items)} items in ObjectStore under tag '{self.trade_planning_key}'.")Example
import unittest
from unittest.mock import MagicMock
def setUp(self):
self.algorithm = MagicMock()
self.object_storage = ObjectStorageManagement(self.algorithm)
self.mock_data = [
{
"Rank": 1,
"EffectiveDate": "2023-01-01",
Mia Alissi
To test the
store_itemsfunction, you can use Python'sunittest.mockmodule to create a mock object forself.algorithm.ObjectStore. This allows you to simulate the behavior of theObjectStorewithout needing to interact with the actual ObjectStore.Here's an example of how you can do this:
In this example, we're using the
patchdecorator to mock thejson.dumpsandObjectStore.SaveBytesmethods. We then check that these methods were called with the expected arguments.Please note that this is a general Python unit testing approach. The actual implementation may vary depending on the specifics of your
ObjectStorageManagementclass andserialize_datemethod.For more information on how to use the ObjectStore in QuantConnect, you can refer to the QuantConnect documentation.
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
Dharmesh Khalasi
FAILED [100%]items_json (raw): <MagicMock name='mock.ObjectStore.Read()' id='2568337609328'>
test_object_store.py:30 (TestObjectStorageManagement.test_store_items)
self = <test_object_store.TestObjectStorageManagement testMethod=test_store_items>
def setUp(self):
self.algorithm = MagicMock()
> self.object_storage = ObjectStorageManagement(self.algorithm)
test_object_store.py:11:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
object_store.py:9: in __init__
self.items = self.load_items()
object_store.py:15: in load_items
res = json.loads(items_json)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
s = <MagicMock name='mock.ObjectStore.Read()' id='2568337609328'>, cls = None
object_hook = None, parse_float = None, parse_int = None, parse_constant = None
object_pairs_hook = None, kw = {}
def loads(s, *, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
Mia Alissi
The error message indicates that the
json.loadsfunction is trying to parse a MagicMock object, which it can't do. This is likely because theObjectStore.Readmethod is being called somewhere in yourload_itemsmethod and it's returning a MagicMock instead of a JSON string.To fix this, you need to set a return value for
ObjectStore.Readin your test setup. Here's an example of how you can do this:In this example,
ObjectStore.Readwill return a JSON string ofself.mock_datawhen it's called. This should allowjson.loadsto parse the returned value correctly.Please note that this is a general Python unit testing approach. The actual implementation may vary depending on the specifics of your
ObjectStorageManagementclass andload_itemsmethod.For more information on how to use the ObjectStore in QuantConnect, you can refer to the QuantConnect documentation.
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
Dharmesh Khalasi
thing = <class 'object_store.ObjectStorageManagement'>, comp = 'algorithm'
import_path = 'object_store.ObjectStorageManagement.algorithm'
def _dot_lookup(thing, comp, import_path):
try:
return getattr(thing, comp)
except AttributeError:
> __import__(import_path)
E ModuleNotFoundError: No module named 'object_store.ObjectStorageManagement'; 'object_store' is not a package
Mia Alissi
The error message indicates that Python is unable to find a module named 'object_store.ObjectStorageManagement'. This could be due to several reasons:
The file
object_store.pyis not in the same directory as the script you are running. Python needs to be able to find this file in order to import theObjectStorageManagementclass from it.The
object_storedirectory does not contain an__init__.pyfile. This file is required for Python to recognize the directory as a package.The
ObjectStorageManagementclass does not exist in theobject_store.pyfile. Make sure the class is defined in this file and that it's spelled correctly.Here's an example of how you can import the
ObjectStorageManagementclass ifobject_store.pyis in the same directory as your script:If
object_store.pyis in a different directory, you'll need to add that directory to the Python path:Replace '/path/to/directory' with the actual path to the directory containing
object_store.py.Please note that this is a general Python import issue. The actual solution may vary depending on your project structure and environment.
For more information on how to use the ObjectStore in QuantConnect, you can refer to the QuantConnect documentation.
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
Dharmesh Khalasi
I am running the test case locally on my machine. How to setup Python project on Pycharm IDE so I can run test cases locally
Mia Alissi
To set up a Python project on PyCharm IDE and run test cases locally, you can follow these steps:
Open PyCharm and create a new project or open an existing one.
Make sure you have the Professional edition of PyCharm as it supports remote debugging functionality which is required for local debugging with QuantConnect's LEAN engine.
Set up local autocomplete for Python in PyCharm. Open a project directory, generated by the CLI, with PyCharm and wait for the project to load. Wait for PyCharm to index all packages and autocomplete starts working. Update your project to include the required imports (source).
To debug your Python algorithms locally in PyCharm, follow these steps as mentioned in the QuantConnect Documentation:
lean backtestcommand with the--debug pycharmoption.For running test cases, you can use Python's built-in
unittestmodule. In PyCharm, you can right-click on the test file or the directory containing the test files and select 'Run Unittests in...'.Please note that this is a general guide for setting up a Python project in PyCharm and running test cases. The actual steps may vary depending on your specific project and test cases.
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
Dharmesh Khalasi
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!