Skip to content

Commit

Permalink
[refactor] refactor with lints
Browse files Browse the repository at this point in the history
Signed-off-by: alexstroke <[email protected]>
  • Loading branch information
alexstroke authored and AlexStroke committed Dec 25, 2023
1 parent 839fab3 commit 4cbbe26
Show file tree
Hide file tree
Showing 31 changed files with 168 additions and 158 deletions.
19 changes: 11 additions & 8 deletions client_cli/pytests/common/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,26 @@
import binascii
import json
import random
import string
import re
import string

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey

from common.consts import ReservedChars, fake

def extract_hash(string):

def extract_hash(stdout):
"""
Extracts a SHA-256 hash from the given string.
:param string: The string from which to extract the hash.
:param stdout: The string from which to extract the hash.
:return: The extracted hash if found, otherwise None.
"""
if not isinstance(string, str) or not string.strip():
if not isinstance(stdout, str) or not stdout.strip():
return None
pattern = r'"([A-Fa-f0-9]{64})"'
match = re.search(pattern, string)
match = re.search(pattern, stdout)
return match.group(1) if match else None

def read_isi_from_json(file_path):
Expand All @@ -32,7 +34,7 @@ def read_isi_from_json(file_path):
:param file_path: Path to the JSON file containing ISI instruction.
:return: Dictionary with ISI instruction.
"""
with open(file_path, 'r') as file:
with open(file_path, 'r', encoding='utf-8') as file:
isi_data = json.load(file)
return isi_data

Expand All @@ -46,7 +48,7 @@ def write_isi_to_json(isi_data, file_path):
"""
if not isinstance(isi_data, list):
isi_data = [isi_data]
with open(file_path, 'w') as file:
with open(file_path, 'w', encoding='utf-8') as file:
json.dump(isi_data, file, indent=4)

def generate_random_string_with_reserved_char():
Expand Down Expand Up @@ -93,7 +95,8 @@ def generate_random_string_without_reserved_chars(length):
"""
Generate a random string with the specified length, excluding reserved characters.
"""
allowed_chars = [c for c in [*string.ascii_letters, *string.digits] if c not in ReservedChars.ALL.value]
allowed_chars = \
[c for c in [*string.ascii_letters, *string.digits] if c not in ReservedChars.ALL.value]
return generate_random_string(length, allowed_chars)


Expand Down
1 change: 1 addition & 0 deletions client_cli/pytests/common/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"""

import os

from dotenv import load_dotenv

load_dotenv()
Expand Down
1 change: 1 addition & 0 deletions client_cli/pytests/models/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""
from dataclasses import dataclass


@dataclass
class Account:
"""
Expand Down
1 change: 1 addition & 0 deletions client_cli/pytests/models/asset.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from dataclasses import dataclass


@dataclass
class AssetDefinition:
"""
Expand Down
1 change: 1 addition & 0 deletions client_cli/pytests/models/domain.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""
from dataclasses import dataclass


@dataclass
class Domain:
"""
Expand Down
2 changes: 1 addition & 1 deletion client_cli/pytests/src/client_cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
This module initializes the Iroha client and configuration using environment variables.
"""

from common.settings import PATH_CONFIG_CLIENT_CLI, PORT_MIN, PORT_MAX
from common.settings import PATH_CONFIG_CLIENT_CLI, PORT_MAX, PORT_MIN
from src.client_cli.client_cli import ClientCli
from src.client_cli.configuration import Config
from src.client_cli.iroha import Iroha
Expand Down
54 changes: 31 additions & 23 deletions client_cli/pytests/src/client_cli/client_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
"""
import shlex
import subprocess
from time import sleep, monotonic
from typing import Callable
from pathlib import Path
from time import monotonic, sleep
from typing import Callable

import allure

from common.helpers import read_isi_from_json, write_isi_to_json, extract_hash
from common.settings import PATH_CONFIG_CLIENT_CLI, CLIENT_CLI_PATH, BASE_DIR, ROOT_DIR
from common.helpers import extract_hash, read_isi_from_json, write_isi_to_json
from common.settings import (BASE_DIR, CLIENT_CLI_PATH, PATH_CONFIG_CLIENT_CLI,
ROOT_DIR)
from src.client_cli.configuration import Config


Expand Down Expand Up @@ -67,7 +68,8 @@ def wait_for(self, condition: Callable[[], bool], timeout=None):
start_time = monotonic()
while not condition():
if monotonic() - start_time > timeout:
raise TimeoutError(f"Expected condition to be satisfied after waiting for '{timeout}' seconds.")
raise TimeoutError(
f"Expected condition to be satisfied after waiting for '{timeout}' seconds.")
sleep(0.25)

def reset(self):
Expand Down Expand Up @@ -109,16 +111,14 @@ def list_all(self):
self.command.append('all')
return self

def list_filter(self, filter):
def list_filter(self, filter_criteria):
"""
Appends the 'list all' command to the command list.
:return: The current ClientCli object.
:rtype: ClientCli
Appends the 'list filter' command to the command list.
:param filter_criteria: Criteria to filter the list.
"""
self.command.append('list'),
self.command.append('list')
self.command.append('filter')
self.command.append(filter)
self.command.append(filter_criteria)
return self

def domain(self, domain: str):
Expand Down Expand Up @@ -240,39 +240,45 @@ def definition(self, asset: str, domain: str, value_type: str):

def register_trigger(self, account):
"""
Creates a JSON file for the register_trigger with a specified account and executes it using the Iroha CLI.
Creates a JSON file for the register trigger and executes it using the Iroha CLI.
:param account: The account to be used in the register_trigger.
:type account: str
"""

json_template_path = Path(BASE_DIR) / 'pytests' / 'common' / 'json_isi_examples' / 'register_trigger.json'
json_template_path = (
Path(BASE_DIR)/'pytests'/'common'/'json_isi_examples'/'register_trigger.json')
trigger_data = read_isi_from_json(str(json_template_path))
trigger_data[0]["Register"]["Trigger"]["action"]["authority"] = str(account)

json_temp_file_path = Path(ROOT_DIR) / 'isi_register_trigger.json'
write_isi_to_json(trigger_data, str(json_temp_file_path))

self._execute_pipe(['cat', str(json_temp_file_path)], [self.BASE_PATH] + self.BASE_FLAGS + ['json'])
self._execute_pipe(
['cat', str(json_temp_file_path)],
[self.BASE_PATH] + self.BASE_FLAGS + ['json'])

return self

def unregister_asset(self, asset_id):
"""
Creates a JSON file for the unregister asset with a specified object_id and executes it using the Iroha CLI.
Creates a JSON file for the unregister asset and executes it using the Iroha CLI.
:param asset_id: The object ID to be used in the unregister_asset.
:type asset_id: str
"""

json_template_path = Path(BASE_DIR) / 'pytests' / 'common' / 'json_isi_examples' / 'unregister_asset.json'
json_template_path = (
Path(BASE_DIR) /'pytests'/'common'/'json_isi_examples'/'unregister_asset.json')
asset_data = read_isi_from_json(str(json_template_path))
asset_data[0]["Unregister"]["Asset"]["object_id"] = str(asset_id)

json_temp_file_path = Path(ROOT_DIR) / 'isi_unregister_asset.json'
write_isi_to_json(asset_data, str(json_temp_file_path))

self._execute_pipe(['cat', str(json_temp_file_path)], [self.BASE_PATH] + self.BASE_FLAGS + ['json'])
self._execute_pipe(
['cat', str(json_temp_file_path)],
[self.BASE_PATH] + self.BASE_FLAGS + ['json'])

return self

Expand Down Expand Up @@ -307,15 +313,16 @@ def execute(self, command=None):
self._execute_single(command)

self.command = [self.BASE_PATH] + self.BASE_FLAGS
self.intention = None
return self

def _execute_pipe(self, cmd1, cmd2):
"""
Executes two commands connected by a pipe.
"""
with subprocess.Popen(cmd1, stdout=subprocess.PIPE) as proc1, \
subprocess.Popen(cmd2, stdin=proc1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc2:
with (subprocess.Popen(
cmd1, stdout=subprocess.PIPE) as proc1,
subprocess.Popen(
cmd2, stdin=proc1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc2):
self.stdout, self.stderr = proc2.communicate()
self.hash = extract_hash(self.stdout)
self._attach_allure_reports()
Expand All @@ -324,7 +331,8 @@ def _execute_single(self, command):
"""
Executes a single command.
"""
with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) as process:
with subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) as process:
self.stdout, self.stderr = process.communicate()
self.hash = extract_hash(self.stdout)
self._attach_allure_reports()
Expand Down Expand Up @@ -354,4 +362,4 @@ def config(self, value):
:param value: The new configuration object.
:type value: Config
"""
self._config = value
self._config = value
16 changes: 8 additions & 8 deletions client_cli/pytests/src/client_cli/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
import json
import os
import random
from urllib.parse import urlparse


class Config:
"""
Configuration class to handle Iroha network configuration. The class provides methods for loading
the configuration from a file, updating the TORII_API_URL with a random port number from the specified
Configuration class to handle Iroha network configuration.
The class provides methods for loading the configuration from a file,
updating the TORII_API_URL with a random port number from the specified
range, and accessing the configuration values.
:param port_min: The minimum port number for the TORII_API_URL.
Expand Down Expand Up @@ -44,7 +44,8 @@ def generate_by_peers(self, peers_configs_dir):
Generate configuration files for each port in the range from port_min to port_max.
"""
if self._config is None:
raise ValueError("No configuration loaded. Use load(path_config_client_cli) to load the configuration.")
raise ValueError(
"No configuration loaded. Use load() method to load the configuration.")

if self.port_min >= self.port_max:
raise ValueError("port_min must be less than port_max.")
Expand All @@ -66,14 +67,13 @@ def select_random_peer_config(self):
:return: None
"""
peers_configs = glob.glob('path/to/peers/configs/*.json') # Replace with the actual directory path
peers_configs = glob.glob('path/to/peers/configs/*.json')
if not peers_configs:
raise ValueError("Peer configuration files not found. First generate them using generate_by_peers.")
raise ValueError(
"Peer configuration files not found. First generate them using generate_by_peers.")

# Select a random configuration file
chosen_config_file = random.choice(peers_configs)

# Use the load method to load the selected configuration
self.load(chosen_config_file)

@property
Expand Down
24 changes: 17 additions & 7 deletions client_cli/pytests/src/client_cli/have.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,20 @@
"""

import json

import allure

from src.client_cli import client_cli, iroha, match


def expected_in_actual(expected, actual) -> bool:
"""
Check if the expected result is present in the actual result.
:param expected: The expected result.
:param actual: The actual result.
:return: True if expected is in actual, False otherwise.
"""
allure.attach(
json.dumps(actual),
name='actual',
Expand All @@ -28,7 +36,7 @@ def domain(expected, owned_by=None):
:param expected: The expected domain object.
:param owned_by: The owner of the domain, default is None.
:return: True if the domain is present (and owned by the specified owner if provided), False otherwise.
:return: True if the domain is present and owned by the specified owner if provided.
"""

def domain_in_domains() -> bool:
Expand Down Expand Up @@ -70,7 +78,9 @@ def asset_definition(expected):
expected_domain = expected.split('#')[1]

def asset_definition_in_asset_definitions() -> bool:
asset_definitions = iroha.list_filter(f'{{"Identifiable": {{"Is": "{expected_domain}"}}}}').asset_definitions()
asset_definitions = (
iroha.list_filter(
f'{{"Identifiable": {{"Is": "{expected_domain}"}}}}').asset_definitions())
return expected_in_actual(expected, asset_definitions)

return client_cli.wait_for(asset_definition_in_asset_definitions)
Expand Down Expand Up @@ -100,15 +110,15 @@ def asset_has_quantity(expected_asset_id, expected_quantity):
"""

def check_quantity() -> bool:
assets = iroha.list_filter(f'{{"Identifiable": {{"Is": "{expected_asset_id}"}}}}').assets()
assets = iroha.list_filter(
f'{{"Identifiable": {{"Is": "{expected_asset_id}"}}}}').assets()
actual_quantity = None
for asset in assets:
if asset == expected_asset_id:
for asset_item in assets:
if asset_item == expected_asset_id:
actual_quantity = assets.get(expected_asset_id, {})["value"]["Quantity"]
break

if actual_quantity is None:
raise Exception(f"Asset with ID {expected_asset_id} not found.")
raise ValueError(f"Asset with ID {expected_asset_id} not found.")

allure.attach(
json.dumps(actual_quantity),
Expand Down
13 changes: 3 additions & 10 deletions client_cli/pytests/src/client_cli/iroha.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@

import json
from typing import Dict, List
from src.client_cli.client_cli import ClientCli, Config

from src.client_cli.client_cli import ClientCli


class Iroha(ClientCli):
Expand All @@ -13,14 +14,6 @@ class Iroha(ClientCli):
for interacting with the Iroha network.
"""

def __init__(self, config: Config):
"""
:param config: A configuration object containing the details for the client.
:type config: Config
:param path: The path where the client executable is located.
:type path: str
"""
super().__init__(config)

def _execute_command(self, command_name: str):
"""
Expand All @@ -42,7 +35,7 @@ def should(self, *args, **kwargs):
"""
return self

def should_not(func):
def should_not(self, func):
"""
Decorator that inverts the result of the check function.
Expand Down
1 change: 1 addition & 0 deletions client_cli/pytests/src/client_cli/match.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import allure


def client_cli_have_error(expected: str, actual: str):
"""
Checks if the command-line client has the expected error.
Expand Down
Loading

0 comments on commit 4cbbe26

Please sign in to comment.