diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..f6af35f1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,107 @@ +# Custom +log/ +.vscode +allure-results/ +status-cli +test-* +*.log + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv’s lock file may be unsuitable. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.envrc +.venv +venv/ +ENV/ +env/ +ENV.bak/ +env.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000..a5258611 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,11 @@ +repos: +- repo: https://github.com/psf/black + rev: 23.7.0 + hooks: + - id: black + args: [--line-length=150] + +- repo: https://github.com/RobertCraigie/pyright-python + rev: v1.1.326 + hooks: + - id: pyright diff --git a/LICENSE-APACHE-v2 b/LICENSE-APACHE-v2 new file mode 100644 index 00000000..318c8b10 --- /dev/null +++ b/LICENSE-APACHE-v2 @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Status Research & Development GmbH + + 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. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 00000000..68faab7b --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2021 Status Research & Development GmbH + +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. diff --git a/pyrightconfig.json b/pyrightconfig.json new file mode 100644 index 00000000..c7304261 --- /dev/null +++ b/pyrightconfig.json @@ -0,0 +1,10 @@ +{ + "include": ["src", "tests"], + "reportMissingImports": true, + "reportOptionalMemberAccess": false, + "reportGeneralTypeIssues": false, + "reportInvalidStringEscapeSequence": false, + "reportWildcardImportFromLibrary": false, + "venvPath": ".", + "venv": ".venv" +} \ No newline at end of file diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 00000000..6b8314ad --- /dev/null +++ b/pytest.ini @@ -0,0 +1,8 @@ +[pytest] +addopts = -s --instafail --tb=short --color=auto +log_level = DEBUG +log_cli = True +log_file = log/test.log +log_cli_format = %(asctime)s %(name)s %(levelname)s %(message)s +log_file_format = %(asctime)s %(name)s %(levelname)s %(message)s +timeout = 300000 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..d2ea5cb5 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,41 @@ +allure-pytest==2.13.2 +allure-python-commons==2.13.2 +attrs==23.1.0 +black==24.3.0 +certifi==2023.11.17 +cfgv==3.4.0 +charset-normalizer==3.3.2 +click==8.1.7 +distlib==0.3.8 +docker==7.0.0 +execnet==2.0.2 +filelock==3.13.1 +identify==2.5.33 +idna==3.7 +iniconfig==2.0.0 +marshmallow==3.20.1 +marshmallow-dataclass==8.6.0 +mypy-extensions==1.0.0 +nodeenv==1.8.0 +packaging==23.2 +pathspec==0.12.1 +platformdirs==4.1.0 +pluggy==1.3.0 +pre-commit==3.6.2 +pyright==1.1.352 +pytest==8.0.2 +pytest-instafail==0.5.0 +pytest-rerunfailures==13.0 +pytest-timeout==2.2.0 +pytest-xdist==3.5.0 +python-dotenv==1.0.1 +pytest-dependency==0.6.0 +PyYAML==6.0.1 +requests==2.31.0 +setuptools==69.0.3 +tenacity==8.2.3 +typeguard==4.1.5 +typing-inspect==0.9.0 +typing_extensions==4.9.0 +urllib3==2.1.0 +virtualenv==20.25.0 diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/libs/__init__.py b/src/libs/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/libs/common.py b/src/libs/common.py new file mode 100644 index 00000000..51dbbe98 --- /dev/null +++ b/src/libs/common.py @@ -0,0 +1,35 @@ +from time import sleep +from src.libs.custom_logger import get_custom_logger +import os +import base64 +import allure + +logger = get_custom_logger(__name__) + + +def bytes_to_hex(byte_array): + return "".join(format(byte, "02x") for byte in byte_array) + + +def to_base64(input_data): + if isinstance(input_data, str): + input_bytes = input_data.encode() + elif isinstance(input_data, int): + input_bytes = str(input_data).encode() + elif isinstance(input_data, bytes): + input_bytes = input_data + else: + input_bytes = str(input_data).encode() + base64_encoded = base64.b64encode(input_bytes) + return base64_encoded.decode() + + +def attach_allure_file(file): + logger.debug(f"Attaching file {file}") + allure.attach.file(file, name=os.path.basename(file), attachment_type=allure.attachment_type.TEXT) + + +def delay(num_seconds): + logger.debug(f"Sleeping for {num_seconds} seconds") + sleep(num_seconds) + diff --git a/src/libs/custom_logger.py b/src/libs/custom_logger.py new file mode 100644 index 00000000..989548c5 --- /dev/null +++ b/src/libs/custom_logger.py @@ -0,0 +1,24 @@ +import logging + +max_log_line_length = 5000 + + +def log_length_filter(max_length): + class logLengthFilter(logging.Filter): + def filter(self, record): + if len(record.getMessage()) > max_length: + logging.getLogger(record.name).log( + record.levelno, f"Log line was discarded because it's longer than max_log_line_length={max_log_line_length}" + ) + return False + return True + + return logLengthFilter() + + +def get_custom_logger(name): + logging.getLogger("urllib3").setLevel(logging.WARNING) + logging.getLogger("docker").setLevel(logging.WARNING) + logger = logging.getLogger(name) + logger.addFilter(log_length_filter(max_log_line_length)) + return logger diff --git a/src/node/__init__.py b/src/node/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/node/rpc_client.py b/src/node/rpc_client.py new file mode 100644 index 00000000..0937d778 --- /dev/null +++ b/src/node/rpc_client.py @@ -0,0 +1,25 @@ +import requests +import json + +from src.libs.custom_logger import get_custom_logger + + +logger = get_custom_logger(__name__) + +class StatusNodeRPC: + def __init__(self, port): + self.base_url = f"http://127.0.0.1:{port}" + + def send_rpc_request(self, method, params=None): + if params is None: + params = [] + payload = { + "jsonrpc": "2.0", + "method": method, + "params": params, + "id": 1 + } + logger.debug(f"Sending RPC request: {json.dumps(payload)}") + response = requests.post(self.base_url, headers={"Content-Type": "application/json"}, data=json.dumps(payload)) + logger.debug(f"Received response: {response.text}") + return response.json() diff --git a/src/node/status_node.py b/src/node/status_node.py new file mode 100644 index 00000000..6a61aa2c --- /dev/null +++ b/src/node/status_node.py @@ -0,0 +1,92 @@ +import os +import subprocess +import re +import threading +import time +from tenacity import retry, stop_after_delay, wait_fixed + +from src.libs.custom_logger import get_custom_logger +from src.node.rpc_client import StatusNodeRPC + +logger = get_custom_logger(__name__) + +class StatusNode: + def __init__(self, name, port, pubkey=None): + try: + os.remove(f"{name}.log") + except: + pass + self.name = name + self.port = port + self.pubkey = pubkey + self.process = None + self.log_thread = None + self.logs = [] + + def start(self): + command = ['./status-cli', 'serve', '-n', self.name, '-p', self.port] + logger.info(f"Starting node with command: {command}") + if self.pubkey: + command += ['-a', self.pubkey] + + self.process = subprocess.Popen( + command, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True + ) + self._capture_logs() + self.api = StatusNodeRPC(self.port) + + def _capture_logs(self): + def read_output(process, logs): + while True: + line = process.stdout.readline() + if not line: + break + logs.append(line.strip()) + logger.debug(f"{self.name.upper()} - {line.strip()}") + + self.log_thread = threading.Thread(target=read_output, args=(self.process, self.logs)) + self.log_thread.start() + time.sleep(2) # Allow some time for the node to start and generate output + + def stop(self): + if self.process: + logger.info(f"Stopping node with name: {self.name}") + self.process.kill() + self.log_thread.join() # Ensure log thread finishes + + def search_logs(self, string=None, regex_pattern=None): + if string: + for log in self.logs: + if string in log: + return log + if regex_pattern: + regex = re.compile(regex_pattern) + for log in self.logs: + match = regex.search(log) + if match: + return match.group(1) + return None + + @retry(stop=stop_after_delay(10), wait=wait_fixed(0.1), reraise=True) + def get_pubkey(self): + pubkey = self.search_logs(regex_pattern=r'public key: (\b0x[0-9a-fA-F]+\b)') + assert pubkey is not None, f"{self.name}'s public key was not found." + return pubkey + + @retry(stop=stop_after_delay(10), wait=wait_fixed(0.1), reraise=True) + def wait_fully_started(self): + assert self.search_logs(string="retrieve messages...") + + def waku_info(self): + return self.api.send_rpc_request("waku_info") + + def send_contact_request(self, pubkey, message): + params = [{"id": pubkey, "message": message}] + return self.api.send_rpc_request("wakuext_sendContactRequest", params) + + def send_message(self, pubkey, message): + params = [{"id": pubkey, "message": message}] + return self.api.send_rpc_request("wakuext_sendOneToOneMessage", params) \ No newline at end of file diff --git a/src/steps/__init__.py b/src/steps/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/steps/common.py b/src/steps/common.py new file mode 100644 index 00000000..0a8442a9 --- /dev/null +++ b/src/steps/common.py @@ -0,0 +1,36 @@ + +import inspect +import pytest +from src.libs.custom_logger import get_custom_logger +from src.node.status_node import StatusNode +from datetime import datetime + +logger = get_custom_logger(__name__) + + +class StepsCommon: + @pytest.fixture(scope="class", autouse=True) + def common_setup(self): + logger.debug(f"Running fixture setup: {inspect.currentframe().f_code.co_name}") + + @pytest.fixture(scope="class", autouse=True) + def start_2_nodes(self, common_setup, request): + logger.debug(f"Running fixture setup: {inspect.currentframe().f_code.co_name}") + self.node_alice = StatusNode(name="alice", port="8545") + self.node_alice.start() + self.node_charlie = StatusNode(name="charlie", port="8565") + self.node_charlie.start() + self.node_alice.wait_fully_started() + self.node_charlie.wait_fully_started() + request.cls.alice_pubkey = self.node_alice.get_pubkey() + request.cls.node_alice = self.node_alice + request.cls.charlie_pubkey = self.node_charlie.get_pubkey() + request.cls.node_charlie = self.node_charlie + yield + self.node_alice.stop() + self.node_charlie.stop() + + def send_message_with_timestamp(self, sender_node, receiver_pubkey, message): + timestamp = datetime.now().strftime("%H:%M:%S") + sender_node.send_message(receiver_pubkey, message) + return timestamp, message \ No newline at end of file diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/test_nodes.py b/tests/test_nodes.py new file mode 100644 index 00000000..10f05118 --- /dev/null +++ b/tests/test_nodes.py @@ -0,0 +1,50 @@ +from time import sleep +from src.steps.common import StepsCommon + + +class TestNodes(StepsCommon): + + def test_one_to_one_messages(self): + num_messages = 15 # Set the number of messages to send + + # Send contact request from Charlie to Alice + self.node_charlie.send_contact_request(self.alice_pubkey, "test1") + sleep(4) + + messages = [] + + # Send messages from Charlie to Alice and from Alice to Charlie + for i in range(num_messages): + timestamp_charlie, message_charlie = self.send_message_with_timestamp(self.node_charlie, self.alice_pubkey, f"message_from_charlie_{i}") + sleep(2) + timestamp_alice, message_alice = self.send_message_with_timestamp(self.node_alice, self.charlie_pubkey, f"message_from_alice_{i}") + sleep(2) + messages.append((timestamp_charlie, message_charlie, "charlie")) + messages.append((timestamp_alice, message_alice, "alice")) + + # Validate that all messages were received + missing_messages = { + "alice": [], + "charlie": [] + } + + for timestamp, message, sender in messages: + if sender == "charlie": + log_message = f"message received: {message}" + if not self.node_alice.search_logs(log_message): + missing_messages["alice"].append((timestamp, message)) + elif sender == "alice": + log_message = f"message received: {message}" + if not self.node_charlie.search_logs(log_message): + missing_messages["charlie"].append((timestamp, message)) + + # Check for missing messages and collect assertion errors + errors = [] + if missing_messages["alice"]: + errors.append(f"Alice didn't receive the following messages from Charlie: {missing_messages['alice']}") + if missing_messages["charlie"]: + errors.append(f"Charlie didn't receive the following messages from Alice: {missing_messages['charlie']}") + + # Raise a combined assertion error if there are any missing messages + if errors: + raise AssertionError("\n".join(errors)) \ No newline at end of file