-
Notifications
You must be signed in to change notification settings - Fork 21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Mypy error fixes #159
Mypy error fixes #159
Changes from 2 commits
49546dd
72ca5f4
6f662e3
a915a78
2dcaf2a
fdb4f5d
899d438
e7e9b66
c422b14
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,4 @@ | ||
from typing import List, Dict, Any | ||
from typing import List, Dict, Any, Union | ||
from csle_common.dao.docker.docker_container_metadata import DockerContainerMetadata | ||
from csle_common.dao.emulation_config.emulation_env_config import EmulationEnvConfig | ||
from csle_common.dao.emulation_config.kafka_config import KafkaConfig | ||
|
@@ -11,7 +11,7 @@ class DockerEnvMetadata(JSONSerializable): | |
""" | ||
|
||
def __init__(self, containers: List[DockerContainerMetadata], name: str, subnet_prefix: str, | ||
subnet_mask: str, level: str, config: EmulationEnvConfig, kafka_config: KafkaConfig): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Kafka config None går inte att undvika här, men config bör vi nog inte tillåta vara None. Uppdatera även to_dict och from_dict i docker_env_metadata så att de inte failar om kafka_config är None |
||
subnet_mask: str, level: str, config: Union[None, EmulationEnvConfig], kafka_config: Union[None, KafkaConfig]): | ||
""" | ||
Initializes the DTO | ||
|
||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nästan alla list-funktioner i metastorefacade går felmeddelandet att dom returnerar List[Tuple[Any, ...]] när dom ska returnera List[ClassConfigObject],. Eftersom jag har mockat alla fuinktioner efter den type-hintinhen är jag inte säker på att det rätt att ändra till List[Tuple[Any, ...]] på dom funktionerna? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. såhär tycker mypy att det ska se ut på dessa sorters funktioner, vilket då inte stämmer överens med hur jag mockat. Ska jag köra på det iallafall? |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -71,7 +71,7 @@ def list_emulations_ids() -> List[Tuple]: | |
return records | ||
|
||
@staticmethod | ||
def get_emulation_by_name(name: str) -> Union[None, EmulationEnvConfig]: | ||
def get_emulation_by_name(name: Union[None, str]) -> Union[None, EmulationEnvConfig]: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Lägg bara till Union[None, originalType] om koden fungerar med None. I denna metoden, vill vi tillåta None? Antagligen inte, det är inte rimligt att hämta emulation_by_name på None. Då är det nog bättre att ha kvar name: str och försöka undvika None genom att lägga till "if name is not None, get_emulation_by_name(name)" och skicka ett exception om det är None där denna funktionen anropas |
||
""" | ||
Function for extracting the metadata of an emulation with a given name | ||
|
||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Vet inte om det var såhär du menade? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ja |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -23,7 +23,7 @@ def parse_runnning_emulation_infos() -> List[DockerEnvMetadata]: | |
client_1 = docker.from_env() | ||
client_2 = docker.APIClient(base_url=constants.DOCKER.UNIX_DOCKER_SOCK_URL) | ||
parsed_containers = DockerUtil.parse_running_containers(client_1=client_1, client_2=client_2) | ||
emulations = list(set(list(map(lambda x: x.emulation, parsed_containers)))) | ||
emulations: List[Union[None, str]] = list(set(list(map(lambda x: x.emulation, parsed_containers)))) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Samma här, antagligen vill vi inte tillåta None. Det du kan göra är att filtrera listen för None först eller försök hitta roten till problemet där någonstans returneras None (antagligen i ett externt bibliotek) och där vill vi ha en if-statement/exception om det är None för att undvika att lägga till None i vår kod där det inte ska vara None. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Vill vi att det exception ska vara inne i init i den klassen isf? Typ: There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. oh nvm såg din kommentar ovan |
||
parsed_envs = DockerUtil.parse_running_emulation_envs(emulations=emulations, containers=parsed_containers) | ||
return parsed_envs | ||
|
||
|
@@ -72,7 +72,7 @@ def parse_stopped_containers(client_1, client2) -> List[DockerContainerMetadata] | |
return parsed_containers | ||
|
||
@staticmethod | ||
def parse_running_emulation_envs(emulations: List[str], containers: List[DockerContainerMetadata]) \ | ||
def parse_running_emulation_envs(emulations: List[Union[None, str]], containers: List[DockerContainerMetadata]) \ | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Vill nog inte tillåta None här |
||
-> List[DockerEnvMetadata]: | ||
""" | ||
Queries docker to get a list of all active emulation environments | ||
|
@@ -180,7 +180,7 @@ def get_docker_gw_bridge_ip(container_id: str) -> str: | |
containers = docker_gw_bridge_info[constants.DOCKER.CONTAINERS_KEY] | ||
if container_id in containers: | ||
container = containers[container_id] | ||
ip = container[constants.DOCKER.IPV4_KEY] | ||
ip: str = container[constants.DOCKER.IPV4_KEY] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Bra |
||
ip = ip.split("/")[0] | ||
return ip | ||
raise ValueError(f"The container with id:{container_id} does not have an IP in the docker gw bridge network. " | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,4 @@ | ||
from typing import Tuple, Dict, Any | ||
from typing import Tuple, Dict, Any, Union, List | ||
import io | ||
import csv | ||
import json | ||
|
@@ -40,13 +40,13 @@ def get_dir_size_gb(dir_path: str = '.') -> float: | |
:param dir_path: the path to the directory | ||
:return: the size of the directory in GB | ||
""" | ||
total = 0 | ||
total = 0.0 | ||
with os.scandir(dir_path) as it: | ||
for entry in it: | ||
if entry.is_file(): | ||
total += entry.stat().st_size | ||
elif entry.is_dir(): | ||
total += ExportUtil.get_dir_size(entry.path) | ||
total += ExportUtil.get_dir_size_gb(entry.path) | ||
return round((float(total) / 1000000000), 2) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Bra |
||
|
||
@staticmethod | ||
|
@@ -87,6 +87,8 @@ def export_emulation_traces_to_disk_json(num_traces_per_file: int, output_dir: s | |
Logger.__call__().get_logger().info(f"Reading trace {i}/{len(emulation_traces_ids)} from the metastore, " | ||
f"trace id: {id_obj[0]}") | ||
tr = MetastoreFacade.get_emulation_trace(id=id_obj[0]) | ||
if tr is None: | ||
raise ValueError("Tr is none and thus has no modules") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Bra, men använd alltid deskiptiva variabel namn. I testcases var det ok med lite abbreviations, men inte i main-koden. Dvs det ska inte vara tr utan "trace" i detta fallet. https://readlearncode.com/code-and-stuff/clean-code-variables/ |
||
if num_attributes_per_time_step == -1: | ||
num_attributes_per_time_step = tr.num_attributes_per_time_step() | ||
if schema is None: | ||
|
@@ -111,7 +113,7 @@ def export_emulation_traces_to_disk_json(num_traces_per_file: int, output_dir: s | |
num_traces = len(emulation_traces_ids) | ||
with io.open(f"{output_dir}{constants.COMMANDS.SLASH_DELIM}{constants.DATASETS.METADATA_FILE_NAME}", 'w', | ||
encoding='utf-8') as f: | ||
metadata_dict = {} | ||
metadata_dict: Dict[str, Any] = {} | ||
metadata_dict[constants.DATASETS.FILE_FORMAT_PROPERTY] = file_format | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Bra |
||
metadata_dict[constants.DATASETS.NUM_TRACES_PROPERTY] = num_traces | ||
metadata_dict[constants.DATASETS.NUM_ATTRIBUTES_PER_TIME_STEP_PROPERTY] = num_attributes_per_time_step | ||
|
@@ -138,7 +140,7 @@ def extract_emulation_traces_dataset_metadata(dir_path: str, zip_file_path: str) | |
file_format = "unknown" | ||
added_by = "unknown" | ||
num_traces = -1 | ||
schema = "" | ||
schema = {} | ||
columns = "" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Bra |
||
num_traces_per_file = -1 | ||
num_attributes_per_time_step = -1 | ||
|
@@ -173,7 +175,7 @@ def extract_emulation_traces_dataset_metadata(dir_path: str, zip_file_path: str) | |
if constants.DATASETS.COLUMNS_PROPERTY in metadata_dict: | ||
columns = metadata_dict[constants.DATASETS.COLUMNS_PROPERTY] | ||
else: | ||
columns = [] | ||
columns = "" | ||
|
||
num_files = len([name for name in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, name))]) - 1 | ||
size_compressed_gb = round(float(os.path.getsize(zip_file_path)) / 1000000000, 2) | ||
|
@@ -213,10 +215,12 @@ def export_emulation_traces_to_disk_csv( | |
file_name = f"{file_id}.csv" | ||
last_export = 0 | ||
num_attributes_per_time_step = -1 | ||
columns = None | ||
columns: Union[List[Union[str, int, float]], None]= None | ||
for i, id_obj in enumerate(emulation_traces_ids): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Bra |
||
Logger.__call__().get_logger().info(f"Reading trace {i}/{len(emulation_traces_ids)} from the metastore") | ||
tr = MetastoreFacade.get_emulation_trace(id=id_obj[0]) | ||
if tr is None: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. trace inte tr |
||
raise ValueError("tr is None and thus has no modules/attributes") | ||
tr_values, tr_labels = tr.to_csv_record(max_time_steps=max_time_steps, max_nodes=max_nodes, | ||
max_ports=max_ports, max_vulns=max_vulns, null_value=null_value) | ||
if num_attributes_per_time_step == -1: | ||
|
@@ -240,7 +244,7 @@ def export_emulation_traces_to_disk_csv( | |
num_traces = len(emulation_traces_ids) | ||
with io.open(f"{output_dir}{constants.COMMANDS.SLASH_DELIM}{constants.DATASETS.METADATA_FILE_NAME}", 'w', | ||
encoding='utf-8') as f: | ||
metadata_dict = {} | ||
metadata_dict: Dict[str, Any] = {} | ||
metadata_dict[constants.DATASETS.FILE_FORMAT_PROPERTY] = file_format | ||
metadata_dict[constants.DATASETS.NUM_TRACES_PROPERTY] = num_traces | ||
metadata_dict[constants.DATASETS.NUM_ATTRIBUTES_PER_TIME_STEP_PROPERTY] = num_attributes_per_time_step | ||
|
@@ -270,6 +274,8 @@ def export_emulation_statistics_to_disk_json(output_dir: str, zip_file_output: s | |
if not os.path.exists(output_dir): | ||
os.makedirs(output_dir) | ||
emulation_statistic = MetastoreFacade.get_emulation_statistic(id=statistics_id) | ||
if emulation_statistic is None: | ||
raise ValueError("emulation_statistic is None and thus has no modules/attributes") | ||
file_name = "statistics.json" | ||
Logger.__call__().get_logger().info(f"Exporting statistics with id {statistics_id} to file: {file_name}") | ||
emulation_statistic.compute_descriptive_statistics_and_distributions() | ||
|
@@ -278,14 +284,14 @@ def export_emulation_statistics_to_disk_json(output_dir: str, zip_file_output: s | |
metrics = ",".join(emulation_statistic.metrics) | ||
conditions = ",".join(emulation_statistic.conditions) | ||
num_conditions = emulation_statistic.num_conditions | ||
statistics_dict = emulation_statistic.to_dict() | ||
statistics_dict: Dict[str, Any] = emulation_statistic.to_dict() | ||
statistics_dict = json.dumps(statistics_dict, indent=4, sort_keys=True) | ||
with io.open(f"{output_dir}{constants.COMMANDS.SLASH_DELIM}{file_name}", 'w', encoding='utf-8') as f: | ||
f.write(statistics_dict) | ||
file_format = "json" | ||
with io.open(f"{output_dir}{constants.COMMANDS.SLASH_DELIM}{constants.DATASETS.METADATA_FILE_NAME}", 'w', | ||
encoding='utf-8') as f: | ||
metadata_dict = {} | ||
metadata_dict: Dict[str, Any] = {} | ||
metadata_dict[constants.DATASETS.FILE_FORMAT_PROPERTY] = file_format | ||
metadata_dict[constants.DATASETS.NUM_MEASUREMENTS_PROPERTY] = num_measurements | ||
metadata_dict[constants.DATASETS.NUM_CONDITIONS_PROPERTY] = num_conditions | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,15 +3,15 @@ | |
from csle_common.metastore.metastore_facade import MetastoreFacade | ||
from csle_common.dao.system_identification.emulation_statistics import EmulationStatistics | ||
from csle_common.dao.emulation_config.emulation_trace import EmulationTrace | ||
|
||
from typing import Union | ||
|
||
class ImportUtil: | ||
""" | ||
Class with utility functions for importing data to the metastore | ||
""" | ||
|
||
@staticmethod | ||
def import_emulation_statistics_from_disk_json(input_file: str, emulation_name: str = None) -> None: | ||
def import_emulation_statistics_from_disk_json(input_file: str, emulation_name: Union[str, None] = None) -> None: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Bra |
||
""" | ||
Imports emulation statistics from disk to the metastore | ||
|
||
|
@@ -30,7 +30,7 @@ def import_emulation_statistics_from_disk_json(input_file: str, emulation_name: | |
f"input file:{input_file}") | ||
|
||
@staticmethod | ||
def import_emulation_traces_from_disk_json(input_file: str, emulation_name: str = None) -> None: | ||
def import_emulation_traces_from_disk_json(input_file: str, emulation_name: Union[str, None] = None) -> None: | ||
""" | ||
Imports emulation traces from disk to the metastore | ||
|
||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Samma fall här, försök undvika None typer.
Jag gissar att mypy klagar för att någonstans anropas DockerContainerMetadata() med värden som kan vara None. För att ta bort det error utan att lägga till None typer kan du lägga till en exception/if-statement innan DockerContainerMetadata() anropas för att kolla efter None värden.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sjävklart på alla ställen där vi redan har initialsierat argumenten till None så kan du lägga till None Union-typen. Men försök undvika att lägga till None typer på ställen där vi inte har kodat redan för att hantera None, då är det bättre att bara lägga in en exception eller if-case.